DEV Community

Dmytro Olefyrenko
Dmytro Olefyrenko

Posted on • Originally published at olefyrenko.com

🤖 How to create a Telegram Crypto Bot in Javascript

Cryptocurrencies and blockchain technology are very hot topics right now. Bitcoin and Ethereum are hitting new all-time highs and more and more companies invest their assets in Bitcoin. Taking these facts as an opportunity to be involved in the crypto world, we will write a bot 🤖 for Telegram to monitor the prices on the cryptocurrency market. Below you can see the screenshot of such a bot. You can send to the bot the crypto token (or token pair) and get its trading price on the largest in terms of trading volume crypto exchange Binance.

Alt Text

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.

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

mkdir cryptobot
cd cryptobot
npm init
Enter fullscreen mode Exit fullscreen mode

Please answer the questions in the command line questionnaire. After it is done you should see the terminal output similar to mine:

Npm Console

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

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

npm install binance-api-node node-telegram-bot-api dotenv
Enter fullscreen mode Exit fullscreen mode

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

Getting the Crypto prices from Binance

As a first step, we will get the prices for the cryptocurrencies from Binance API. To use the Binance API, you need to have a Binance account (you can register a new one here). The code for retrieving Bitcoin price from Binance you can find in the following listing. 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}`)
  )
Enter fullscreen mode Exit fullscreen mode

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, we initialize the Binance API client binanceClient by providing API key and API secret. These keys you can generate in your Binance account in the API Management page. 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.

Creating the Telegram Bot

Since now we are able to get the cryptocurrency prices from the Binance API, it is time to integrate our application with the Telegram Bot API. After doing so, we will send the cryptocurrency price into the Telegram chat instead of sending it to the terminal, as we did on the previous code listing.

To create a Telegram Bot we need (can you guess :-)?) to talk to another bot, BotFather. By following simple steps, we can specify the name and the username for the bot and get the token after the creation is successful. This token should be kept secure and stored safely in .env file with a key TELEGRAMM_BOT_TOKEN.

Bot Father in Telegram

Now having the token for our Telegram bot, we can create its instance using node-telegram-bot-api package.

const bot = new TelegramBot(process.env.TELEGRAMM_BOT_TOKEN, { polling: true })
Enter fullscreen mode Exit fullscreen mode

Finally, we need to add the handlers for onText and message events. When the bot receives the message that matches the following pattern /price [symbol], our 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 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 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
  }
})
Enter fullscreen mode Exit fullscreen mode

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 price from it 🚀. You can check the source code of the ready project in this Github repository. And, of course, you can interact with the real Alice Crypto bot here - http://t.me/alice_crypto_bot.

Please follow me on Twitter @olefyrenko to get updates about how to add new functionality for our bot, like price changes alert (i.e., the price for the cryptocurrency went down or up). Also, feel free to ask me any questions in DM on Twitter. Thank you!

Top comments (0)