简体   繁体   English

Discord.js v12 如何为用户分配新创建的角色?

[英]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:但它没有找到适合我的角色......用法: $create @user <RoleName>我的代码:

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.您的问题的解决方案是在创建角色时使用await ,然后将角色添加到指定的用户。 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.您可以使用roleCreate事件。 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如果您可以使用.then() 方法添加它,您为什么要搜索您创建的角色

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

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

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