【问题标题】:Discord.js mojang-apiDiscord.js mojang-api
【发布时间】:2021-08-04 11:08:38
【问题描述】:

我想编写一个可以通过标题轻松识别的不和谐机器人。

我的问题是我输入时出现错误,例如.args-info "fnfjsn",bot 不再工作。我已经在互联网上寻找了解决方案,不幸的是什么也没找到,但现在我终于到了这里

我很高兴得到任何帮助,并提前感谢您的帮助

const args = msg.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();

if (command === 'args-info') {
  if (!args.length) {
    return msg.channel.send(`You didn't provide any arguments, ${msg.author}!`);
  }

  msg.channel.send(`Command name: ${command}\nArguments: ${args}`);
  MojangAPI.nameToUuid(`${args}`, function (err, res) {
    if (err) {
      console.log(err);
    } else {
      console.log(res[0].name + "? No, they're " + res[0].id + ' to me.');
    }
  });
}

错误:

} else if(res[0].*name* != null) {
TypeError: Cannot read property '*name*' of undefined

【问题讨论】:

  • 嘿@Max,我试图在下面为您提供答案。你有机会去看看吗?有意义吗?如果答案有用,请单击其左侧的点赞按钮 (▲)。如果它回答了您的问题,请单击复选标记 (✓) 接受它。另见What should I do when someone answers my question?

标签: javascript discord discord.js minecraft


【解决方案1】:

我认为,如果没有错误但也没有结果,您的 API 将返回一个空数组 ([])。空数组没有任何元素,因此尝试读取[0] 元素的name 将导致TypeError: Cannot read property 'name' of undefined

要解决这个问题,您需要检查 res 数组是否包含任何元素。

MojangAPI.nameToUuid(`${args}`, function (err, res) {
  if (err)
    return console.log(err);

  if (!res.length)
    return console.log(`No results found for "${args}"`);

  console.log(res[0].name + "? No, they're " + res[0].id + ' to me.');
});

另外,我不确定您是否要像这样对 args 数组进行字符串化,因为它会导致字符串由逗号连接。您可能只想使用第一个参数,或者通过单个空格加入 args

const args = ['first', 'second', 'third'];

console.log(`${args}`);
// => 'first,second,third'
console.log(args[0]);
// => 'first'
console.log(args.join(' '));
// => 'first second third'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 2020-12-28
    • 2017-06-22
    • 2020-12-17
    • 2020-07-02
    • 2020-11-29
    • 2020-11-02
    相关资源
    最近更新 更多