【问题标题】:Having trouble with message.mentions.users.first().id definitionmessage.mentions.users.first().id 定义有问题
【发布时间】:2020-11-13 06:51:48
【问题描述】:

好的,我是 javascript 的新手,并且一直在使用 Discord.js 制作一两个 Discord Bot。我最近正在开发一个Medal 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 变量,它是在此之前的一段sn-p 代码中定义的。我的主要问题是id 没有定义。

【问题讨论】:

  • 您确定邮件中包含提及吗?如果您尝试登录 message.mentions.users 会显示什么?另外,/ 前缀已经被 Discord 使用,你不应该使用它,因为它可能会导致错误。

标签: javascript discord.js


【解决方案1】:

稍微改进了你的代码:

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);

【讨论】:

    【解决方案2】:

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

    服务器没有用户,他们有成员,所以使用

    message.mentions.members.first().id
    

    【讨论】:

    猜你喜欢
    • 2021-06-28
    • 2018-12-02
    • 2013-06-03
    • 2018-10-24
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多