简体   繁体   中英

Discord.js v12 How to assign a newly created role to a user?

I am trying to create a new role and instantly assigning it to the user and the person that is mentioned. But it doesn't find the role for me... Usage: $create @user <RoleName> my code:

client.on('message', async message => {
    if (message.content.startsWith(prefix + "create")) {
        let args = message.content.slice(prefix.length).split(/ +/);
        let teamName = args.slice(2).join(" ");
        message.guild.roles.create({
            data:{
            name: `${teamName}`,
            color: "DEFAULT"
        }
        })
    let teamMate = message.mentions.members.first()   
    let teamRole = message.guild.roles.cache.find(role => role.name == `${teamName}`)
    message.member.roles.add(teamRole)
    teamMate.roles.add(teamRole)
    }})

A solution to your problem would be to use await when the role is created and then add the role to the specified user. Here's an example:

const Role = await message.guild.roles.create({ // Creating the role.
    data: {name: "My Role", color: "DEFAULT"}
}).catch((e) => console.error(`Couldn't create role. | ${e}`)); // Catching for errors.

message.member.roles.add(Role).then(() => { // Adding the role to the member.
    message.channel.send(`Role ${Role.name} has been added to ${message.author.tag}`); // Sending a message if the role has been added.
}).catch((e) => console.error(`Couldn't add role. | ${e}`)); // Catching for errors.

There's another solution. You can use the roleCreate event. Example:

client.on("roleCreate", role => { // Listening to the roleCreate event.
    role.guild.members.cache.get("MemberID").roles.add(role);
    // Getting a GuildMember and adding the role.
});

Why are you searching for a role that you create if you can add it with.then() method

const teamName = args.slice(2).join(" ");
const teamMate = message.mentions.members.first()  
message.guild.roles.create({
    data:{
    name: `${teamName}`,
    color: "DEFAULT"
}
}).then(r => teamMate.roles.add(r))

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