Discord.js TypeError:无法读取 null 的属性“角色”

Posted

技术标签:

【中文标题】Discord.js TypeError:无法读取 null 的属性“角色”【英文标题】:Discord.js TypeError: Cannot read property 'roles' of null 【发布时间】:2021-03-02 08:36:51 【问题描述】:

当我尝试运行我的 discord bot 命令代码时,我收到错误消息“TypeError: Cannot read property 'roles' of null”。这已经完美运行了一年,突然间它不起作用了。

代码的用途是检查成员是否有角色,然后添加或删除角色。

代码:

client.on('message', message => 
if ((message.content === prefix + 'cs') || (message.content === prefix + 'CS')) 
        if (message.member.roles.has('371060297773088768')) 
            message.member.removeRole('371060297773088768')
                .then(() => message.reply('Counter-Strike role removed!'));
         else 
            message.member.addRole('371060297773088768')
                .then(() => message.reply('Counter-Strike role added!'));
        
    
);

PS:这个机器人只适用于一台服务器,所以我为什么不说清楚消息来自哪个公会。

【问题讨论】:

【参考方案1】:

试试这个message.member.roles.cache.has('371060297773088768')

client.on('message', message => 
if ((message.content === prefix + 'cs') || (message.content === prefix + 'CS')) 
        if (message.member.roles.cache.has('371060297773088768')) 
            message.member.removeRole('371060297773088768')
                .then(() => message.reply('Counter-Strike role removed!'));
         else 
            message.member.addRole('371060297773088768')
                .then(() => message.reply('Counter-Strike role added!'));
        
    
);

【讨论】:

添加后出现“TypeError: Cannot read property 'has' of undefined” 好像我有一个过时的版本。对于那个很抱歉。代码有效

以上是关于Discord.js TypeError:无法读取 null 的属性“角色”的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法读取未定义的“获取”函数(discord.js)

Discord.js:TypeError:无法读取未定义的属性“删除”

(Discord.js)TypeError:无法读取未定义的属性“添加”

Discord.js:TypeError:无法读取未定义的属性“get”

discord.js TypeError:无法读取未定义的属性“发送”

node.js/discord.js:TypeError:无法读取 null 的属性“setPresence”