【问题标题】:How can I get a Minecraft player's UUID from their username in NodeJS?如何从 NodeJS 中的用户名中获取 Minecraft 玩家的 UUID?
【发布时间】:2020-09-17 05:00:38
【问题描述】:

我知道还有很多其他帖子都在问同样的问题,但其他帖子都没有解决我的问题。我正在使用 NodeJS 和 DiscordJS 创建一个 discord 机器人,我需要从 Minecraft 玩家的用户名中获取 UUID,该用户名将作为命令中的参数提供。

这是我为此创建的函数,但它似乎不起作用。

  function getId(playername) {
    const { data } = fetch(`https://api.mojang.com/users/profiles/minecraft/${args[2]}`)
    .then(data => data.json())
    .then(({ player }) => {
      return player.id;
    });
  }

args[2] 是命令的第三个参数,格式如下:<prefix> id <playername>fetch 是我安装的“node-fetch”npm 模块的一部分。我在发送命令时调用该函数,它从 Mojang 的 API 获取数据,但无法获取 UUID。这是错误:

(node:39416) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
    at C:\Users\archi\OneDrive\Documents\Programming\Discord Bots\Hypixel Discord Bot\index.js:161:21
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
(node:39416) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:39416) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

它是说它无法读取'id'的属性,如果你使用Mojang API,它是玩家UUID的关键。有什么想法吗?

【问题讨论】:

  • mojang api 表示它返回一个包含对象的数组。您假设它只返回一个对象。 return player[0].id 或许。
  • 该页面还显示了应如何格式化有效负载我不确定您是否完全正确。检查您的浏览器开发工具网络选项卡,找到 api 调用并检查参数是否正确。
  • @James 不幸的是这不起作用,尽管我知道你来自哪里。在 wiki 上,有两种从名称中获取 UUID 的不同方式,一种是 POST,一种是 GET,这在 JS 中的实现方式有区别吗?
  • 供参考,using fetch

标签: javascript node.js discord.js minecraft


【解决方案1】:

尝试在请求 URL 中使用 playername 而不是 args[2],并使其返回一个承诺。也没有必要使用{ player },因为 API 返回的对象没有玩家专有。只需使用player 作为箭头函数的参数即可。

function getId(playername) {
  return fetch(`https://api.mojang.com/users/profiles/minecraft/${playername}`)
    .then(data => data.json())
    .then(player => player.id);
}

然后在你的代码中这样调用它:

// Using .then (anywhere)
getId(args[2]).then(id => {
  console.log(`ID is ${id}`)
})
// Using await (inside of an async function)
const id = await getId(args[2])
console.log(`ID is ${id}`)

【讨论】:

  • 仍然出现同样的错误,该函数没有返回任何内容
  • @ArchieMargretts 我已经更新了答案,请再次检查:)
  • 我再次更新了它。我忽略了一件产生巨大影响的小事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 2015-09-09
相关资源
最近更新 更多