JS Discord Bot扮演角色

Hel*_*ion 1 javascript bots discord discord.js

我试图在不使用消息的情况下获得角色,例如:

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

     Role.delete()
Run Code Online (Sandbox Code Playgroud)

这可以做到吗?

小智 8

顺便说一下,Collection#find("key", "value")不推荐使用 Discord.JS 中的这种方式,您应该Collection#find(Obj => Obj.key == "value")改用。


Nic*_*via 6

我尝试使用已发布的解决方案,但client.guilds.get未被识别为函数:

UnhandledPromiseRejectionWarning: TypeError: client.guilds.get 不是客户端的函数。

检查client.guilds我发现的“缓存”对象的内容:

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

解决方案是:

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}`);
});
Run Code Online (Sandbox Code Playgroud)


Wri*_*ght 5

是的,可以,但是您需要具有要从中获得角色的公会ID。另外,您应该将该部分放在ready事件中。

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}`);
})
Run Code Online (Sandbox Code Playgroud)

  • find("name", "Your_role_name") 已弃用,请参阅 StanB 答案 (2认同)