Discord.js开发报错:ReferenceError: channel is not defined 问题求助(附嵌入消息测试代码)
解决Discord机器人Embed消息的ReferenceError: channel is not defined错误
嘿,我帮你找出问题所在啦!你碰到的ReferenceError: channel is not defined错误,原因很简单——你在代码里直接调用了channel.send(),但channel这个变量根本没被定义过。
在Discord.js的message事件回调函数里,当用户发送消息触发事件时,我们可以通过传入的message对象获取到当前消息所在的频道,也就是message.channel。你只需要把原来的channel.send(exampleEmbed);改成message.channel.send(exampleEmbed);就能解决这个问题啦。
下面是修正后的完整代码:
client.on('message', (message) => { console.log(`[${message.author.tag}]: ${message.content}`); if (message.content === 'brh!testembed') { const exampleEmbed = new Discord.MessageEmbed() .setColor('#0099ff') .setTitle('Some title') .setURL('https://discord.js.org/') .setAuthor('Some name', 'https://i.imgur.com/wSTFkRM.png', 'https://discord.js.org') .setDescription('Some description here') .setThumbnail('https://i.imgur.com/wSTFkRM.png') .addFields( { name: 'Regular field title', value: 'Some value here' }, { name: '', value: '' }, { name: 'Inline field title', value: 'Some value here', inline: true }, { name: 'Inline field title', value: 'Some value here', inline: true }, ) .addField('Inline field title', 'Some value here', true) .setImage('https://i.imgur.com/wSTFkRM.png') .setTimestamp() .setFooter('Some footer text here', 'https://i.imgur.com/wSTFkRM.png'); // 这里把channel改成message.channel message.channel.send(exampleEmbed); } });
另外给你两个小提示:
- 如果你用的是Discord.js v14及以上版本,
MessageEmbed已经被替换成EmbedBuilder了,要是之后碰到相关报错,可以考虑改成new Discord.EmbedBuilder()。 - 测试的时候记得确认机器人在目标频道里有发送消息和嵌入链接的权限,不然可能会出现新的权限相关错误哦。
内容的提问来源于stack exchange,提问作者JoeSchmoe69
相关产品推荐
相关产品推荐

