custom PokeAPI middleware

This commit is contained in:
Emily 2020-11-02 13:13:34 +11:00
parent 678aed92e4
commit c81ca81d2e
4 changed files with 96 additions and 113 deletions

View file

@ -1,6 +1,5 @@
const Embed = require('../../util/embed'); const Embed = require('../../util/embed');
const Pokedex = require('pokedex-promise-v2'); const API = new (require('../../util/pokeapi'));
const Dex = new Pokedex();
module.exports = class { module.exports = class {
constructor (name, category) { constructor (name, category) {
@ -21,98 +20,58 @@ module.exports = class {
} }
async run (client, message, args, data) { //eslint-disable-line no-unused-vars async run (client, message, args, data) { //eslint-disable-line no-unused-vars
const forms = [
'mega',
'alola',
'alolan',
'galar',
'galarian'
];
let query = args.join(' '); let query = args.join(' ');
let form = '';
let spritePrefix = '';
for (let i = 0; i < forms.length; i++) {
if (query.indexOf(forms[i]) > -1) {
query = query.replace(forms[i], '');
if (forms[i] === '-galarian') {
form += 'galar';
} else if (forms[i] === '-alolan') {
form += '-alola';
} else {
form += `-${forms[i]}`;
}
if (forms[i] === 'alola') {
spritePrefix = 'alolan-';
} else if (forms[i] === 'galar') {
spritePrefix = 'galarian-';
} else {
spritePrefix = `${forms[i]}-`;
}
break;
}
}
query = query.trim(); query = query.trim();
const pokemon = await Dex.resource('/api/v2/pokemon/' + query + form); const pokemon = await API.fetchPokemon(args.join(' '));
const pokeSpecies = await Dex.resource('/api/v2/pokemon-species/' + pokemon.species.name);
let evoData = await Dex.resource(pokeSpecies.evolution_chain.url);
evoData = evoData.chain;
const typeArray = []; const typeArray = [];
for (let i = 0; i < pokemon.types.length; i++) { for (let i = 0; i < pokemon.info.types.length; i++) {
typeArray.push(pokemon.types[i].type.name.toProperCase()); typeArray.push(pokemon.info.types[i].type.name.toProperCase());
} }
const abilityArray = []; const abilityArray = [];
for (let i = 0; i < pokemon.abilities.length; i++) { for (let i = 0; i < pokemon.info.abilities.length; i++) {
let ability = pokemon.abilities[i].ability.name.toProperCase(); let ability = pokemon.info.abilities[i].ability.name.toProperCase();
if (pokemon.abilities[i].is_hidden === true) ability = `*${ability}*`; if (pokemon.info.abilities[i].is_hidden === true) ability = `*${ability}*`;
abilityArray.push(ability); abilityArray.push(ability);
} }
const evoArray = []; const evoArray = [];
do { do {
const numberOfEvolutions = evoData.evolves_to.length; const numberOfEvolutions = pokemon.evolutions.chain.evolves_to.length;
evoArray.push(evoData.species.name.toProperCase()); evoArray.push(pokemon.evolutions.chain.species.name.toProperCase());
if (numberOfEvolutions > 1) { if (numberOfEvolutions > 1) {
for (let i = 1;i < numberOfEvolutions; i++) { for (let i = 1;i < numberOfEvolutions; i++) {
evoArray.push(evoData.species.name.toProperCase()); evoArray.push(pokemon.evolutions.chain.species.name.toProperCase());
} }
} }
evoData = evoData.evolves_to[0]; pokemon.evolutions.chain = pokemon.evolutions.chain.evolves_to[0];
} while (evoData != undefined && evoData.hasOwnProperty('evolves_to')); //eslint-disable-line no-prototype-builtins } while (pokemon.evolutions.chain != undefined && pokemon.evolutions.chain.hasOwnProperty('evolves_to')); //eslint-disable-line no-prototype-builtins
console.log(evoArray)
const filtered = pokeSpecies.flavor_text_entries.filter(text => text.language.name === 'en'); const filtered = pokemon.species.flavor_text_entries.filter(text => text.language.name === 'en');
const description = filtered[0].flavor_text.replace(/(\r\n|\n|\r)/gm, ' ').replace(/\s+/g,' '); const description = filtered[0].flavor_text.replace(/(\r\n|\n|\r)/gm, ' ').replace(/\s+/g,' ');
const sprite = API.fetchSprite(query);
let spritePath = 'normal';
const random = client.functions.intBetween(0, 100);
if (random === 69) spritePath = 'shiny';
console.log(`https://raw.githubusercontent.com/woomyware/rotom-b-data/master/sprites/pokemon/${spritePath}/${spritePrefix}${query}.gif`);
const embed = new Embed() const embed = new Embed()
.setTitle(pokemon.name.toProperCase()) .setTitle(pokemon.info.name.toProperCase())
.setThumbnail(`https://raw.githubusercontent.com/woomyware/rotom-b-data/master/sprites/pokemon/${spritePath}/${spritePrefix}${query}.gif`) .setThumbnail(sprite)
.setDescription(description.replace('\n', '')) .setDescription(description.replace('\n', ''))
.addField('**Types:**', typeArray.join(', '), true) .addField('**Types:**', typeArray.join(', '), true)
.addField('**Abilities:**', abilityArray.join(', '), true); .addField('**Abilities:**', abilityArray.join(', '), true);
if (evoArray.length > 1) embed.addField('**Evolution Chain:**', evoArray.join(' → ').replace(pokeSpecies.name.toProperCase(), `**${pokeSpecies.name.toProperCase()}**`)); if (evoArray.length > 1) embed.addField('**Evolution Chain:**', evoArray.join(' → ').replace(pokemon.species.name.toProperCase(), `**${pokemon.species.name.toProperCase()}**`));
embed.addField('**Base Stats:**', `**HP:** ${pokemon.stats[0].base_stat} **Atk:** ${pokemon.stats[1].base_stat} **Def:** ${pokemon.stats[2].base_stat} **SpA:** ${pokemon.stats[3].base_stat} **SpD:** ${pokemon.stats[4].base_stat} **Spe:** ${pokemon.stats[5].base_stat}`); embed.addField('**Base Stats:**', `**HP:** ${pokemon.info.stats[0].base_stat} **Atk:** ${pokemon.info.stats[1].base_stat} **Def:** ${pokemon.info.stats[2].base_stat} **SpA:** ${pokemon.info.stats[3].base_stat} **SpD:** ${pokemon.info.stats[4].base_stat} **Spe:** ${pokemon.info.stats[5].base_stat}`);
message.channel.createMessage({ embed: embed }); message.channel.createMessage({ embed: embed });
} }
}; };

76
bot/util/pokeapi.js Normal file
View file

@ -0,0 +1,76 @@
const fetch = require('node-fetch');
const { Collection } = require('eris');
class PokeAPI {
constructor (client) {
this.client = client;
this.cache = new Collection();
this.url = 'https://pokeapi.co/api/v2';
this.forms = [
'mega',
'alola',
'alolan',
'galar',
'galarian'
];
}
async fetchPokemon (query) {
let form = '';
for (let i = 0; i < this.forms.length; i++) {
if (query.indexOf( this.forms[i]) > -1) {
query = query.replace( this.forms[i], '');
if ( this.forms[i] === '-galarian') {
form += 'galar';
} else if ( this.forms[i] === '-alolan') {
form += '-alola';
} else {
form += `-${ this.forms[i]}`;
}
break;
}
}
query = query.trim();
if (this.cache.has(query + form)) return this.cache.get(query + form);
const pokeData = {};
const info = await fetch(this.url + '/pokemon/' + query + form);
pokeData.info = await info.json();
const species = await fetch(this.url + '/pokemon-species/' + pokeData.info.species.name);
pokeData.species = await species.json();
const evolutions = await fetch(pokeData.species.evolution_chain.url);
pokeData.evolutions = await evolutions.json();
this.cache.set(query + form, pokeData);
return pokeData;
}
fetchSprite (query) {
let spritePrefix = '';
for (let i = 0; i < this.forms.length; i++) {
if (query.indexOf( this.forms[i]) > -1) {
query = query.replace( this.forms[i], '');
if ( this.forms[i] === 'alola') {
spritePrefix = 'alolan-';
} else if ( this.forms[i] === 'galar') {
spritePrefix = 'galarian-';
} else {
spritePrefix = `${ this.forms[i]}-`;
}
break;
}
}
let spritePath = 'normal';
if (Math.floor((Math.random() * 100) + 1) === 69) spritePath = 'shiny';
return `https://raw.githubusercontent.com/woomyware/rotom-b-data/master/sprites/pokemon/${spritePath}/${spritePrefix}${query}.gif`;
}
}
module.exports = PokeAPI;

51
package-lock.json generated
View file

@ -224,14 +224,6 @@
"resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz",
"integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==" "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg=="
}, },
"axios": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz",
"integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==",
"requires": {
"follow-redirects": "1.5.10"
}
},
"balanced-match": { "balanced-match": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
@ -533,29 +525,6 @@
"resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz", "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz",
"integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==" "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA=="
}, },
"follow-redirects": {
"version": "1.5.10",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz",
"integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==",
"requires": {
"debug": "=3.1.0"
},
"dependencies": {
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
}
},
"fs-readdir-recursive": { "fs-readdir-recursive": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz", "resolved": "https://registry.npmjs.org/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz",
@ -713,11 +682,6 @@
"resolved": "https://registry.npmjs.org/lru_map/-/lru_map-0.3.3.tgz", "resolved": "https://registry.npmjs.org/lru_map/-/lru_map-0.3.3.tgz",
"integrity": "sha1-tcg1G5Rky9dQM1p5ZQoOwOVhGN0=" "integrity": "sha1-tcg1G5Rky9dQM1p5ZQoOwOVhGN0="
}, },
"memory-cache": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/memory-cache/-/memory-cache-0.2.0.tgz",
"integrity": "sha1-eJCwHVLADI68nVM+H46xfjA0hxo="
},
"minimatch": { "minimatch": {
"version": "3.0.4", "version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
@ -781,11 +745,6 @@
"integrity": "sha512-DcBadTdYTUuH9zQtepsLjQn4Ll6rs3dmeFvN+SD0ThPnxRBRm/WC1zXWPg+wgAJimB784gdZvUMA57gDP7FdVg==", "integrity": "sha512-DcBadTdYTUuH9zQtepsLjQn4Ll6rs3dmeFvN+SD0ThPnxRBRm/WC1zXWPg+wgAJimB784gdZvUMA57gDP7FdVg==",
"optional": true "optional": true
}, },
"p-map": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz",
"integrity": "sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw=="
},
"packet-reader": { "packet-reader": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/packet-reader/-/packet-reader-1.0.0.tgz", "resolved": "https://registry.npmjs.org/packet-reader/-/packet-reader-1.0.0.tgz",
@ -868,16 +827,6 @@
"split2": "^3.1.1" "split2": "^3.1.1"
} }
}, },
"pokedex-promise-v2": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/pokedex-promise-v2/-/pokedex-promise-v2-3.2.0.tgz",
"integrity": "sha512-pW9WHIIKqxC+tjuXSfL19StxJdh6QAQCmErn9fOx0/0XZ+Zg2913ftJOa/cxGOrAhAQ8EhJZJb/oZLAmG2K2Dw==",
"requires": {
"axios": "^0.19.0",
"memory-cache": "^0.2.0",
"p-map": "^2.1.0"
}
},
"postgres-array": { "postgres-array": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",

View file

@ -14,7 +14,6 @@
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"pg": "^8.4.2", "pg": "^8.4.2",
"pg-format": "^1.0.4", "pg-format": "^1.0.4",
"pokedex-promise-v2": "^3.2.0",
"windrose": "^2.1.0" "windrose": "^2.1.0"
}, },
"devDependencies": {}, "devDependencies": {},