首页 > 解决方案 > 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)
        })
        
    }
}

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

标签: javascriptnode.jsdiscorddiscord.js

解决方案


如果您已经拥有异步execute功能,则可以使用 async/await。这样你就可以摆脱then()s.

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

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

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

这意味着它返回一个对象,该对象包含另一个以硬币 id 作为键的对象。所以如果cc's value 是bitcoin,你可以从中得到 USD 的价格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:您可以将颜色设置为'RANDOM',因此您不需要使用额外的功能。

在此处输入图像描述


推荐阅读