Medraj
Medraj

Reputation: 173

Discord.js v12 Role add to mentioned user problem

so I am trying to make a command like $roletested @user which should give the user mentioned the specific role. I get an error called:_ "Cannot read property 'roles' of undefined... Help me out please, here's my code :D

    if (message.content.startsWith(prefix + "roletested")) {
        let testedUser = message.mentions.members.first()
        if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'));
        if(!testedUser) return message.channel.send("You have to mention the person you want to assign the role to!").then((declineMsg) => { message.react('❌');
            declineMsg.delete({timeout: 5000});
            let testedRole = message.guild.roles.cache.find(role => role.id === "724676382776492113");
            testedUser.roles.add(testedRole);
            message.channel.send("Added the role `TESTED` to user.")
        })}})

Upvotes: 1

Views: 4531

Answers (2)

Renato
Renato

Reputation: 29

I fixed your code :

  • I put in order something (the code is the same, I only changed something)
  • You can't use message.guild.roles.cache.find(...) so I changed it to message.guild.role.cache.get('Role ID')

Source : Link

Code :

    if (message.content.startsWith(prefix + 'roletested')) {
        const testedUser = message.mentions.members.first();
        if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'));
        if (!testedUser) {
            message.channel.send('You have to mention the person you want to assign the role to!').then(declineMsg => {
                message.react('❌');
                declineMsg.delete({ timeout: 5000 });
                return;
            });
        }
        const testedRole = message.guild.roles.cache.get('395671618912780289');
        testedUser.roles.add(testedRole);
        message.channel.send('Added the role `TESTED` to user.');
    }

I tested this code on my bot and it worked as expected.

Upvotes: 0

rez
rez

Reputation: 331

Your code but fixed

  if (message.content.startsWith(prefix + "roletested")) {
    if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'))

    let testedRole = message.guild.roles.cache.get('724676382776492113');
    let testedUser = message.mentions.members.first();
    if(!testedUser) return message.channel.send("You have to mention the person you want to assign the role to!").then((declineMsg) => { message.react('❌')
    declineMsg.delete({timeout: 5000});
    });
    
    testedUser.roles.add(testedRole);
    message.channel.send("Added the role `TESTED` to user.")
  }

Upvotes: 1

Related Questions