How to make a raw event run only once

Viewed 136

I have a raw event:

this.on('raw', packet => {
            if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
            const channel = this.channels.cache.get(packet.d.channel_id);
            if (channel.messages.cache.has(packet.d.message_id)) return;
            channel.messages.fetch(packet.d.message_id).then(message => {
                const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
                const reaction = message.reactions.cache.get(emoji);
                if (reaction) reaction.users.cache.set(packet.d.user_id, this.users.cache.get(packet.d.user_id));
                if (packet.t === 'MESSAGE_REACTION_ADD') {
                    this.emit('messageReactionAdd', reaction, this.users.cache.get(packet.d.user_id));
                }
                if (packet.t === 'MESSAGE_REACTION_REMOVE') {
                    this.emit('messageReactionRemove', reaction, this.users.cache.get(packet.d.user_id));
                }
            });
        });

This event spams continuously when one reaction is added, I want to make it so if you react it will run once. How can I do this?

1 Answers

You should not use the raw event past discord.js version 12. As there are some issues when your bot grows.

Instead use Partials as explained in the offical Discord.js Guide

const Discord = require('discord.js');
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
client.on('messageReactionAdd', async (reaction, user) => {
    // When we receive a reaction we check if the reaction is partial or not
    if (reaction.partial) {
        // If the message this reaction belongs to was removed the fetching might result in an API error, which we need to handle
        try {
            await reaction.fetch();
        } catch (error) {
            console.error('Something went wrong when fetching the message: ', error);
            // Return as `reaction.message.author` may be undefined/null
            return;
        }
    }
    // Now the message has been cached and is fully available
    console.log(`${reaction.message.author}'s message "${reaction.message.content}" gained a reaction!`);
    // The reaction is now also fully available and the properties will be reflected accurately:
    console.log(`${reaction.count} user(s) have given the same reaction to this message!`);
});

Source and more information: https://discordjs.guide/popular-topics/reactions.html#listening-for-reactions-on-old-messages

Related