在message.mentions.users.first().id定义方面遇到麻烦



好吧,我是一个相当新的人,可以使用discord.js来制作一个或两个不偏见的机器人。最近,我正在使用奖牌bot ,如果某人授予该命令,它将授予用户。它看起来大致喜欢:/awardmedal The Copper Cross (INSERT USER@ HERE)每当我运行代码并执行任何奖牌命令时,都会提出以下内容:

Medals.js:21 var usertag = message.mentions.users.first().id; 
                                                         ^
TypeError: Cannot read property 'id' of undefined

我想知道是否有人可以帮助我告诉我我应该做些什么来修复它,谢谢。这是执行此操作的代码:

var prefix = "/"
client.on('ready', () => {
  console.log("ZiloBot Loaded");
});
client.on("message", (message) => {
  var usertag = message.mentions.users.first().id;
  if (message.content.startsWith(prefix + "awardmedal " + "The Copper Cross " + usertag)) {
    if (sjw.includes(message.author.id)) {
      console.log("Awarding Copper Cross to " + usertag);
      message.channel.send("Awarding Copper Cross to " + usertag);
    };
  };
  client.login(mytokenissecret);
});

不必担心sjw变量,它在此之前的代码段中定义。我的主要问题是未定义id的事实。

改进了您的代码:

client.on('ready', () => {
  console.log("ZiloBot Loaded");
});
client.on("message", (message) => {
  const prefix = "/"; // using ES6
  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).trim().split(/ +/g);
  const cmdName = args.shift().toLowerCase();
  if (cmdName === 'awardmedal') {
    // checking if user inluded correct medal name in message.
    let mention = message.mentions.users.first();
    // checking if message don't have a user mention
    if (!mention) return message.channel.send('You need to mention a user.');
    let medals = ['The Copper Cross']; // creating array of medals in case u want to add more medals later on
    let medal = args.join(' ').replace(`<@!${mention.id}>`, '').trim(); // removing mention and spaces from message string
    if (!medals.map(m => m.toLowerCase()).includes(medal.toLowerCase())) {
      message.channel.send(`Please choose one from a list:n${medals.join(', ')}`);
      return;
    }
    if (!sjw.includes(message.author.id)) {
       // if user in not in "sjw"
       return;
    }
    console.log(`Awarding ${medal} to ${mention.name}`);
    message.channel.send(`Awarding ${medal} to ${mention}`);
  }
};
client.login(mytokenissecret);

要首先解决您的主要问题,您需要检查是否存在使用用户,并且只有在获得ID之后。

let mention = message.mentions.users.first();
if (mention) console.log(mention.id);

message.mentions.users.first()不是东西

服务器没有用户,他们有会员,因此请使用

message.mentions.members.first().id

最新更新