简体   繁体   English

discord.js 无法读取 null 的属性“角色”

[英]discord.js cannot read property 'roles' of null

I'm having some trouble with my discord bot and I could really use some help我的 discord 机器人遇到了一些问题,我真的需要一些帮助

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 :消息 object 似乎没有 member 属性(可能是因为消息已在 DM 中发送),尝试为Optional chaining添加询问标记:

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

The bot simply receives DMs.机器人只是接收 DM。 Check if it's a DM, and return early if it is:检查是否是 DM,如果是则尽早返回:

if (!message.guild) return;

Maybe you should try this也许你应该试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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