如何解决在节点获取之前将字符串与文件数据进行比较的替代解决方案
我正在使用 poke-api 调用 poke-api 来查找有关 Pokemon 的信息的 pokemon 查找命令制作一个不和谐的机器人。我没有返回任何特定错误,我只是在寻找有关如何重新格式化某个部分的指导,因为我是编码新手。 我遇到的主要问题是过滤 pokemon 名称。
if(!args[0]) return message.reply("Enter a Pokemon name or National dex number.");
if(isNaN(args[0])){
let pokemon = args[0];
pokemon.toLowerCase();
fs.readFile('pokemonlowercase.txt',function read(err,data){
if (err) {
return console.log(err);
}
if(!data.includes(`${pokemon}`)) return message.reply(`${pokemon} is not a valid Pokemon name.`); //Does not filter out gibberish that isnt pokemon names.
fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`) //Does this operate before my if statement?
.then(res => res.json())
.then(data => { //lots of defining constants from found api data,and implementing them into a discord embed.
我正在尝试查看文件 pokemonlowercase.txt
以将列出的 Pokemon 名称与输入 pokemon
(或 args[0]
)匹配。如果使用正确的 Pokemon 名称执行该命令可以正常工作,但如果 Pokemon 名称是一堆乱码,则从 api 返回错误。
本质上,bot 会忽略 pokemon
与 pokemonlowercase.txt
中的所有 893 个 pokemon 名称之间的比较。
我正在使用 node-fetch 来获取 api 的信息。
我是否需要使用异步延迟 .fetch 或者参数 !data.includes
是一个不正确的使用场景?我知道 .fetch 是一个承诺,但没有提到它首先会发生。
有关更多上下文,完整的命令代码在这里: https://sourceb.in/Z0qKSGNPw7
解决方法
您可以使用一个名为“axios”的库,它是一个基于承诺的库。
我设法在不使用 pokemon.txt
文件的情况下使其工作。
const axios = require("axios");
// pokemon command
if (command === "pokemon") {
if (!args.length >= 1)
return message.channel.send("Enter a Pokemon name or National dex number.");
// request to API
axios
.get(`https://pokeapi.co/api/v2/pokemon/${args[0].toLowerCase()}`)
.then((data) => data.data)
.then((data) => {
// pokemon exists,do something with your data
console.log(data);
})
.catch((err) => {
if (err.response.status === 404) {
// Pokemon doesn't exist
message.channel.send("That's not a pokemon chief");
} else {
// Error
console.error(err);
}
});
}
如果 pokemon 不存在,PokeAPI 会返回 404 状态,这意味着一旦您请求,您可以检查状态是否为 404 类型,如果是,则 pokemon 不存在,如果不存在则为 pokemon存在(或发生错误)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。