javascriptnode.jstelegram-botcoinmarketcap

How to add values from coinmarketcap API to telegram message?


I'm trying to finish telegram bot that will after several commands respond with message... Lost any hope of trying that i can solve this alone. Those commands with predefined message are done and working like a charm, but now I'm stuck on the /price command which should show coin value in the message from coinmarket API respond..

I tried many variants but following results always called for API Call error: or message like [object Object]..

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

This text above is correct respond from bot... Unfortunately with free API from CMC I can do only price with USD so correct answer should be

       Coinname: Price | Change%
       Cap: Marketcap       

My code of /price command

    //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;

Respond from API after node index.js (turning bot on, (message from visual studio terminal)

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

The messages that appears after /price command triggered

"API call error:"
"[object Object]"
"Error while running node index.js (bad code)"

Chat with Bot


Solution

  • As I could see, you are incorrectly accessing the resulting json response object here:

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

    Just pretty printing that response object gives a correct way to access certain properties.

    {
        "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"
                    }
                }
            }
        }
    }
    

    So we could see that price field is located under USD object wich itself located under quote object, which is missing in your code.

    Proper way to get it would be:

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

    PriceHandler code:

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