Reputation: 27
I've been trying to make my discord bot to add roles to members on my server, but whenever I run my command, it doesn't work and always says:
TypeError: Cannot read the property 'add' of undefined
I've even tried replacing .add()
with .addRole()
, but nothing has worked.
Here is my code:
command(client, 'add', (message) => {
const target = message.mentions.members.first
const role = message.mentions.roles.first
const embed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setDescription(`Added the role ${role}`)
.then(target.roles.addRole(role));
})
console.log('Commands are set')
Upvotes: 1
Views: 221
Reputation: 23160
There are a couple of errors:
mentions.members
and mentions.roles
return collections that have a first()
method (not a property, so you'll need to add parentheses).setDescription()
doesn't return a promise but a MessageEmbed
.then()
you should pass a function but instead you call .addRole()
and pass a valueaddRole()
is simply add()
nowCheck out the code below:
command(client, 'add', async (message) => {
// first is a method not a property
const target = message.mentions.members.first();
const role = message.mentions.roles.first();
// if something is missing, send an error message
if (!role) return message.channel.send('You need to mention a role');
if (!target) return message.channel.send('You need to mention a member');
try {
// add the role
await target.roles.add(role);
const embed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setDescription(`Added the role ${role}`);
message.channel.send(embed);
} catch (err) {
console.err(err);
message.channel.send('Oops, there was an error. Maybe try again?!');
}
});
Upvotes: 3
Reputation: 9571
.then(target.roles.addRole(role));
should probably be
.then(() => target.roles.addRole(role));
beyond that, you need to figure out why target.roles
is undefined. You could start by logging target
.
Upvotes: 0