Beginner's Guide: Creating a Crypto Price Tracking Telegram Bot with Javascript

Beginner's Guide: Creating a Crypto Price Tracking Telegram Bot with Javascript

This bot tracks the prices of Coins using the Binance API.

A while ago, when I heard there was a dip in the crypto market, I thought of checking the current prices of some coin pairs. More reason I came up with the idea of building a Bot to track the prices of these coin pairs automatically. In this tutorial, we will be building a telegram bot that tracks the prices from Binance.

Brief Introduction

  • What is Telegram?

Telegram is one of the top social media platforms for messaging. Its core functionalities include sending messages to other Telegram users, creating group chats, calling contacts, and sending files and stickers. You can learn more about Telegram here telegram.org

  • What is a Telegram Bot?

Telegram Bots are accounts that are operated by software and not actual people. They can do anything from teaching, playing games, acting as search engines, broadcasting messages, serving as reminders, connecting and integrating with other services, or even passing commands to Internet Of Things (IoT) devices.

  • What is an API

API stands for Application Programming Interface. In the context of APIs, the word Application refers to any software with a distinct function. The interface can be thought of as a contract of service between two applications. APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. For example, the weather bureau’s software system contains daily weather data. The weather app on your phone “talks” to this system via APIs and shows you daily weather updates on your phone.

Prerequisites For This Tutorial

1: Get your Binance API Key

To generate your API KEY, you need to sign up on Binance or probably login, after setting up your 2FA, click on the Profile Icon and a dropdown menu will popover. Click on API management

API

On the API management tab, click on Create API, choose a name for your API, do your 2FA, and generate your API key. Make sure to take note of your API Key and API secret! Don't share it with anyone. You now have your Binance API key. API.png

2: Set up your telegram bot

Now that, you have successfully generated your Binance API credentials, it’s time to create your Telegram Bot.

Getting Started

  • Having a Conversation with BotFather
    Sign in to your Telegram account then search for @botfather and start a conversation with the account. PS: BotFather is also a Telegram Bot. bot.png boty.png

  • Creating the Telegram Bot Interface with BotFather
    You will now use the /newbot command to create a new Telegram Bot. Creating the Telegram Bot with BotFather means you give it a name and assign a username to it. newbot.png butex.png

Now that, you have successfully fulfilled all the requirements we are good to go for the integration of the Binance API with our BOT. If you've come this far, take a deep breath and give yourself some accolades.

Initializing the Node.js project

Please make sure that you have Node.js installed on your machine. You can get the latest version from the official website.

Firstly, we need to create a folder where the code of our bot will be located. By executing the following commands, you can make the folder and initialize the Node.js project there:

mkdir binance-bot
cd binance-bot
npm init

After the successful project initialization, the package.json should be created inside the project folder and contain the information about your project metadata.

Now you need to install three(3) npm packages required for your application. By executing this command, you will get them into the project:

npm install dotenv node-binance-api node-telegram-bot-api

binance-api-node — interacts with the official Binance API

node-telegram-bot-api — interacts with the official Telegram Bot API

dotenv — loads environment variables from a .env file into process.env

Then, you have to create your “.env” file where we will put in all the required API credentials. Copy the code below and paste it into your .env file

BINANCE_API_KEY=YOUR_BINANCE's_API_KEY
BINANCE_API_SECRET=YOUR_BINANCE's_SECRET_KEY
TELEGRAM_BOT_TOKEN=TELEGRAM's_BOT_API_KEY

Getting the Crypto prices from Binance

After you have gotten your API keys, you will get the prices for the cryptocurrencies from Binance API. To get the BTC price, we need to pass the symbol BTCUSDT as a parameter (USDT is a stablecoin, 1 USDT ≈ 1 USD).

import Binance from 'binance-api-node'
import dotenv from 'dotenv'
import { formatMoney } from './utils/money.js'

dotenv.config()

// API keys can be generated here https://www.binance.com/en/my/settings/api-management
const binanceClient = Binance.default({
  apiKey: process.env.BINANCE_API_KEY,
  apiSecret: process.env.BINANCE_API_SECRET,
})

const cryptoToken1 = 'BTC'
const cryptoToken2 = 'USDT'

binanceClient
  .avgPrice({ symbol: `${cryptoToken1}${cryptoToken2}` }) // example, { symbol: "BTCUSTD" }
  .then((avgPrice) => {
    console.log(formatMoney(avgPrice['price']))
  })
  .catch((error) =>
    console.log(`Error retrieving the price for ${cryptoToken1}${cryptoToken2}: ${error}`)
  )

Now you can run node index.js in the terminal and get the latest price for the BTC token as an output of the console.log.

If you are getting SyntaxError: Cannot use import statement outside a module please add ”type”: “module” into your package.json to be able to import ESModules in Node.js.

In the listing above, firstly, you initialize the Binance API client binanceClient by providing the API key and API secret. Then we call the API method binanceClient.avgPrice to get the price by providing the object with the symbol key { symbol: "BTCUSTD" } as a parameter.

The API keys are stored in the .env file as a separation of config from code and as a security measure.

Finally, you need to add the handlers for onText and message events. When the bot receives the message that matches the following pattern /price [symbol], your code will call Binance API to get the latest price for the provided symbol. The final code for the main file of the project index.js you can find it below.

import Binance from 'binance-api-node'
import TelegramBot from 'node-telegram-bot-api'
import dotenv from 'dotenv'
import { formatMoney } from './utils/money.js'

dotenv.config()

// API keys can be generated here https://www.binance.com/en/my/settings/api-management
const binanceClient = Binance.default({
  apiKey: process.env.BINANCE_API_KEY,
  apiSecret: process.env.BINANCE_API_SECRET,
})

// The bot token can be obtained from BotFather https://core.telegram.org/bots#3-how-do-i-create-a-bot
const bot = new TelegramBot(process.env.TELEGRAMM_BOT_TOKEN, { polling: true })

// Matches "/price [symbol]"
bot.onText(/\/price (.+)/, (msg, data) => {
  const chatId = msg.chat.id

  bot.sendMessage(chatId, 'Wait...')

  // data[1] can be a single token (i.e. "BTC") or pair ("ETH BTC")
  const [cryptoToken1, cryptoToken2 = 'USDT'] = data[1].split(' ')

  binanceClient
    .avgPrice({ symbol: `${cryptoToken1}${cryptoToken2}`.toUpperCase() }) // example, { symbol: "BTCUSTD" }
    .then((avgPrice) => {
      bot.sendMessage(chatId, formatMoney(avgPrice['price']))
    })
    .catch((error) =>
      bot.sendMessage(
        chatId,
        `Error retrieving the price for ${cryptoToken1}${cryptoToken2}: ${error}`
      )
    )
})

bot.on('message', (msg) => {
  const chatId = msg.chat.id

  switch (msg.text) {
    case '/start':
      bot.sendMessage(chatId, 'Hi there! I am Alice Crypto Bot.')
      break

    default:
      break
  }
})

Conclusion

Voila!!! you have successfully created your crypto prices tracking bot.

Now if you run the project locally node index.js you should be able to send commands to your bot and get the responses with cryptocurrency prices from it 🚀. TELEGRAM BOT.png

If you have any questions, don't hesitate to hit me up on Twitter: @Elishaokon13