Discord JS中无法获取请求响应值,Embed消息无法正常显示
问题分析与修复方案
核心问题
你的代码存在三个关键问题:
- 异步时序错误:
util.status是异步方法,.then()回调内的代码会在异步操作完成后才执行,但你在回调外直接调用interaction.channel.send(embed),此时embed还未被定义,自然无法正常传递值。 - 变量作用域问题:
embed被定义在.then()的回调函数内部,外部作用域无法访问到这个变量。 - 未定义变量:
online变量没有赋值,应该对应result.players.online。
修复后的代码
使用async/await替代.then(),让异步代码的执行逻辑更直观,同时解决作用域和时序问题:
async execute(interaction) { const ip = interaction.options.getString('server-ip'); const port = interaction.options.getString('port'); // 用await等待异步操作完成,直接获取result const result = await util.status(ip, parseInt(port)); const embed = new EmbedBuilder() .setThumbnail('attachment://favicon.png') .setColor('#BFCDEB') .setTitle('Mc server status') .addFields( { name: 'Players Online', value: result.players.online.toString() }, // 修正online变量,转字符串避免类型错误 { name: 'Max Player Cap', value: result.players.max.toString() }, { name: 'Server Version', value: result.version.name }, { name: 'MOTD', value: result.motd.clean }, { name: 'Ping (from proxies like bungee/waterfall)', value: result.roundTripLatency.toString(), } ) .setFooter('MC Server Checker'); // 确保embed创建完成后再发送消息,Discord.js v14+需用embeds数组传递 await interaction.channel.send({ embeds: [embed] }); }
额外注意点
- Discord.js v14及以上版本中,发送嵌入消息必须通过
{ embeds: [embed] }的格式传递,不能直接传入embed。 - 数字类型的字段值需要转为字符串(
.toString()),因为Embed的value要求是字符串类型,否则会抛出类型错误。
内容的提问来源于stack exchange,提问作者Ashiq Tasdid
相关产品推荐
相关产品推荐

