const fetch = require("node-fetch");
const Discord = module.require("discord.js");
module.exports = {
name: "ability",
aliases: ["abilities"],
description: "Displays pokedex information for a given pokemon",
category: "util",
requiredArgs: ["query"],
run: async (client, message, args) => {
const query = args.join(" ");
if (!query) {
return message.channel.send("Try Again This Time With A Pokemon Name");
}
try {
const data = await fetch(
`https://pokeapi.co/api/v2/ability/${encodeURIComponent(
query
)}`
).then((res) => res.json());
let embed = new Discord.MessageEmbed()
.setDescription(`*${data.flavor_text_entries.flavor_text[1]}*`)
message.reply({ embeds: [embed] });
} catch(err) {
console.log(err);
message.reply('NO DATA FOUND')
}
},
};
How can I get the ability description? I didn't found anything about obtaining specific details from the API in docs, so I would appreciate your help!
From what I can see by looking at their API, you'll get a multidimensional array, which you'll need to iterate through in order to fetch the description you need.
A good method in this case is to use the for in loop, which is optimal, because you can opt to break out once you've accessed the value you were looking for.
I can't tell by your question, how you're processing the data exactly, so I took the liberty to make my own structure. Feel free to use it, edit it, or do whatever to suit your needs.
Note that the structure of the fetch I am making is dynamic to "some extent", like choosing the ability to describe, as well as what language it should be displayed in.
In my example, I'll use the ability that has the value of 4, also known as battle-armor in their API register. The result will be in English for my example.
When running the snippet, wait a few seconds for the response to go through.
const getDescription = async (value, lang='en') => {
const dataList = await fetch(`https://pokeapi.co/api/v2/ability/${value}`)
.then(response => response.json())
.catch((error) => console.log(error));
if (dataList) {
for (const entry in dataList) {
if (entry === 'flavor_text_entries') {
for (const flavor in dataList[`${entry}`]) {
if (dataList[`${entry}`][`${flavor}`]['language'].name === `${lang}`) {
console.log(dataList[`${entry}`][`${flavor}`].flavor_text);
break;
}
}
}
}
} else {
console.log('No data!');
}
};
getDescription(4, 'en');
Codepen here.