How to check if member has a role using discord.js?

by dalton_moen , in category: Javascript , 8 days ago

How to check if member has a role using discord.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 7 days ago

@dalton_moen 

You can check if a member has a specific role in a Discord server using the roles.cache property of the GuildMember object in discord.js. Here's an example code snippet to demonstrate how to check if a member has a role:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', message => {
    if(message.content === '!checkRole') {
        // Get the member object of the message sender
        const member = message.guild.member(message.author);

        // Get the role object for the role you want to check
        const role = message.guild.roles.cache.find(role => role.name === 'YourRoleName');

        // Check if the member has the role
        if(member.roles.cache.has(role.id)) {
            message.channel.send('The member has the role!');
        } else {
            message.channel.send('The member does not have the role.');
        }
    }
});

client.login('YOUR_DISCORD_BOT_TOKEN');


In the above code, !checkRole is a command that will check if the message sender has a role named 'YourRoleName'. If the member has the role, it will send a message saying "The member has the role!", otherwise it will send a message saying "The member does not have the role.". Make sure to replace 'YOUR_DISCORD_BOT_TOKEN' with your own bot token.


This is a basic example and you can modify and enhance it based on your specific requirements and use case.