【问题标题】:JS Discord Bot Get RoleJS Discord 机器人获取角色
【发布时间】:2018-06-26 06:57:14
【问题描述】:

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

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

     Role.delete()

这样可以吗?

【问题讨论】:

    标签: javascript bots discord discord.js


    【解决方案1】:

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

    这似乎在最新的 API 版本中有效。

    【讨论】:

      【解决方案2】:

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

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

      查看client.guilds的内容我发现了'cache'对象:

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

      【讨论】:

        【解决方案3】:

        顺便说一句,不推荐在 Discord.JS 中使用 Collection#find("key", "value") 的方式, 你应该改用Collection#find(Obj =&gt; Obj.key == "value")

        【讨论】:

        • 很高兴知道,但是自从接受另一个答案以来,这一年是否发生了变化?由于 SO 是历史知识的存储库,因此可以通过添加指示何时弃用的参考来改进此答案。
        【解决方案4】:

        除非您在服务器上设置了公会,否则公会不起作用。人们一直建议这样做,但您必须已经在您的不和谐服务器中设置了基础架构。

        【讨论】:

          【解决方案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}`);
          })
          

          【讨论】:

          • find("name", "Your_role_name") 已弃用,请参阅 StanB 答案
          • 是的,它已被弃用,而新的做法是。 const role = guild.roles.cache.find((r) =&gt; r.name === 'Your_role_name');
          猜你喜欢
          • 2020-12-30
          • 1970-01-01
          • 2020-08-28
          • 2019-09-16
          • 2022-10-30
          • 1970-01-01
          • 2021-08-14
          • 2019-08-10
          • 1970-01-01
          相关资源
          最近更新 更多