Discord.js MESSAGE_REFERENCE_UNKNOWN_MESSAGE错误求助
解决Discord.js中的MESSAGE_REFERENCE_UNKNOWN_MESSAGE错误
错误原因
这个错误的核心逻辑是:使用message.reply()时,Discord.js会自动将回复关联到触发命令的原消息。如果原消息已被删除、机器人无权限读取该消息,或者消息ID无效,Discord API会返回MESSAGE_REFERENCE_UNKNOWN_MESSAGE错误——因为它找不到要引用的目标消息。
从你的错误日志能看到,请求体中的message_reference默认设置了fail_if_not_exists: true,这是message.reply()的默认行为:一旦引用的消息不存在,直接触发报错。
解决方案
有两种直接修复方式,可根据需求选择:
方式1:改用普通消息发送(不关联原消息)
如果不需要回复关联原消息,直接用message.channel.send()替代message.reply(),彻底避免消息引用逻辑:
// 修改错误提示部分 if (!voiceChannel || voiceChannel.type !== 'GUILD_VOICE') { return message.channel.send("Could not find the target voice channel."); } // 修改catch块内的错误提示 await message.channel.send('There was an error renaming the voice channel.');
方式2:保留回复样式但允许引用不存在的消息
如果需要保留回复的格式(消息显示为回复原消息的样式),可手动配置message.reply()的参数,将failIfNotExists设为false,这样即使原消息不存在,机器人仍能发送回复:
// 修改错误提示的回复 if (!voiceChannel || voiceChannel.type !== 'GUILD_VOICE') { return message.reply({ content: "Could not find the target voice channel.", failIfNotExists: false }); } // 修改catch块内的回复 await message.reply({ content: 'There was an error renaming the voice channel.', failIfNotExists: false });
额外检查项
确保机器人拥有读取消息历史的权限,否则即便原消息存在,机器人也无法获取到它,仍会触发该错误。
修改后的完整代码
const channelId = '1293020925058355240'; const voiceChannel = message.guild.channels.cache.get(channelId); if (!voiceChannel || voiceChannel.type !== 'GUILD_VOICE') { return message.channel.send("Could not find the target voice channel."); } // Increment the order counter orderCounter++; const newChannelName = `Orders: ${orderCounter}`; try { await voiceChannel.setName(newChannelName); await message.channel.send({ content: `The Order count is updated! It’s now a total of **${orderCounter}** Orders || Updated by <@${message.author.id}>` }); } catch (error) { // Log the error to the console for debugging console.error('Error renaming the voice channel:', error); // Send an error message in the text channel await message.channel.send('There was an error renaming the voice channel.'); }
内容的提问来源于stack exchange,提问作者Amit
相关产品推荐
相关产品推荐

