xrrjchvizeçq
xrrjchvizeçq

Reputation: 333

JS Discord Bot Get Role

I'm trying to get a role without using messages, like:

     const Discord = require('discord.js');
     const Bot = new Discord.Client();
     const Role = Discord.roles.find('name,'Exemple')

     Role.delete()

Is this possible to do that?

Upvotes: 6

Views: 41147

Answers (6)

Víctor Alvarado
Víctor Alvarado

Reputation: 11

To get an specific role i use this code. Replace SERVER_ID with your server id and ROLE_NAME with the name of the role

const guild = client.guilds.cache.get("SERVER_ID");
const role = guild.roles.cache.find((r) => r.name === "ROLE_NAME");

console.log(`Found the role ${role.name}`);
console.log(`Found the role ${role.id}`);

Upvotes: 0

Anatoly
Anatoly

Reputation: 11

const role = guild.roles.cache.get('role_id');

This seems to be working in the latest API version.

Upvotes: 0

Nicolas Hevia
Nicolas Hevia

Reputation: 15897

I tried with the posted solution but client.guilds.get was not recognized as a function:

UnhandledPromiseRejectionWarning: TypeError: client.guilds.get is not a function at Client.

Checking the content of client.guilds I found 'cache' object:

GuildManager {
  cacheType: [Function: Collection],
  cache: Collection [Map] {
    '<discord server id>' => Guild {
      members: [GuildMemberManager],
      channels: [GuildChannelManager],
      (...)
     }
  }
}

The solution was:

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

client.once('ready', () => {
    const myGuild = client.guilds.cache.get('<discord server id>');
    const myRole = myGuild.roles.cache.find(role => role.name === '<role name>');
    console.log(`Found the role ${myRole.name}`);
});

Upvotes: 6

StanB
StanB

Reputation: 101

Using that way of Collection#find("key", "value") in Discord.JS is deprecated by the way, You should use Collection#find(Obj => Obj.key == "value") instead.

Upvotes: 10

Casey Shore
Casey Shore

Reputation: 29

Guild doesn't work unless you have it set up on the server. People keep suggesting this but you have to already have infrastructure set up in your discord server.

Upvotes: 0

Wright
Wright

Reputation: 3424

Yes you can but you will need to have the guild id you want to get the role from. Also, you should put that part in the ready event.

const discord = require("discord.js");
const client = new discord.Client();

client.on("ready", () => {
    console.log("Bot online!");
    const guild = client.guilds.get("The_server_id");
    const role = guild.roles.find("name", "Your_role_name");

    console.log(`Found the role ${role.name}`);
})

Upvotes: 10

Related Questions