我正在执行定时静音命令,但出现很多错误,主要错误是:
(node:6584) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Role
at RequestHandler.execute (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async GuildMemberRoleManager.remove (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\managers\GuildMemberRoleManager.js:125:7)
(Use `node --trace-warnings ...` to show where the warning was created)
这是被窃听的代码:
const ms = require('ms');
module.exports = {
name : 'mute',
description: 'Mutes given user',
execute(client, message, args) {
if(!message.member.hasPermission('MUTE_MEMBERS') && message.member.hasPermission('MANAGE_ROLES')) {
return message.reply('You need permissions to use this command !');
}
const target = message.mentions.users.first();
if(target) {
const member = message.guild.members.cache.get(target.id)
if(member) {
const muteRole = message.guild.roles.cache.find(role => role.name === "Muted");
if(muteRole) {
const RoleFolder = []
const roles = member.roles.cache.map(role => role);
roles.forEach(role => {
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
member.roles.add(muteRole.id)
setTimeout(function () {
member.roles.remove(muteRole.id)
RoleFolder.forEach(roles => {
member.roles.add(roles)
})
}, ms(args[1]));
} else {
return message.reply('Make sure you have a role nammed "Muted" when trying to mute a member');
}
} else {
return message.reply('There was an error while attempting to get member object of mentioned user !')
}
} else {
return message.reply('You need a user to mute ! ');
}
}
}
问题来自这样一个事实,即我从用户那里获取所有角色,将其存储然后将其归还。我不知道是否还有其他方法可以做到,但这就是我发现的。
谢谢!
答案 0 :(得分:1)
出现错误 DiscordAPIError: Unknown Role
是因为您试图从 Discord API 找不到的用户中删除角色。此角色是所有成员都拥有的 @everyone
角色。
您也不需要对角色运行 map
,因为您已经可以遍历缓存集合。
问题中的代码:
const RoleFolder = []
const roles = member.roles.cache.map(role => role);
roles.forEach(role => {
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
可以改为:
const RoleFolder = []
member.roles.cache.forEach(role => {
if (role.id === member.guild.id) return;
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
要忽略discord API中不存在的角色,可以检查:
role.id === member.guild.id
或 role.rawPosition === 0
您可以使用 return
跳过为该特定角色执行代码,这意味着它不会添加到 RoleFolder,并且不会尝试删除该角色。
编辑:我会避免使用 role.name === '@everyone'
,因为用户可以创建一个名为 @everyone
的角色,这会被遗漏,所以我更新了我的答案以检查更好的状态。