你如何给一个特定的成员一个角色?Discord.js



我必须创建一个帐户才能发布此消息,但我正在向我的机器人发出!addrole命令,我在弄清楚如何将角色添加到成员中时遇到了一些问题,它一直给我这个错误

TypeError: Cannot read property ‘roles’ of undefined

以下是我一直在做的事情:

if (!message.content.startswith(prefix) || message.author.client) return;
const arguments = message.content.slice(prefix.length).split(‘‘);
const command = arguments.shift().toLowerCase();
if (command === ‘addrole’) {
const role = message.guild.roles.cache.find(role => role.name === ‘ROLE’)
const userId = arguments[0].slice(2, 19) // users id from the message
const user = message.guild.members.cache.get(userId) // user itself 
user.roles.add(role)
}

但它一直给我上面的错误,请帮帮我。另外,请原谅我的大写和索引,我刚刚把代码从电脑复制到手机上,我的浏览器有点故障。你也可以在Ralphiboy22#7118 上dm

有一种更好的方法可以做到这一点,而不是做userId和user等,你可以使用message.mentions.members.first(),就像这样:

const role = message.guild.roles.cache.find(role => role.name === ‘Insert role here’)
const target = message.mentions.members.first();
target.roles.cache.add(role)

你也可以在目标行的底部添加这个:

if(!target) message.channel.send(‘User not found!’)

discord.jsv12及更高版本使用Managers,这意味着您必须通过cache属性传递它。

user.roles.cache.add(role)

GuildMemberRoleManager

最新更新