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

Discord.js开发时reaction反应计数异常,多用户反应无法正确统计如何解决?

问题根源与修复方案

错误点1:过滤器逻辑错误

你当前的filter2添加了user.id === message.author.id的限制,仅会捕获投票发起者的反应,其他所有用户的反应都会被过滤,这就是多用户投票无法统计到的核心原因。

错误点2:计数未排除机器人自身

机器人先给投票消息添加了两个默认反应,reaction.count默认会包含机器人的1次计数,直接取值会比真实用户数多1,建议直接过滤掉所有机器人用户的反应再统计数量更稳妥。

错误点3:缺少必要配置

Discord.js v13+版本需要先在开发者后台开启GUILD_MESSAGE_REACTIONS权限意图,同时创建反应收集器时建议添加fetchAll: true配置,避免缓存缺失导致统计不全。

修正后代码

collector.on('end', (collected) => {
  let i = 0;
  const collectedembed = new Discord.MessageEmbed();
  collected.forEach((value) => {
    i++;
    collectedembed.setTitle(question);
    if (i === 1) {
      collectedembed.addField('1st option', value.content);
    } else if (i === 2) {
      collectedembed.addField('2nd option', value.content);
    }
  });
  message.channel.send({ embeds: [collectedembed] }).then(async (poll) => {
    await poll.react('1️⃣');
    await poll.react('2️⃣');
    // 移除仅匹配发起者的限制,仅校验表情合法、非机器人操作
    const filter2 = (reaction, user) => {
      return ['1️⃣', '2️⃣'].includes(reaction.emoji.name) && !user.bot;
    };
    // 添加fetchAll配置拉取全量反应
    const collector2 = poll.createReactionCollector({ filter: filter2, time: 5000, fetchAll: true });
    collector2.on('end', (collected) => {
      // 过滤机器人后统计真实用户数
      const count1 = poll.reactions.cache.get('1️⃣').users.cache.filter(u => !u.bot).size;
      const count2 = poll.reactions.cache.get('2️⃣').users.cache.filter(u => !u.bot).size;
      poll.channel.send(
        `reacted with 1️⃣ ${count1} users \n reacted with 2️⃣ ${count2} users`,
      );
    });
  });
});

额外说明:如果你的投票统计时长需要更长,可以调整createReactionCollector里的time参数值,单位为毫秒,当前5000即5秒的统计窗口可能偏短。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:15:03