简体   繁体   中英

discord.js cannot read property 'roles' of null

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?

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();
}

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

if (!message.guild) return;

Maybe you should try this

if (message.member.roles.cache.some(role => role.id === 'RoleId')) {
 return message.delete();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM