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

时间:2020-07-08 13:30:28

标签: javascript discord discord.js

我正在尝试创建一个新角色,并将其立即分配给用户和所提到的人。但却找不到适合我的角色...用法:$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)
    }})

2 个答案:

答案 0 :(得分:1)

解决此问题的方法是在创建角色时使用await,然后将角色添加到指定的用户。这是一个示例:

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.

还有另一种解决方案。您可以使用roleCreate事件。示例:

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

答案 1 :(得分:1)

如果可以使用.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))