Discord Bot TypeError: Unable to access 'add' on undefined during role assignment

I’m having trouble with my Discord bot’s captcha system. The captcha works fine, but when it tries to add a role after verification, I get this error:

handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined

Here’s a simplified version of my code:

const Discord = require('discord-api');
const bot = new Discord.Bot();
const CaptchaGen = require('captcha-maker');

bot.on('message', async msg => {
  if (msg.content === '!verify') {
    let captcha = new CaptchaGen();
    msg.channel.send('Type the text in this image:', { files: [captcha.image] });

    const response = await msg.channel.awaitMessages(m => m.author.id === msg.author.id, { max: 1, time: 30000 });
    
    if (response.first().content === captcha.text) {
      msg.reply('Verification successful!');
      let verifiedRole = msg.guild.roles.cache.find(r => r.name === 'Verified');
      msg.author.roles.add(verifiedRole);
    } else {
      msg.reply('Verification failed. Try again.');
    }
  }
});

bot.login('BOT_TOKEN');

Can someone help me figure out why the role assignment isn’t working? Thanks!

yo, had same prob. ur using msg.author instead of guild member. try this:

let member = msg.guild.members.cache.get(msg.author.id);
member.roles.add(verifiedRole);

make sure bot has perms to manage roles too. good luck!

I ran into a similar issue with role assignment in my Discord bot. The problem is likely that you’re trying to add a role to the message author (msg.author) instead of the guild member.

Try modifying your code to use GuildMember instead:

if (response.first().content === captcha.text) {
  msg.reply('Verification successful!');
  let verifiedRole = msg.guild.roles.cache.find(r => r.name === 'Verified');
  let member = msg.guild.members.cache.get(msg.author.id);
  await member.roles.add(verifiedRole);
}

This fetches the GuildMember object, which has the roles property with the add method. Also, make sure the bot has the necessary permissions to manage roles in the server.

If you’re still having issues, double-check that ‘Verified’ role exists and that the bot’s role is higher in the hierarchy than the role it’s trying to assign.

In my experience with Discord bots, the issue stemmed from trying to access the roles of the user object rather than the corresponding guild member. Instead of using msg.author directly, you should fetch the guild member using await msg.guild.members.fetch(msg.author.id) and then add the role with await member.roles.add(verifiedRole). This adjustment ensures you work with the object that actually has the roles property. Additionally, verify that the bot has the MANAGE_ROLES permission and that the ‘Verified’ role exists and is higher in the role hierarchy than the bot’s current role.