【问题标题】:Discord.js crypto currency command returning undefined for pricesDiscord.js 加密货币命令返回未定义的价格
【发布时间】:2021-05-14 10:22:26
【问题描述】:

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

这是我的代码:

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)
        })
        
    }
}

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

【问题讨论】:

  • 你检查过cc的值和返回的data吗?

标签: javascript node.js discord discord.js


【解决方案1】:

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

其中一个问题是@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',所以你不需要使用额外的功能。

【讨论】:

    【解决方案2】:
    .then (response => response.json)
    

    应该是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多