“ TypeError:无法读取未定义的属性'id'” Discord.js错误

时间:2020-06-11 15:59:22

标签: javascript discord.js

我正在使用Discord.js编写Discord机器人。我有下面的代码,但是运行命令时出现错误:"person.roles.remove(mainrole.id); TypeError: Cannot read property 'id' of undefined"

我不知道如何定义或确切定义什么。任何帮助,将不胜感激,谢谢您。

bot.on('message', msg => {

  let args = msg.content.substring(PREFIX.length).split(" ");

  switch (args[0]) {
    case 'mute':
      let person = msg.guild.member(msg.mentions.users.first() || msg.guild.member.cache.find(args[1]))
      if (!person) {
        return msg.reply("Couldn't find that user");
      }
      let mainrole = msg.guild.roles.cache.find(role => role.name == "Member");
      let muterole = msg.guild.roles.cache.find(role => role.name === "muted");

      if (!muterole) {
        return msg.reply("Couldn't find mute role");
      }

      let time = args[2];

      if (!time){
        return msg.reply("Please specify a time")
      } 

      person.roles.remove(mainrole.id);
      person.roles.add(muterole.id);

      msg.channel.send(`@${person.user.tag} has been muted for @${ms(ms(time))}`);

      setTimeout(function (){
        person.roles.add(mainrole.id);
        person.roles.remove(muterole.id);
        msg.channel.send(`@${person.user.tag} has been unmuted`)
      }, ms(time));


      break;
  }
})

1 个答案:

答案 0 :(得分:0)

似乎您没有满足此条件,role => role.name == "Member"就是mainroleundefined的原因。

您可能可以避免的错误是:

if(mainrole && mainrole.id) {
       person.roles.remove(mainrole.id);
       person.roles.add(muterole.id);
       msg.channel.send(`@${person.user.tag} has been muted for @${ms(ms(time))}`);

       setTimeout(function(){
           person.roles.add(mainrole.id);
           person.roles.remove(muterole.id);
           msg.channel.send(`@${person.user.tag} has been unmuted`)
       }, ms(time));
}