Discord机器人无法识别用户反应问题求助
解决Discord机器人无法识别用户反应的问题
你的代码核心问题是过滤条件的用户ID对比逻辑错误:
你在filter中把user.id(字符串类型的用户ID)直接和interaction.options.getUser('user')(User对象)做比较,两者类型不匹配,导致过滤条件永远不成立,自然无法识别目标用户的反应。
修改步骤:
- 提前获取并存储目标用户对象,避免重复调用API:
const targetUser = interaction.options.getUser('user'); let username = `${targetUser}`;
- 修正filter中的用户判断逻辑,用用户ID字符串做对比:
const filter = (reaction, user) => { return ['✅', '❌'].includes(reaction.emoji.name) && user.id === targetUser.id; };
完整修改后的代码:
module.exports = { data: new SlashCommandBuilder() .setName('chess') .setDescription('Starts a game of chess with a specified user') .addUserOption(option => option.setName("user") .setDescription("User to play") .setRequired(true)), async execute(interaction) { // 修正异步操作顺序,确保延迟回复完成后再删除 await interaction.deferReply({ ephemeral: true }); await interaction.deleteReply(); const targetUser = interaction.options.getUser('user'); let username = `${targetUser}`; const message = await interaction.channel.send(`${interaction.user} challenges ` + username); await message.react('✅'); await message.react('❌'); const filter = (reaction, user) => { return ['✅', '❌'].includes(reaction.emoji.name) && user.id === targetUser.id; }; message.awaitReactions({ filter, max: 1, time: 40000, errors: ['time'] }) .then(collected => { const reaction = collected.first(); if (reaction.emoji.name === '✅') interaction.channel.send(username + ' accepted.'); else interaction.channel.send(username + ' declined.'); }) .catch(() => { interaction.channel.send(username + ' has not responded and has timed out.'); }); } }
额外优化:
- 给
deferReply加上ephemeral: true,让临时回复只对命令发起者可见,更友好 - 把
message.react改成await链式调用,确保表情按顺序添加
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

