Unhandled Promise Rejection Warning: TypeError When Adding Role in Discord Bot

I’m facing a problem with the captcha system in my Discord bot. The captcha functionality is properly implemented; however, when attempting to assign a role after successful verification, I receive the following error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property ‘add’ of undefined

Here’s the code I am currently using:

const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = '!';
const CaptchaGenerator = require('@haileybot/captcha-generator');

bot.once('ready', () => {
    console.log('Bot is ready!');
});

let captchaInstance = new CaptchaGenerator();

bot.on('message', async msg => {
    if (!msg.content.startsWith(prefix) || msg.author.bot) return;
    
    const arguments = msg.content.slice(prefix.length).trim().split(/ +/);
    const cmd = arguments.shift().toLowerCase();
    
    if (cmd === 'verify') {
        let captcha = new CaptchaGenerator();
        msg.channel.send(
            '**Please type the text shown in the image:**',
            new Discord.MessageAttachment(captcha.JPEGStream, 'captcha.png')
        );
        let collector = msg.channel.createMessageCollector(m => m.author.id === msg.author.id);
        collector.on('collect', m => {
            if (m.content.toUpperCase() === captcha.value) {
                msg.channel.send('Verification successful!');
                let verifiedRole = msg.guild.roles.cache.find(role => role.name === 'Verified');
                msg.member.roles.add(verifiedRole);
            } else {
                msg.channel.send('Verification failed!');
            }
            collector.stop();
        });
    }
});

bot.login('your-token-here');

Any guidance would be greatly appreciated!

Hi there! Looks like the error might be coming from msg.guild being undefined. Make sure you have the server intent permissions enabled on your discord developer portal and check if the bot has the right permissions to manage roles. Give that a shot!

You might want to ensure that the bot has the necessary permissions within the server, especially the permission to manage roles. Additionally, verify that the role you’re trying to assign exists and is spelled correctly. Sometimes, roles can be case-sensitive or may contain special characters. Lastly, try logging msg.guild and msg.member to check if they are properly defined when the command is executed. Sometimes, certain conditions can cause them to be undefined, leading to the error you’re encountering.