javascriptnode.jsdiscorddiscord.jsticket-system

Weird reaction behavior, ticket system discord.js


I am trying to make an own ticket system for my discord server with my discord.js bot. If a user reacts to a certain message with the 📩 emoji, I want it first to delete the reaction instantly, and then continue. So basically the reaction count stays at 1 (the only one from my bot). The problem is, if I restart the bot and react to the message, it doesn't delete my reaction, however when I manually delete it, and try again, it works!

Here is my code:

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.');
        }
    }
});

Solution

  • The problem is that the messageReactionAdd event is only triggered when a reaction is added to a cached message, as stated by the Discord.js docs:

    Emitted whenever a reaction is added to a cached message.

    You could fix this by adding every message to the cache when the bot starts by using the following code:

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

    If you want to prevent too many messages being added to the cache, you can pass ChannelLogsQueryOptions to the MessageManager.fetch() function.