Home > Blockchain >  discord.js cannot read property 'roles' of null
discord.js cannot read property 'roles' of null

Time:12-10

I'm having some trouble with my discord bot and I could really use some help

Currently my bot executes this piece of code, and it works perfectly most of the time:

if (message.member.roles.cache.has('917521104908742736')) //muted role
{
        return message.delete();
}

However, from time to time, the bot crashes randomly, giving out the following error:

TypeError: Cannot read property 'roles' of null

I don't know what to do anymore, and even worse is that the program crashes randomly, so I don't know what exactly causes the error. Could you help me, please?

CodePudding user response:

The message object doesn't seem to have the member property (maybe because the message has been sent in DMs), try to add the interogation mark for Optional chaining :

if(message.member?.roles.cache.has('917521104908742736')) {
  return message.delete();
}

CodePudding user response:

The bot simply receives DMs. Check if it's a DM, and return early if it is:

if (!message.guild) return;
  • Related