Discord.js 加密货币命令返回未定义的价格

时间:2021-02-10 17:22:53

标签: javascript node.js discord discord.js

我创建了一个命令来获取给定加密货币的价格数据。当我运行我的命令时,每个价格值的嵌入都有“未定义”。

这是我的代码:

module.exports = {
    name: 'crypto',
    description: 'gets crypto data',
    async execute (message, args) {

        let cc = args.slice(0).join(' ');

        const noArgs = new Discord.MessageEmbed()
        .setTitle('Missing arguments')
        .setColor((Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0'))
        .setDescription('You are missing some args (ex: -crypto bitcoin || -covid dogecoin)')
        .setTimestamp(new Date().getTime())
    
        if(!cc) return message.channel.send(noArgs);

        await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${cc}&vs_currencies=usd%2Ceur%2Cgbp`)
        .then (response => response.json)
        .then(data => {
            let usdprice = data.usd
            let europrice = data.eur
            let gbpprice = data.gbp

            const embed = new Discord.MessageEmbed()
            .setTitle(`**Current price of ${cc}:**`)
            .setDescription('This data might be inaccurate.')
            .setColor((Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0'))
            .setTimestamp(new Date().getTime())
            .addField('**USD:**', usdprice, true)
            .addField('**EURO:**', europrice, true)
            .addField('**GBP:**', gbpprice, true)

            message.channel.send(embed)
        })
        
    }
}

当我运行命令时,控制台也没有错误。

2 个答案:

答案 0 :(得分:1)

如果您已经有一个异步 execute 函数,则可以使用 async/await。这样您就可以摆脱 then()

问题之一是@Mellet 提到的,你需要调用 response.json()

另一个是获取数据看起来像这样(如果硬币ID是“比特币”):

{
  "bitcoin": {
    "usd": 44833,
    "eur": 36948,
    "gbp": 32383
  }
}

这意味着它返回一个对象,该对象包含另一个以硬币 ID 为键的对象。因此,如果 cc 的值为 bitcoin,您可以从 data.bitcoin.usd 获取美元价格。但是,您不能也不想对硬币 ID 进行硬编码,因此您需要将密钥添加为变量:data[coinId].usd

我还添加了一个辅助函数来检查返回的数据是否为空,因此您可以发送错误消息:

const isEmptyObject = (obj) => Object.keys(obj).length === 0;

module.exports = {
  name: 'crypto',
  description: 'gets crypto data',
  async execute(message, args) {
    let cc = args.slice(0).join(' ');

    if (!cc) {
      const noArgs = new Discord.MessageEmbed()
        .setTitle('Missing arguments')
        .setColor('RANDOM')
        .setDescription(
          'You are missing some args (ex: -crypto bitcoin || -covid dogecoin)',
        )
        .setTimestamp(new Date().getTime());

      return message.channel.send(noArgs);
    }

    const response = await fetch(
      `https://api.coingecko.com/api/v3/simple/price?ids=${cc}&vs_currencies=usd%2Ceur%2Cgbp`
    );
    const data = await response.json();

    if (isEmptyObject(data)) {
      return message.channel.send(
        `No returned data from the API. Are you sure "${cc}" is a valid id?`,
      );
    }

    let usdprice = data[cc].usd;
    let europrice = data[cc].eur;
    let gbpprice = data[cc].gbp;

    const embed = new Discord.MessageEmbed()
      .setTitle(`**Current price of ${cc}:**`)
      .setDescription('This data might be inaccurate.')
      .setColor('RANDOM')
      .setTimestamp(new Date().getTime())
      .addField('**USD:**', usdprice, true)
      .addField('**EURO:**', europrice, true)
      .addField('**GBP:**', gbpprice, true);

    message.channel.send(embed);
  },
};

PS:你可以set the colour to 'RANDOM',所以你不需要使用额外的功能。

enter image description here

答案 1 :(得分:0)

.then (response => response.json)

应该

.then (response => response.json())