discord.js messageReactionAdd事件无法正确匹配识别反应emoji
问题排查与修复方案
核心错误原因
1. 表情匹配逻辑类型错误
reaction.emoji返回的是discord.js的Emoji类实例,不是字符串,直接和Unicode表情字符串做全等判断永远不成立,这是代码始终进入else分支的最主要原因,需要改为读取reaction.emoji.name属性进行匹配。
2. 代码块括号位置错误
当前代码中,你把所有用户校验、表情匹配逻辑都放在了if (reaction.partial)的判断块内,只有当反应是partial类型时才会执行后续逻辑,如果反应不是partial类型,所有匹配逻辑都不会运行,直接跳过。
3. 异步逻辑处理错误
频道创建是异步操作,你创建分类后立刻从缓存读取,大概率读取不到刚创建的分类,需要用await接收创建结果。
修复后代码
bot.on('messageReactionAdd', async (reaction, user) => { const message = reaction.message // 处理partial反应,单独闭合代码块 if (reaction.partial) { try { await reaction.fetch(); } catch (error) { console.error('Something went wrong when fetching the message: ', error); return; } } // 这里补上partial判断的闭合括号,后续逻辑放在外面 if(user.bot) return; // 改为匹配emoji.name if(reaction.emoji.name === "🤖"){ reaction.message.channel.send("Right emoji") // 先判断反应是否存在再操作,避免报错 const robotReaction = reaction.message.reactions.cache.get("🤖") robotReaction && robotReaction.users.remove(user); reaction.message.react("🤖") let category = message.guild.channels.cache.find(cat=> cat.name === "my category") if(category == null){ // await接收创建结果,不需要再查缓存 category = await message.guild.channels.create('my category', { type: 'GUILD_CATEGORY' }) .catch(console.error); } setTimeout(createShopTicketChannel, 2000, message, category, user, "🤖") }else if(reaction.emoji.name === "🗺"){ reaction.message.channel.send("Wrong emoji") const mapReaction = reaction.message.reactions.cache.get("🗺") mapReaction && mapReaction.users.remove(user); reaction.message.react("🗺") let category = message.guild.channels.cache.find(cat=> cat.name === "my category") if(category == null){ category = await message.guild.channels.create('my category', { type: 'GUILD_CATEGORY' }) .catch(console.error); } setTimeout(createShopTicketChannel, 2000, message, category, user, "🗺") }else{ message.channel.send("Wrong emoooji") } })
注意事项
- 如果你使用的是discord.js v14及以上版本,分类创建的type参数需要改为
ChannelType.GuildCategory,同时需要提前从discord.js导入ChannelType - 确保你的bot开启了
GUILD_MESSAGE_REACTIONS和MESSAGE_CONTENT等必要的 Gateway Intents,否则无法正常监听反应事件
内容的提问来源于stack exchange,提问作者Draco
相关产品推荐
相关产品推荐

