Auto Reaction Roles / Discord.js Bot



So I’m having a slight issue getting my auto roles to work I have been trying to sort it via message.js and in the reactionrole.js but its still giving the same issue wondering if anyone can help would be appreciated as I have looked up about it via tutorials and apart from a few differences due to different text / details it does has not helped

Also I’m using Command handler V2 if that helps Error

(node:7712) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of undefined at Object.execute (commandsotherreactionrole.js:6:46) at module.exports (eventsguildmessage.js:46:25) at Client.emit (events.js:376:20) at MessageCreateAction.handle
(node_modulesdiscord.jssrcclientactionsMessageCreate.js:31:14) at Object.module.exports [as MESSAGE_CREATE] (node_modulesdiscord.jssrcclientwebsockethandlersMESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (node_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:384:31)
at WebSocketShard.onPacket (node_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:444:22) at WebSocketShard.onMessage (node_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:301:10) at WebSocket.onMessage node_moduleswslibevent-target.js:132:16)
at WebSocket.emit (events.js:376:20) (Use `node --trace-warnings ...` to show where the warning was created) (node:7712) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) (node:7712) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

reactionrole.js

module.exports = {
    name: 'reactionrole',
    description: 'Sets Up Roles!',
    async execute(message, args, Discord, client){
        const channel = '860952043845058570'
        const vgmembers = message.guild.roles.cache.find(role => role.name === "VG Members");
        const vgamembers = message.guild.roles.cache.find(role => role.name === "VG-A Members");
        const vghmembers = message.guild.roles.cache.find(role => role.name === "VG-H Members");

        const vgmembersEmoji = `<:VG:860965732057219122>`;
        const vgamembersEmoji = `<:VGA:860964110434566154>`;
        const vghmembersEmoji = `<:VGH:860964110371913748>`;

        let embed = new Discord.MessageEmbed()
        .setColor('#e42643')
        .setTitle('What Family Are You In')
        .setDescription('Select The Emjoi Of The Alliance You Are In nn'
        + `${vgmembersEmoji} If Your A VG Membern`
        + `${vgamembersEmoji} If Your A VG-A Membern`
        + `${vghmembersEmoji} If Your A VG-H Member`);

        let messageEmbed = await message.channel.send(embed);
        messageEmbed.react(yellowTeamEmoji);
        messageEmbed.react(blueTeamEmoji);
 
        client.on('messageReactionAdd', async (reaction, user) => {
            if (reaction.message.partial) await reaction.message.fetch();
            if (reaction.partial) await reaction.fetch();
            if (user.bot) return;
            if (!reaction.message.guild) return;
 
            if (reaction.message.channel.id == channel) {
                if (reaction.emoji.name === vgmembersEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.add(vgmembers);
                }
                if (reaction.emoji.name === vgamembersEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.add(vgamembers);
                }
                if (reaction.emoji.name === vghmembersEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.add(vghmembers);
                }
            } else {
                return;
            }
 
        });
 
        client.on('messageReactionRemove', async (reaction, user) => {
 
            if (reaction.message.partial) await reaction.message.fetch();
            if (reaction.partial) await reaction.fetch();
            if (user.bot) return;
            if (!reaction.message.guild) return;
 
 
            if (reaction.message.channel.id == channel) {
                if (reaction.emoji.name === vgmembersEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.remove(vgmembers);
                }
                if (reaction.emoji.name === vgamembersEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.remove(vgamembers);
                }
                if (reaction.emoji.name === vghmembersEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.remove(vghmembers);
                }
            } else {
                return;
            }
        });
    }
 
}   

message.js

require("dotenv").config();
const { Console, time } = require('console');
const cooldowns = new Map();


module.exports = async (Discord, client, message) => {
    const prefix = process.env.PREFIX;


    if(!message.content.startsWith(prefix) || message.author.bot) return;


    const args = message.content.slice(prefix.length).split(/ +/);
    const cmd = args.shift().toLowerCase();

    const command = client.commands.get(cmd) || client.commands.find((a) => a.aliases && a.aliases.includes(cmd));
    if (!command) return message.channel.send("This Command Doesn't Exist!");

    if (command === "reactionrole"){
        client.commands.get('reactionrole').execute(message, Discord, client);
      }

    if(!cooldowns.has(command.name)){
        cooldowns.set(command.name, new Discord.Collection());
    }
  
    const current_time = Date.now();
    const time_stamps = cooldowns.get(command.name);
    const cooldown_amount = (command.cooldown) * 1000;

    //If time_stamps has a key with the author's id then check the expiration time to send a message to a user.
    if(time_stamps.has(message.author.id)){
        const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;

        if(current_time < expiration_time){
            const time_left = (expiration_time - current_time) / 1000;

            return message.reply(`Please wait ${time_left.toFixed(1)} more seconds before using ${command.name}`);
        }
    }
    //If the author's id is not in time_stamps then add them with the current time.
    time_stamps.set(message.author.id, current_time);
    //Delete the user's id once the cooldown is over.
    setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);

    if(command) command.execute(client, message, args, Discord);
}

Answer

In your message.js you have

if(command) command.execute(client, message, args, Discord);

While in reactionrole.js you have

async execute(message, args, Discord, client){

This simply means that the value names are mismatched.

There are 3 ways to fix this.

  1. Changing the order in your command file

Probably the best way to fix this. Simply change the beginning of reactionrole.js to:

module.exports = {
    name: 'reactionrole',
    description: 'Sets Up Roles!',
    async execute(client, message, args, Discord){
    //the rest of the code
  1. Change your Command Handler output

This isn’t advised, as you probably have other command files that already use the current format, but still possible.

Simply change the last line in message.js to

if(command) command.execute(message, args, Discord, client);

But that might mean having to change all the command files along with it.

  1. Reformat the output and input

One of the best solutions is to use Objects.

In message.js change the last line to

if(command) command.execute({ client, message, args, Discord });

In command files, change the execute property to

async execute({ client, message, args, Discord }){

This will also allow you to only take specific properties in command files, and change the order in which you take them.

Examples:

  • You can leave out the client, args and Discord properties if it’s a simple response like so:
async execute({ message }){
  • You can change the order without a penalty
async execute({ message, args, Discord, client }){

This will still work, even though the order changed.

The only thing you have to watch out for with this method is the capitalization. If you were to type discord instead of Discord it wouldn’t work.

Use any method you prefer, and a happy coding!



Source: stackoverflow