![](/img/trans.png)
[英]How to remove all roles and add one role on discord bot, and then remove the added role and restore previous roles
[英]Discord Bot how to remove specific user roles
我一直在尝试制作一个机器人,如果用户有“角色 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
属性而不是对象本身。Collection.find()
。 不建议这样做。*Map.has()
按关键字搜索。 Collection s 使用 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);
}
}
我猜在 message.guild.roles.find 你必须传入一个函数,比如 message.guild.roles.find(function); 此外,我认为 find 已被弃用,这意味着已过时并取代了更好的解决方案/功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.