Hassan_BH
Hassan_BH

Reputation: 113

How to check if mention has a role

I have been making a mute command for my discord bot and it suddenly.... didn't work in the part of the

if (msg.content.startsWith("!mute")) {
    if (!msg.member.hasPermission("MANAGE_MEMBERS"))
        return msg.channel.send(`You don't have permision to mute members!`);

    let target = msg.mentions.members.first();

    let taggedId = target.id;
    var role = msg.guild.roles.cache.find((role) => role.name === "Muted");
    if (!role) return msg.channel.send("There is no Muted role on the server");

    //The part it didn't work////////////

    if (taggedId.roles.cache.find((r) => r.name === "Muted"))
        return msg.channel.send("The member is already muted!");

    /////////////////////////////////////////////////

    if (target.member.hasPermission("ADMINISTRATOR"))
        return msg.channel.send(`The target is an Admin`);

    if (!target) return msg.channel.send(`I couldn't find your target!`);

    target.roles.add(role);

    msg.channel.send(`Muted ${target} Succesfully!`);
}

And I get this error:

/home/runner/Bot/index.js:289
    if(taggedId.roles.cache.find(r => r.name === "Muted")) return msg.channel.send('The member is already muted!')
                      ^

    TypeError: Cannot read property 'cache' of undefined
        at Client.<anonymous> (/home/runner/Bot/index.js:289:19)

I did my best but it was no worth it please if anyone knows help me!

Upvotes: 1

Views: 392

Answers (1)

Toasty
Toasty

Reputation: 1880

You are trying to access roles of a string (taggedId) which contains the ID of the mentioned user.

If you want to access the roles you have to use your target variable because this contains the GuildMember:

So insted of this:

if(taggedId.roles.cache.find(r => r.name === "Muted")) return msg.channel.send('The member is already muted!')

You should do this:

if(target.roles.cache.find(r => r.name === "Muted")) return msg.channel.send('The member is already muted!')

Upvotes: 1

Related Questions