我正在制作一个discord bot,我想制作一个命令,将指定的角色添加到指定的用户中。代码执行良好,但当我尝试执行命令时,它显示错误
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'highest' of undefined
at Object.execute (/home/runner/Discord-Bot/commands/moderation/addrole.js:16:22)
at Client.<anonymous> (/home/runner/Discord-Bot/index.js:57:11)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Discord-Bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Discord-Bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Discord-Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Discord-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/Discord-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/Discord-Bot/node_modules/ws/lib/event-target.js:132:16)
(node:4928) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4928) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
";addrole.js";发生错误的是
if (member.roles.highest.position >= message.member.roles.highest.position)
return message.channel.send('You cannot add a role to someone with an equal or higher role');
有人知道为什么会发生这种事吗?完整代码请点击此处
问题是message.mentions.users
返回User
的集合,而User
没有角色。只有GuildMember
具有。虽然User
是Discord上的全局用户,但GuildMember
是特定服务器上的用户,该成员在该服务器上具有角色。
因此,应该使用返回GuildMember
的集合的message.mentions.members
而不是message.mentions.users
:
const member = message.mentions.members.first();
消息中的错误不言自明。
TypeError: Cannot read property 'highest' of undefined
尝试在undefined
上访问属性highest
(它没有这样的属性(。
从您的代码访问member.roles.highest.position
。由此,我们可以得出结论,在您执行代码的情况下,member.roles
就是undefined
。