Discord.js mojang-api

Viewed 86

I wanted to program a discord bot as can be easily recognized by the title.

My problem is that I get an error when I enter, for example .args-info "fnfjsn", the bot no longer works. I have already looked for a solution on the internet and unfortunately found nothing, but now I've ended up here

I am happy about any help and thank you in advance for your help

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.');
    }
  });
}

The error:

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

I think, if there is no error but no results either, your API will return an empty array ([]). An empty array doesn't have any elements so trying to read the name of the [0] element will result in a TypeError: Cannot read property 'name' of undefined.

To solve this, you'll need to check if the res array contains any elements.

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.');
});

Also, I'm not sure you want to stringify the args array like that as it will result in a string joined by commas. You probably want to use the first argument only, or join the args by a sinlge space:

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

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

Related