Ralphiboy22
Ralphiboy22

Reputation: 27

How do you give a specific member a role? Discord.js

I had to make an account to post this, but I’m making an !addrole command to my bot and I’m having some troubles figuring out how to add the role to the member, it keeps giving me this error

TypeError: Cannot read property ‘roles’ of undefined

Here’s what I’ve been working on:

if (!message.content.startswith(prefix) || message.author.client) return;
const arguments = message.content.slice(prefix.length).split(‘‘);
const command = arguments.shift().toLowerCase();

if (command === ‘addrole’) {
    const role = message.guild.roles.cache.find(role => role.name === ‘ROLE’)
    const userId = arguments[0].slice(2, 19) // users id from the message
    const user = message.guild.members.cache.get(userId) // user itself 
    user.roles.add(role)
}

But it keeps giving me the error above, please help. Also, excuse my capitalization and indexing, I just copied the code from my computer to my phone, my browser was a bit glitchy. You can also dm on Ralphiboy22#7118

Upvotes: 2

Views: 773

Answers (2)

Ianthecoder
Ianthecoder

Reputation: 56

There is a really better way to do it, instead of doing userId and user and etc., you can use message.mentions.members.first() Like so:

const role = message.guild.roles.cache.find(role => role.name === ‘Insert role here’)
const target = message.mentions.members.first();
target.roles.cache.add(role)

You can also add this on the bottom of the target line:

if(!target) message.channel.send(‘User not found!’)

Upvotes: 1

Lioness100
Lioness100

Reputation: 8402

discord.js v12 and higher uses Managers, which means you have to pass it through the cache property.

user.roles.cache.add(role)

GuildMemberRoleManager

Upvotes: 1

Related Questions