javascript - 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")
但是删除角色命令仍然不起作用。
解决方案
- 它看起来像是
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);
}
}
推荐阅读
- html - 在网格中将项目彼此相邻对齐
- sql - 在 oracle 11g xe 中连接表
- reactjs - 如何使用多个数据集更改chartjs甜甜圈图的标签
- python - 如何将 poppler 文件添加到我的 exe
- javascript - 预计会收到一个 SlashCommandChannelOption 构建器,而不是未定义
- android - Firebase 消息:由于所需的 APNs SSL 证书已过期或未上传,无法向 iOS 设备发送消息
- php - 无法回显来自 POST API CALL PHP 的响应
- laravel-livewire - Livewire 在事件发生后未使用 db 中的值进行更新
- pyspark - 为什么我的构建挂起/需要很长时间才能生成具有许多联合的查询计划?
- google-signin - 如何检测用户是否在 Android 原生库(Java/Kotlin)中使用 Google One Tap 登录或退出并在返回时获取凭证数据(令牌)?