代码之家  ›  专栏  ›  技术社区  ›  Hell Protection

JS Discord Bot Get角色

  •  5
  • Hell Protection  · 技术社区  · 7 年前

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

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

    这有可能做到吗?

    6 回复  |  直到 7 年前
        1
  •  10
  •   StanB    6 年前

    使用这种方式 Collection#find("key", "value") 不和谐。顺便说一下,JS不太受欢迎, 您应该使用 Collection#find(Obj => Obj.key == "value") 相反

        2
  •  9
  •   Wright    7 年前

    是的,你可以,但你需要有你想要获得角色的公会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}`);
    })
    
        3
  •  6
  •   Nicolas Hevia    4 年前

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

    未处理PromisejectionWarning:TypeError:client。公会。get不是客户端的函数。

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

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

    解决方案是:

    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}`);
    });
    
        4
  •  0
  •   Casey Shore    6 年前

    除非您在服务器上设置了公会,否则公会不会工作。人们一直在建议这一点,但您必须已经在discord服务器中设置了基础设施。

        5
  •  0
  •   Anatoly    4 年前

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

    这似乎在最新的API版本中起作用。

        6
  •  0
  •   Víctor Alvarado    3 年前

    要获得特定角色,我使用此代码。 将SERVER\u ID替换为服务器ID,将ROLE\u NAME替换为角色名称

    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}`);