简体   繁体   English

您如何赋予特定成员角色? Discord.js

[英]How do you give a specific member a role? Discord.js

I had to make an account to post this, but I'm making an !addrole command to my bot and I'm having some troubles figuring out how to add the role to the member, it keeps giving me this error我必须创建一个帐户才能发布此内容,但我正在向我的机器人发出!addrole命令,并且在弄清楚如何将角色添加到成员时遇到了一些麻烦,它一直给我这个错误

TypeError: Cannot read property 'roles' of undefined

Here's what I've been working on:这是我一直在做的事情:

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)
}

But it keeps giving me the error above, please help.但它一直给我上面的错误,请帮助。 Also, excuse my capitalization and indexing, I just copied the code from my computer to my phone, my browser was a bit glitchy.另外,请原谅我的大写和索引,我只是将代码从我的电脑复制到我的手机,我的浏览器有点小故障。 You can also dm on Ralphiboy22#7118你也可以在 Ralphiboy22#7118 上私信

discord.js v12 and higher uses Managers , which means you have to pass it through the cache property. discord.js v12 及更高版本使用Managers ,这意味着您必须通过cache属性传递它。

user.roles.cache.add(role)

GuildMemberRoleManager

There is a really better way to do it, instead of doing userId and user and etc., you can use message.mentions.members.first() Like so:有一个更好的方法可以做到这一点,而不是做 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)

You can also add this on the bottom of the target line:您还可以将其添加到目标行的底部:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM