Discord.js on raw event breakage

Viewed 818

Desired outcome: Assign role to a user who reacts to message in channel. On bot restart the message if not in cache, therefore user is not assigned role.

Issue: Code stops responding after guildID = client.guilds.get(packet.d.guild_id); client has been defined at the start of the script.

Expected output: Returns guildID and adds the role to the user who reacted.

Followed this guide

client.on('raw', packet => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
if (!(packet.d.channel_id === '<CHANNEL_ID>')) return;

//console.log(packet);

guildID = client.guilds.get(packet.d.guild_id);

if (packet.t === 'MESSAGE_REACTION_ADD') {
    console.log("ADDED");
    if (packet.d.emoji.name === '⭐') {
        try {
            guildID.members.cache.get(packet.d.user_id).roles.add('<ROLE_ID>').catch()
        } catch (error) {
            console.log(error);
        }
    }
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
    console.log("REMOVED");
}

});

2 Answers

Try to using these alternative way to use

And guildID = client.guilds.get(packet.d.guild_id); this wrong way to get guild since discord.js v12 updated it will be guildID = client.guilds.cache.get(packet.d.guild_id);

client.on('messageReactionAdd', (reaction, user) => {
    console.log('a reaction has been added');
});
 
client.on('messageReactionRemove', (reaction, user) => {
    console.log('a reaction has been removed');
});

Solved it with this

client.on('raw', async (packet) => {
    if (!['MESSAGE_REACTION_ADD',   'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
    if (!(packet.d.channel_id === '800423226294796320')) return;

    guild = client.guilds.cache.get(packet.d.guild_id);

    if (packet.t === 'MESSAGE_REACTION_ADD') {
        console.log("ADDED");
        if (packet.d.emoji.name === '⭐') {
            try {
                member = await guild.members.fetch(packet.d.user_id);
                role = await guild.roles.cache.find(role => role.name === 'star');
                member.roles.add(role);
            } catch (error) {
                console.log(error);
            }
        }
    }
    if (packet.t === 'MESSAGE_REACTION_REMOVE') {
        console.log("REMOVED");
        if (packet.d.emoji.name === '⭐') {
            try {
                member = await guild.members.fetch(packet.d.user_id);
                role = await guild.roles.cache.find(role => role.name === 'star');
                member.roles.remove(role);
            } catch (error) {
                console.log(error);
            }
        }
    }
});
Related