deadkill
deadkill

Reputation: 23

How do I check what roles my bot has? [Discord.js]

I am trying to find if my bot has a specific role so it can do something else. For example:

client.user.roles.cache.find(r => r.name === 'specific role');

My error:

TypeError: Cannot read property 'cache' of undefined

Upvotes: 2

Views: 812

Answers (3)

Jytesh
Jytesh

Reputation: 825

You need to resolve the user into a GuildMember, since users don't have roles.

To do that you need a Guild class,after that you can use the guild.member() method to convert it to a member

const guild = client.guilds.cache.get('id of the guild'),
member = guild.member(client.user.id);
member.roles.cache.find(r=> r.name === 'name')

Another issue you might run into here is, the member constant being undefined, this can be solved by using guild.members.fetch(id) or enabling the Privileged Member intent in the Discord Developer Portal

Upvotes: 0

Tyler2P
Tyler2P

Reputation: 2370

Let's start of by stating that users do not have roles, therefore you have to fetch the guildMember.

Fetching the guild member is easy;
First of all, you will have to fetch the guild the user is in. For example:

var guild = client.guilds.cache.get('guild-id');

Secondly, you will have to find the user in that guild. For example:

var member = guild.members.cache.get('user-id');

Then you will be able to move forward and fetch the roles

member.roles.cache.find(r => r.name === 'role-name');

The full example:

const Discord = require('discord.js'); //Define discord.js
const client = new Discord.Client(); //Define the client

client.on('message' message => { //Event listener
    //Do something here
    var guild = client.guilds.cache.get(message.guild.id);
    var member = guild.members.cache.get(client.user.id);

    member.roles.cache.find(r => r.name === 'role-name');
});

client.login('token'); //Login

Upvotes: 2

deadkill
deadkill

Reputation: 23

So maybe I didnt explain my problem very well but here is what I found working for me message.guild.me.roles.cache.find(r=> r.name === 'a role') thanks to everyone for helping me !!!

Upvotes: 0

Related Questions