无法读取未定义 'highest' 的属性

cannot read the properties of undefined 'highest'

我想检查提到角色的成员是否与机器人的位置相同或更高,但出现错误。

const member = message.mentions.users.first();
const reason = args.slice(1).join(' ') || 'No reason specified.'

if (member.roles.highest.position >= message.guild.client.roles.highest.position) return message.reply('I cannot moderate this user as their highest role is higher than mine or I have the same highest role position as them.')

错误:

TypeError: Cannot read properties of undefined (reading 'highest')

我是 discord.js v13 和 Node.js v16

重要的是要记住,在 Discord 中(以及因此 Discord.js),UserMember 绝对不同。 message.mentions.users.first(); returns 一个 User object,其中没有任何 属性 名为 roles.

您似乎想要 members property on message.mentions instead, which returns a Collection of GuildMember objects,每个 应该roles 属性:

const member = message.mentions.members.first();
const reason = args.slice(1).join(' ') || 'No reason specified.'

if (member.roles.highest.position >= message.guild.client.roles.highest.position) return message.reply('I cannot moderate this user as their highest role is higher than mine or I have the same highest role position as them.')

您正在使用将 User 分配给 member,并且 message.guild.client returns 没有 .rolesClient 对象.使用 .mentions.members.guild.me 代替

const member = message.mentions.members.first();
const reason = args.slice(1).join(' ') || 'No reason specified.'

if (member.roles.highest.position >= message.guild.me.roles.highest.position) return message.reply('...')

当您使用 message.guild.client 时,您会得到实例化公会的客户端,它没有 roles 属性。相反,您可以使用:

const member = message.mentions.members.first();
const botMember = message.guild.members.cache.get(client.user.id)
const reason = args.slice(1).join(' ') || 'No reason specified.'

if (member.roles.highest.position >= botMember.roles.highest.position) return message.reply('I cannot moderate this user as their highest role is higher than mine or I have the same highest role position as them.')