JS Discord Bot“无法读取未定义的属性'角色'

时间:2018-02-12 17:13:29

标签: javascript node.js discord.js

“bot.js”:https://AppName.host.name/Home/ “mute.js”:https://hastebin.com/hujexulemo.js

当我尝试运行代码时 我收到这个错误:

let mutedRole = guild.roles.get(r => r.name === " Muted ");
                      ^
TypeError: Cannot read property 'roles' of undefined
    at Timeout.bot.setInterval [as _onTimeout] (E:\DiscordBot\bot.js:40:35)
    at ontimeout (timers.js:475:11)
    at tryOnTimeout (timers.js:310:5)
    at Timer.listOnTimeout (timers.js:270:5)
[nodemon] app crashed - waiting for file changes before starting...

1 个答案:

答案 0 :(得分:2)

与此问题相关的代码(来自您的hastebin链接)是以下两行:

let guild = bot.guilds.get(guildId);
let mutedRole = guild.roles.get(r => r.name === " Muted ");

您收到的错误来自第二行中的guild.roles,其中guildundefined,这表示其上没有属性roles。当bot.guilds.get(guildId)找不到ID为guildId的公会时,可能会发生这种情况。

要解决此问题,请在致电guildId之前确保您的bot.guilds.get(guildId)正确无误,或在guild行之前检查let mutedRole = ...是否存在。

Map .get函数的文档为here

注意困惑的Discord.js开发者: .get文档中仅提及.find()函数

  

请勿使用此[ array (size=646) 0 => object(stdClass)[1] public 'id' => string '1' (length=1) public 'name' => string 'John' (length=4) public 'city' => string 'NY' (length=2) 1 => object(stdClass)[3] public 'id' => string '2' (length=1) public 'name' => string 'Henry' (length=5) public 'city' => string 'Mexico' (length=6) 2 => object(stdClass)[5] public 'id' => string '2' (length=1) public 'name' => string 'Jordan' (length=6) public 'city' => string 'Lake' (length=4) ... ]按ID获取项目。相反,使用collection.get(id)。有关详细信息,请参阅Collection.find(...)

这让我困惑了一段时间,所以希望它能帮助别人:)