奇怪的反应行为,票务系统discord.js

Weird reaction behavior, ticket system discord.js

我正在尝试使用我的 discord.js 机器人为我的 discord 服务器创建一个自己的票务系统。 如果用户用表情符号对某条消息做出反应,我希望它首先立即删除反应,然后继续。所以基本上反应计数保持在 1(我的机器人中唯一的一个)。 问题是,如果我重新启动机器人并对消息做出反应,它不会删除我的反应,但是当我手动删除它并重试时,它有效!

这是我的代码:

client.on("messageReactionAdd", async (messageReaction, user) => {
    if (messageReaction.partial) {
        try {
            await messageReaction.fetch();
        } catch (error) {
            console.log("couldn't fetch message1", error);
        }
    }
    let msg = messageReaction.message;
    if (msg.id === config.support_msg_id) {
        const userReactions = msg.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));
        try {
            for (const reaction of userReactions.values()) {
                await reaction.users.remove(user.id);
            }
        } catch (error) {
            console.error('Failed to remove reactions.');
        }
    }
});

问题是 messageReactionAdd 事件仅在将反应添加到 缓存 消息时触发,如 Discord.js docs 所述:

Emitted whenever a reaction is added to a cached message.

您可以通过使用以下代码在机器人启动时将每条消息添加到缓存来解决此问题:

client.on('ready', () => {
  client.guilds.cache.each(guild => {
    guild.channels.cache.each(channel => {
      if (channel.type === 'text' || channel.type === 'dm') {
        channel.messages.fetch();
      }
    });
  });
});

如果要防止过多的消息被添加到缓存中,可以通过ChannelLogsQueryOptions to the MessageManager.fetch()函数。