You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.js v13如何统计已发送消息上指定emoji的反应数量

问题原因&修复方案
  • 过滤规则错误:你当前的filter加了user.id === message.author.id限制,仅会收集投票发起者的反应,其余用户的反应全部被拦截,自然无法凑够阈值,也不会统计到其他用户的投票。
  • 变量返回错误:你在await message.channel.send().then()的回调中没有返回sEmbed对象,导致外层embedSend变量为undefined,调用其属性自然会抛出类型错误。
  • 反应收集逻辑错误:collected.first()只会读取收集到的第一个反应,所以只会打印一次结果,无法实现逐次/累计计数的需求,且你设置的max为20,会不管emoji类型凑够20个反应就停止收集,不符合按单类emoji计数的需求。
  • API调用版本不匹配:discord.js v13及以上版本,反应集合需要从cache属性中读取,你用的旧版本find方法已经失效。
修正后代码
// 发送投票embed
const sEmbed = await message.channel.send({ embeds: [suggestionEmbed] });
// 添加默认反应
await sEmbed.react('⬆️');
await sEmbed.react('⬇️');

// 修正filter:过滤指定emoji,排除机器人自己的反应
const filter = (reaction, user) => {
    return ['⬆️', '⬇️'].includes(reaction.emoji.name) && !user.bot;
};

// 等待反应,时间到自动结束收集
sEmbed.awaitReactions({ 
    filter, 
    time: 50000,
    errors: ['time'] 
})
.then(collected => {
    // 统计两类反应的数量,count已包含机器人预先发的反应
    const upCount = sEmbed.reactions.cache.get('⬆️').count;
    const downCount = sEmbed.reactions.cache.get('⬇️').count;
    console.log('支持票数:', upCount);
    console.log('反对票数:', downCount);
    // 按需求判断阈值,比如支持票达10执行后续操作
    if(upCount >= 10) {
        // 你的后续逻辑
    }
})
.catch(collected => {
    // 时间到自动统计最终票数
    const upCount = sEmbed.reactions.cache.get('⬆️').count;
    const downCount = sEmbed.reactions.cache.get('⬇️').count;
    console.log('投票结束,支持票:', upCount, '反对票:', downCount);
});
补充说明
  • 如果需要实时监听每一次反应变化,可以用createReactionCollector代替awaitReactions,每收到新反应就触发回调统计计数。
  • 如果需要排除重复投票的用户,可以在filter或者回调中额外判断用户是否已经投过票。

内容的提问来源于stack exchange,提问作者PackOf20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:57:01