如何将coinmarketcap API中的值添加到电报消息中?

问题描述 投票:1回答:1

我正在尝试完成电报机器人,它将在几个命令响应消息之后...失去任何希望尝试我可以单独解决这个问题。具有预定义消息的那些命令已经完成并且像魅力一样工作。但是现在我坚持/ price命令应该在来自coinmarket API的消息中显示硬币值。

我尝试了很多变种但是后面的结果总是调用API调用错误:或者像[object Object]这样的消息。

     ALQO: $0.0443407142 | 9.73% 🙂
     ETH: 0.000313592 | 10.14% 🙂
     BTC: 0.0000107949 | 9.5% 🙂
     Cap: $2,545,718

上面这个文本是正确的响应机器人...不幸的是,从CMC的免费API,我只能用美元价格,所以正确的答案应该是

       Coinname: Price | Change%
       Cap: Marketcap       

我的代码/ price命令

    //This is /price command code
    'use strict';

     const Telegram = require('telegram-node-bot');

     const rp = require('request-promise');
     const requestOptions = {
     method: 'GET',
     uri: 'https://pro- 
     api.coinmarketcap.com/v1/cryptocurrency/quotes/latest? 
     id=3501&convert=USD',
     headers: {
     'X-CMC_PRO_API_KEY': 'MYFREEAPIKEYFROMCMC'
      },
      json: true,
      gzip: true
     };

     rp(requestOptions).then(response => {
     console.log('API call response:', response['data'][3501]);
     }).catch((err) => {
     console.log('API call error:', err.message);
   });

    class PriceController extends Telegram.TelegramBaseController {
    PriceHandler($) {
    rp(requestOptions).then(response => {
    console.log('API call response:', response['data'][3501]);
    $.sendMessage('Cryptosoul: price', response['data']['USD']['price'] 
    [3501]);
   }).catch((err) => {
    $.sendMessage('API call error:', err.message);
  });
 }

get routes() {
    return {
        'priceCommand': 'PriceHandler'
    };
  };
}

 module.exports = PriceController;

在节点index.js之后从API响应(打开bot,(来自visual studio终端的消息)

     API call response: { id: 3501,
     name: 'CryptoSoul',
     symbol: 'SOUL',
     slug: 'cryptosoul',
     circulating_supply: 143362580.31,
     total_supply: 499280500,
     max_supply: null,
     date_added: '2018-10-25T00:00:00.000Z',
     num_market_pairs: 3,
     tags: [],
     platform:
   { id: 1027,
     name: 'Ethereum',
     symbol: 'ETH',
     slug: 'ethereum',
     token_address: '0xbb1f24c0c1554b9990222f036b0aad6ee4caec29' },
     cmc_rank: 1194,
     last_updated: '2019-04-01T23:03:07.000Z',
   quote:
    { USD:
     { price: 0.000188038816143,
     volume_24h: 11691.5261174775,
     percent_change_1h: 0.29247,
     percent_change_24h: 0.0222015,
     percent_change_7d: 4.69888,
     market_cap: 26957.72988069816,
     last_updated: '2019-04-01T23:03:07.000Z' } } }

/ price命令触发“API调用错误:”[object object]“”运行节点index.js(错误代码)时出错的消息“Chat with Bot

node.js api telegram-bot price
1个回答
0
投票

正如我所看到的,您在这里错误地访问了生成的json响应对象:

$.sendMessage('Cryptosoul: price', response['data']['USD']['price'] 
[3501])

只是相当打印响应对象提供了访问某些属性的正确方法。

{
    "status": {
        "timestamp": "2019-04-02T08:38:09.230Z",
        "error_code": 0,
        "error_message": null,
        "elapsed": 14,
        "credit_count": 1
    },
    "data": {
        "3501": {
            "id": 3501,
            "name": "CryptoSoul",
            "symbol": "SOUL",
            "slug": "cryptosoul",
            "circulating_supply": 143362580.31,
            "total_supply": 499280500,
            "max_supply": null,
            "date_added": "2018-10-25T00:00:00.000Z",
            "num_market_pairs": 3,
            "tags": [],
            "platform": {
                "id": 1027,
                "name": "Ethereum",
                "symbol": "ETH",
                "slug": "ethereum",
                "token_address": "0xbb1f24c0c1554b9990222f036b0aad6ee4caec29"
            },
            "cmc_rank": 1232,
            "last_updated": "2019-04-02T08:37:08.000Z",
            "quote": {
                "USD": {
                    "price": 0.000201447607597,
                    "volume_24h": 12118.3983544441,
                    "percent_change_1h": 1.48854,
                    "percent_change_24h": 6.88076,
                    "percent_change_7d": 12.4484,
                    "market_cap": 28880.04882238228,
                    "last_updated": "2019-04-02T08:37:08.000Z"
                }
            }
        }
    }
}

所以我们可以看到price字段位于USD对象下面,它位于quote对象下面,在你的代码中缺少。

获得它的正确方法是:

const price = response["data"][3501]["quote"]["USD"]["price"];

PriceHandler代码:

PriceHandler($) {
    rp(requestOptions)
        .then((response) => {
            const price = response["data"][3501]["quote"]["USD"]["price"];
            $.sendMessage("Cryptosoul: price", price);
        })
        .catch((err) => {
            console.error("API call error:", err.message);
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.