" TypeError: Cannot read property 'cache' of undefined" and "TypeError: Cannot read property 'roles' of null"

Issue

The bot works completely fine before but suddenly it crashed itself with the error "TypeError: Cannot read property ‘cache’ of undefined" and even if it don’t, I am not able to add roles using the bot.(TypeError: Cannot read property ‘roles’ of null) Did discord changed anything? Please help me with this. Thank you.

Here is the errors I got: https://pastebin.com/PWc8MAvU

Below is the code I’ve been using

const Discord = require('discord.js');
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION','GUILD_MEMBER', 'USER'] });

bot.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.partial) {
        try {
            await reaction.fetch();
        } catch (error) {
            console.log('Error when fetch msg ', error);
            return;
        }
    }
    
    if(reaction.message.id === "the id of message for users to react to"){
        if(reaction.emoji.name === '🥕'){
            console.log(user.username+' verified')            
            let member = bot.guilds.resolve('My server's id').members.resolve(user.id);
            member.roles.add('Id of the role I want to add');
        }
    }
});

Solution

Your issue here is that sometimes, the member isn’t cached yet when you try to get their roles (By default, only a small part of members are cached). Instead of using resolve(), I would suggest using fetch() and an async system, so if the user isn’t cached, the bot will cache it first before getting their roles.

const Discord = require('discord.js');
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION','GUILD_MEMBER', 'USER'] });

bot.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.partial) {
        try {
            await reaction.fetch();
        } catch (error) {
            console.log('Error when fetch msg ', error);
            return;
        }
    }
    
    if(reaction.message.id === "the id of message for users to react to"){
        if(reaction.emoji.name === '🥕'){
            console.log(user.username+' verified');
            let guild = bot.guilds.cache.get("My server's id");
            guild.members.fetch(user.id)
            .then(member -> {
                member.roles.add('Id of the role I want to add');
            }).catch(console.error);
        }
    }
});

Answered By – Dorian349

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.