Discord JS交互中等待用户消息并获取内容的问题排查
解决Discord.js中awaitMessages返回undefined的问题
你的代码出现undefined的核心原因有两个:一是没有过滤消息来源,可能收集到不符合预期的消息集合;二是未正确处理交互的超时限制,同时在高版本Discord.js中awaitMessages已被废弃,容易引发兼容性问题。以下是修复方案:
修复后的代码(兼容v12及以下)
// 确保在async函数中执行 if (interaction.customId === 'voice_mute') { // 先回复交互,避免Discord的3秒超时限制 await interaction.deferReply({ ephemeral: true }); await interaction.followUp({ content: "Mention an user with `@`...", ephemeral: false }); // 只收集发起交互的用户的消息 const filter = msg => msg.author.id === interaction.user.id; try { const collected = await interaction.channel.awaitMessages({ filter, max: 1, time: 30000, errors: ['time'] }); const targetMsg = collected.first(); // 现在控制台能正确输出消息内容 console.log(targetMsg.content); if (targetMsg.content.startsWith("@")) { await targetMsg.channel.send(`Correct`); } else { await targetMsg.channel.send("Invalid"); } } catch (err) { await interaction.channel.send('Timeout'); } }
高版本Discord.js(v13+)推荐方案(使用MessageCollector)
awaitMessages在v13后已被废弃,官方推荐使用MessageCollector:
if (interaction.customId === 'voice_mute') { await interaction.deferReply({ ephemeral: true }); await interaction.followUp({ content: "Mention an user with `@`...", ephemeral: false }); const filter = msg => msg.author.id === interaction.user.id; const collector = interaction.channel.createMessageCollector({ filter, time: 30000, max: 1 }); collector.on('collect', (targetMsg) => { console.log(targetMsg.content); if (targetMsg.content.startsWith("@")) { targetMsg.channel.send(`Correct`); } else { targetMsg.channel.send("Invalid"); } collector.stop(); }); collector.on('end', (_, reason) => { if (reason === 'time') { interaction.channel.send('Timeout'); } }); }
关键修复点说明
- 添加消息过滤:通过
filter确保只收集发起交互的用户的消息,避免频道内其他用户的消息干扰,同时保证收集到的消息是目标用户的输入。 - 处理交互超时:必须先调用
deferReply或reply回复Discord交互,否则会触发3秒超时错误,导致后续代码执行异常。 - 变量命名规范:避免重复使用
message变量覆盖集合对象,改用targetMsg等明确名称,防止作用域混淆。
内容的提问来源于stack exchange,提问作者jksnDev
相关产品推荐
相关产品推荐

