首页 > 解决方案 > 从 PokeAPI for DiscordBot 以 JSON 格式显示 JS 对象

问题描述

我正在尝试使用我的不和谐机器人并从 PokeApi 获取信息,特别是口袋妖怪的移动列表。我有以下代码,但我正在努力弄清楚如何获取每个口袋妖怪的移动列表。

client.on('message',(async message =>{
    const args = message.content.toLowerCase().slice(poke.prefix.length).split(/ +/);
    if(!message.content.startsWith(poke.prefix))return;
    if(args[0] === "api"){
        const fetch = require ('node-fetch');
        fetch('https://pokeapi.co/api/v2/pokemon/25')
        .then(res => res.json())
        .then(data => message.channel.send(data.name.moves.move.name))
        .catch(err => message.reply('that spell does not exist!'));}}))

现在我知道我在这里指定了一个特定的口袋妖怪(第 25 号),这很好,因为我可以稍后更改它,但这似乎是让我退缩的部分:

.then(data => message.channel.send(data.name.moves.move.name))

还有一种干净的方法来创建数据嵌入。我必须创建一个包含信息的变量还是可以使用“res”?

非常感谢任何帮助或指导!谢谢!

标签: node.jsjsondiscordpokeapi

解决方案


您从 API 中分割数据的方式不正确。响应中没有 data.name.moves.move.name,所以读取它会导致以下错误:

TypeError: Cannot read property 'move' of undefined

相反,响应看起来更像以下内容(仅显示相关位):

{
  "name": "pikachu",
  "moves": [
    {
      "move": {
        "name": "mega-punch",
        "url": "https://pokeapi.co/api/v2/move/5/"
      }
    },
    {
      "move": {
        "name": "pay-day",
        "url": "https://pokeapi.co/api/v2/move/6/"
      }
    },
    ...
  ]
}

因此,根据您想要对这些动作做什么,您需要将一系列动作按摩成您想要的格式。例如,要给他们一个逗号分隔的移动列表,请尝试以下操作:

fetch('https://pokeapi.co/api/v2/pokemon/25')
  .then(res => res.json())
  .then(data => {
    // Convert to `string[]` of move names
    const moves = data.moves.map(moveData => moveData.move.name);
    // Send message with a comma-separated list of move names
    message.channel.send(moves.join(','));
  });

至于创建嵌入,这些很容易按照嵌入结构文档构建:

fetch('https://pokeapi.co/api/v2/pokemon/25')
  .then(res => res.json())
  .then(data => {
    // Convert to `string[]` of move names
    const moves = data.moves.map(moveData => moveData.move.name);
    // Send message with embed containing formatted data
    message.channel.send({
      embeds: [{
        // Set embed title to 'pikachu'
        title: data.name,
        // Add embed field called 'moves', with comma-separated list of move names
        fields: [{
          name: 'Moves',
          value: moves.join(','),
        }],
      }],
    });
  });

推荐阅读