如何在discord.js v13中统计embed消息的表情反应总数量?
问题根源
- 监听对象错误:你此前的代码监听的是用户触发命令的原始消息,而非机器人发送的带embed的目标消息,自然捕获不到对应反应
- 异步时序错误:消息发送、表情添加都是异步操作,在
then回调外访问未完成初始化的消息属性必然返回undefined报错 - 配置缺失:discord.js v13及以上版本需要在开发者后台开启
GuildMessageReactions网关意图,同时初始化客户端时声明该意图,否则无法捕获反应事件 - 计数注意:默认统计的反应数量包含机器人自身添加的反应,如需仅统计用户反应,最终数值需减1
可用实现代码
固定时长统计版(发送后监听10秒再统计结果)
const discord = require('discord.js'); const db = require('quick.db'); module.exports = { name: 'command', run: async (message, args) => { const suggestionEmbed = new discord.MessageEmbed() .setColor('#000000') .setTitle('[!] Hello') .setTimestamp() // 等待消息发送完成,拿到实际发送的消息对象 const sEmbed = await message.channel.send({ embeds: [suggestionEmbed] }); // 按顺序添加两个表情 await sEmbed.react('⬆️'); await sEmbed.react('⬇️'); // 配置过滤规则:仅匹配两个目标表情,可根据需求添加!user.bot排除机器人反应 const filter = (reaction, user) => ['⬆️', '⬇️'].includes(reaction.emoji.name); // 监听目标消息的反应,时长10秒 const collected = await sEmbed.awaitReactions({ filter, time: 10000 }); // 统计数量,无对应反应时默认返回0 const upCount = collected.get('⬆️')?.count || 0; const downCount = collected.get('⬇️')?.count || 0; // 此处可替换为你的业务逻辑,比如判断赞踩阈值 message.reply(`统计结果:👍 ${upCount} 个,👎 ${downCount} 个`); } }
实时监听版(反应达标立即触发逻辑,无需等待时间结束)
// 前面发送embed、添加表情的逻辑同上 const filter = (reaction, user) => ['⬆️', '⬇️'].includes(reaction.emoji.name); const collector = sEmbed.createReactionCollector({ filter, idle: 30000 }); // 30秒无新反应自动停止监听 collector.on('collect', (reaction) => { const upCount = reaction.message.reactions.cache.get('⬆️')?.count || 0; const downCount = reaction.message.reactions.cache.get('⬇️')?.count || 0; // 达到阈值触发逻辑示例 if(upCount >= 5) { message.reply(`该建议已达到5个赞`); collector.stop('up_goal_reached'); // 触发后停止监听 } if(downCount >= 10) { message.reply(`该建议已达到10个踩`); collector.stop('down_goal_reached'); } });
常见问题排查
- 仍无反应:确认客户端初始化时已添加
GuildMessageReactions意图,示例:
const client = new discord.Client({ intents: [ discord.Intents.FLAGS.GUILDS, discord.Intents.FLAGS.GUILD_MESSAGES, discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS // 必须加这行 ] });
- 计数多1:因为包含了机器人自己添加的反应,如需仅统计用户反应,将
upCount改为(collected.get('⬆️')?.count || 0) - 1即可
内容的提问来源于stack exchange,提问作者PackOf20
相关产品推荐
相关产品推荐

