lelbro420
lelbro420

Reputation: 27

TypeError: Cannot read the property 'add' of undefined

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

Answers (2)

Zsolt Meszaros
Zsolt Meszaros

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)
  • you don't handle errors
  • you don't check if there is a mentioned role and a member
  • .setDescription() doesn't return a promise but a MessageEmbed
  • inside .then() you should pass a function but instead you call .addRole() and pass a value
  • if you're using discord.js v12, addRole() is simply add() now

Check 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?!');
  }
});

enter image description here

Upvotes: 3

andy mccullough
andy mccullough

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

Related Questions