javascript - message.mentions.users.first().id 定义有问题

标签 javascript discord.js

好吧,我是 javascript 的新手,一直在使用 Discord.js 制作一两个 Discord 机器人。我最近在开发一个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 变量,它是在此之前的一段代码中定义的。我的主要问题是 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);

关于javascript - message.mentions.users.first().id 定义有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55238334/

相关文章:

javascript - r未定义,获取用户拥有的所有角色

javascript - 如何跟踪 Mixpanel 中 youtube 嵌入式视频的播放按钮点击?

javascript - ActiveX C++ 控件 WriteFile 在尝试 4 次后失败

javascript - 滚动底层图像时在覆盖的 div 上滚动内容

javascript - 如何在简单的YouTube api搜索javascript中隐藏引号和amp

node.js - Discord 机器人无法通过 ID 获取用户集合

javascript - 尝试在成员加入服务器时添加角色

javascript - 解析 ISO-8601 格式日期在 IE 9 中不起作用

用于跨浏览器检测隐身模式(私有(private)浏览)的 JavaScript

javascript - 使用某种循环添加到字符串中