首页 > 解决方案 > Discord Bot 如何删除特定用户角色

问题描述

我一直在尝试制作一个机器人,如果用户具有“角色 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")

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

标签: javascriptdiscord.js

解决方案


  • 它看起来像是message一个Message对象。您应该比较它的content属性而不是对象本身。
  • 正如Saksham Saraswat所说,您应该将一个函数传递给Collection.find(). 不建议这样做。*
  • Map.has()按键搜索。Collection使用 Discord ID 作为其键,即Snowflakes。您的代码中显示的 ID 不是 ID,因此不会执行if语句的块。
  • 您编写的方式await(...)是执行功能。请参阅此处有关await关键字的文档。请注意,它只能在异步函数内部使用。
  • 你没有收到任何被拒绝的承诺。*

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

实施这些解决方案...

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

推荐阅读