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

Discord.js 14.7.1机器人首次反应未注册问题排查与解决

Discord机器人无法识别历史消息的首次反应问题

问题描述

机器人会跳过对启动前发送的消息的第一个反应表情,取消该反应后重新添加,机器人才能识别到;但对启动后发送的消息,反应识别功能正常。

开发目标

开发Discord机器人,用于收集并打印用户对指定消息的所有反应内容。

环境信息

  • 使用Discord.js 14.7.1版本
  • Discord开发者平台已启用以下权限:
    • Presence Intent
    • Server Members Intent
    • Message Content Intent

代码实现

const { Client, Events, GatewayIntentBits, Partials } = require('discord.js');
const { token } = require('./includes/config.json');

// 创建Discord客户端实例
const client = new Client({
  intents: [
    GatewayIntentBits.DirectMessageReactions,
    GatewayIntentBits.DirectMessageTyping,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.Guilds,
    GatewayIntentBits.MessageContent,
  ],
  partials: [
    Partials.Channel,
    Partials.GuildMember,
    Partials.Message,
    Partials.Reaction,
    Partials.User,
  ]
});

// 客户端就绪事件
client.once(Events.ClientReady, () => {
  console.log('Ready!');
});

// 处理反应添加事件,兼容部分对象
client.on(Events.MessageReactionAdd, async (reaction, user) => {
  if (reaction.partial) {
    try {
      await reaction.fetch();
    } catch (error) {
      console.error(error);
      return;
    }
  }

// 获取反应所属消息
const message = reaction.message;

// 筛选当前用户在该消息上的所有反应
const userReactions = await message.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));

// 打印所有反应表情
try {
  for (const reaction of userReactions.values()) {
    console.log(`Emoji: ${reaction.emoji}`);
  }
} catch(error) {
  console.error(error);
}
})

// 登录机器人
client.login(token);

问题现象

针对机器人启动前的消息进行测试:

  • 操作顺序:依次添加表情😄❤️🔥
  • 实际日志输出:
Emoji: ❤️
Emoji: ❤️
Emoji: 🔥
  • 预期输出:
Emoji: 😄
Emoji: 😄
Emoji: ❤️
Emoji: 😄
Emoji: ❤️
Emoji: 🔥

排查结论

  • 确认MessageReactionAdd事件会正常触发,但机器人仅能处理缓存内的消息
  • 尝试手动fetch完整反应及消息对象后,问题仍未解决

解决方案

通过SQLite数据库持久化记录用户反应:

  1. 在MessageReactionAdd事件中,将用户的反应信息(如消息ID、用户ID、表情内容)存入数据库
  2. 在MessageReactionRemove事件中,删除数据库中对应的反应记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:55:17