0
votes

I am working on creating a Discord bot that creates a role based on arguments entered in the command and then assigns that role to mentioned users in the same message. The role gets created just fine, but I'm having issues then assigning the role to even the author of the message (me) let alone multiple mentions within the message. I've deduced that the role cannot be found, so therefore it cannot be assigned to the users, but I don't know why it can't be found.

I'm using

message.guild.roles.create({
    data: {
        name: roleName,
        color: 'BLUE'
    }
})
.catch(console.error);

(where roleName is defined as the first argument of the command) to create the role, and then

let role = message.guild.roles.cache.find(role => role.name === roleName);

to search for the role by name (which I attempt to print to the console, but it is returned as undefined).

Is it possible to both create and give a role within one command?

1

1 Answers

0
votes

First of all, there really isn't a need in using the find() function in your case! You could simply define your newly created role object as so:

message.guild.roles.create({
data: {
    name: roleName,
    color: 'BLUE'
}
}).catch(console.error).then(role => {
// Our following code will be placed here
})

From there on, in order to assign the role to all mentioned members in the message, we could simply use the message.mentions and the forEach() function in order to get every member object and assign the role to it.

message.mentions.members.forEach(member => {
        member.roles.add(role)
    })

Finally, your code should be looking like this:

message.guild.roles.create({
        data: {
            name: roleName,
            color: 'BLUE'
        }
    }).catch(console.error).then(role => {
        message.mentions.members.forEach(member => {
            member.roles.add(role)
        })
    })