Reputation: 173
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)
}})
Upvotes: 1
Views: 1222
Reputation: 1003
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))
Upvotes: 1
Reputation: 6625
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.
});
Upvotes: 1