【问题标题】:Discord Bot how to remove specific user rolesDiscord Bot 如何删除特定用户角色
【发布时间】:2019-11-01 14:13:12
【问题描述】:

我一直在尝试制作一个机器人,如果用户具有“角色 1”然后他输入频道“角色 2”,机器人应该检查他是否有“角色 1 或角色 3”中的任何一个将其删除然后用户将“角色 2”添加到用户。

if (message == 'role 2') {
  var role = message.guild.roles.find("name", "2");

  if (message.member.roles.has('1')) {
    console.log('user has role 1');
    await message.member.removeRole("1");
    try {
      console.log('removed role 1');
    } catch(e){
      console.error(e)
    }
  }
  message.member.addRole(role);
}

但这不起作用,它只是添加角色而不是删除。 console.log 打印以下内容:

DeprecationWarning: Collection#find: 传递一个函数DeprecationWarning: Collection#find: 传递一个函数

如何在添加新角色之前检查并删除用户角色?


编辑:用这个新代码修复了错误:

var role = message.guild.roles.find(role => role.name === "2")

但删除角色命令仍然不起作用。

【问题讨论】:

    标签: javascript discord.js


    【解决方案1】:
    • 看起来message 是一个Message 对象。您应该比较它的 content 属性而不是对象本身。
    • 正如Saksham Saraswat 所说,您应该将一个函数传递给Collection.find()。不建议这样做。*
    • Map.has() 按键搜索。 Collections 使用 Discord ID 作为其密钥,即 Snowflakes。您的代码中显示的 ID 不是 ID,因此 不会执行该 if 语句的块。
    • 您编写await(...) 的方式是为了执行一个函数。请参阅await 关键字上的文档here。请注意,它只能在async functions 内部使用。
    • 您没有发现任何被拒绝的Promises.*

    * 这不会影响代码的当前结果。

    实施这些解决方案...

    if (message.content === 'role 2') {
      try {
        // message.member will be null for a DM, so check that the message is not a DM.
        if (!message.guild) return await message.channel.send('You must be in a guild.');
    
        // Find Role 2.
        const role2 = message.guild.roles.find(role => role.name === '2');
        if (!role2) return console.log('Role 2 missing.');
    
        // If the user has Role 1, remove it from them.
        const role1 = message.member.roles.find(role => role.name === '1');
        if (role1) await message.member.removeRole(role1);
    
        // Add Role 2 to the user.
        await message.member.addRole(role2);
      } catch(err) {
        // Log any errors.
        console.error(err);
      }
    }
    

    【讨论】:

    • 非常感谢,但我收到错误“;SyntaxError: await is only valid in async function”,你能帮我解决这个问题吗?
    • 将最相关的函数定义为异步。如果是消息事件,回调应该类似于async message => {...}async function(message) {...}
    • 你的意思是这个 "bot.on('message', message => {" ?
    • 非常感谢您的帮助,感谢您的帮助!
    【解决方案2】:

    我猜在 message.guild.roles.find 中你必须传入一个像 message.guild.roles.find(function); 这样的函数。我也认为 find 已被弃用,这意味着已过时并取而代之的是更好的解决方案/功能。

    【讨论】:

    • Collection.find() 并未作为一个整体被弃用;不推荐使用的部分是旧的 Collection.find('property', 'value') 用法。但是,这只是一个警告,不应影响其余代码的结果。
    • 谢谢,已经修复了错误,但删除功能仍然无法正常工作。当我输入“角色 1”然后输入“角色 2”时,它给了我多个角色,我希望机器人删除其他特定角色,知道吗?
    猜你喜欢
    • 2020-11-19
    • 2020-09-02
    • 2020-02-11
    • 2021-01-06
    • 1970-01-01
    • 2022-01-09
    • 2020-08-25
    • 2021-12-29
    • 2020-09-24
    相关资源
    最近更新 更多