SirArchibald
SirArchibald

Reputation: 516

How can I get a Minecraft player's UUID from their username in NodeJS?

I know there are lots of other posts asking this same questions, but none of the others had the solution to my problem. I am using NodeJS and DiscordJS to create a discord bot, and I need to get the UUID of a Minecraft player from just their username, which will be provided as an argument in the command.

This is the function I have created to do this, however it doesn't seem to be working.

  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] is the third argument of the command, which is formatted like this: <prefix> id <playername>. fetch is part of the 'node-fetch' npm module, which I have installed. I call the function when the command is sent, and it fetches the data from Mojang's API, but it can't get the UUID. This is the error:

(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.

It is saying it cannot read the property of 'id', which if you use the Mojang API, is the key for the UUID of a player. Any ideas?

Upvotes: 0

Views: 10321

Answers (1)

Pedro Fracassi
Pedro Fracassi

Reputation: 3925

Try using the playername instead of args[2] in the request URL, and making it return a promise. There's also no need to use { player }, as the object the API returns doesn't have a player propriety. Just use player as the argument for the arrow function.

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

Then call it like so in your code:

// 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}`)

Upvotes: 3

Related Questions