简体   繁体   中英

How can I add a role to a guildMember?

I'm trying to give a user a role, but then I get this error:

error: member is not defined.

I would like to give the new user the Test role. This is my attempt:

client.on('message' , (message) =>{
    if(!message.member.user.bot && message.guild){
       if(message.content == '!test'){
            var role = member.guild.roles.cache.find(role => role.name == "Test");
            member.roles.add(role);
        }
    }
})

client.login(config.token) 

Your problem is in this line:

var role = member.guild.roles.cache.find(role => role.name == "Test");

and also this:

member.roles.add(role);

because you are not defining member . I think you just forgot the message. at the beginning.

You should change it to this:

var role = message.member.guild.roles.cache.find(role => role.name == "Test");
message.member.roles.add(role);

You may consider fetching roles by their ID in case the name gets changed. You then want to use:

message.member.roles.cache.has(role.id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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