Building a Telegram Bot in NodeJS: Track Cryptocurrency Prices

Crafting Your Telegram Crypto Bot: A Simple Guide

ยท

6 min read

Building a Telegram Bot in NodeJS: Track Cryptocurrency Prices

This blog will guide you on starting your journey to create your first Telegram bot. Making a Telegram bot is very easy. A Telegram bot can assist you in various ways and also teach you a lot about bot development, helping you automate many tasks.

After WhatsApp, Telegram has become one of the most popular messaging apps. Telegram surpassed 1 billion downloads, making it one of the most downloaded apps in 2021. As of March 2024, Telegram boasts over 900 million monthly active users. With millions of active users, the opportunities can be endless. Nowadays, people make millions using just a Telegram bot. By utilizing AI, you can create an AI bot that can assist you in studying, learning anything, answering your questions, and helping solve coding problems, among other things.

Nowadays, you can even create a game bot using HTML5, and the game will work directly in Telegram. For businesses, you can set up a Telegram bot that sends you website data whenever a new customer purchases something. The possibilities with a Telegram bot are endless. All you need is a good imagination, and you can build it. Let's dive into it.

Prerequisite

To get the most out of this blog, you should be familiar with the following points:

Setting-up a Telegram Bot

To set up your bot, Telegram offers a bot named BotFather that assists you in creating your own bot. BotFather gives you the API Token needed to communicate with your bot. It also helps you manage your bot, such as adding a description, profile picture, and changing settings.

To set up the bot, follow these steps:

  1. Search for BotFather on Telegram

  2. Open the Menu and select "Create a new bot." Then, give your bot a name and a unique username.

Writing the Bot Code in Node.js

Now, let's write some Node.js code so that whenever we type "price," our chatbot will provide us with the current Dogecoin price in INR. You can customize it with anything you want, but to keep this blog tutorial simple, I'm just going to add one command.

we won't go into how to set up and install Node.js. You can set up a Node project by yourself. Write the following code in the index.js file.

//index.js
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');

const token = 'YOUR TELEGRAM BOT TOKEN';
const bot = new TelegramBot(token, {polling: true});

bot.onText(/\/price/, async (msg) => {
 const chatId = msg.chat.id;
 try {
    const response = await axios.get('https://api.wazirx.com/api/v2/tickers/dogeinr');
    const price = response.data.ticker.last;
    bot.sendMessage(chatId, `Dogecoin price in INR: ${price}`);
 } catch (error) {
    console.error(error);
    bot.sendMessage(chatId, 'Error fetching Dogecoin price.');
 }
});

This code snippet demonstrates how to create a Telegram bot using the node-telegram-bot-api library and fetch the current price of Dogecoin in Indian Rupees (INR) from the WazirX API when a user sends the /price command to the bot.

Here's a breakdown of the code:

  1. Importing Libraries: The node-telegram-bot-api library is used to create a Telegram bot, and the axios library is used to make HTTP requests.

  2. Setting Up the Bot: Replace 'YOUR TELEGRAM BOT TOKEN' with your actual Telegram bot token obtained from the BotFather when you created your bot. This token is used to authenticate your bot with the Telegram API.

  3. Creating the Bot: A new instance of TelegramBot is created with the provided token, and { polling: true } is passed as an option to enable the bot to receive updates via polling.

  4. Handling Commands: The bot.onText method is used to listen for messages that match a specific pattern, in this case, the /price command. When a user sends this command, the bot executes the callback function, passing the message (msg) object.

  5. Fetching Price: Inside the callback function, an asynchronous HTTP GET request is made to the WazirX API to fetch the current price of Dogecoin in INR. The response contains the price data, which is extracted from the response (response.data.ticker.last) and stored in the price variable.

  6. Sending Response: The bot then sends a message to the chat (chatId) with the fetched Dogecoin price in INR using bot.sendMessage.

  7. Error Handling: If an error occurs during the HTTP request, the error is logged to the console (console.error(error)) and a message is sent to the chat indicating the error.

  8. Executing the Bot: The bot is set up to start polling for updates from the Telegram API using bot.startPolling()

You can expand on this by adding more commands or integrating with other APIs to provide additional functionality.

Testing the Bot

Now that our code is written, it's time to test it. To do this, first ensure that our Node app is running. Then, send the command message "/price" that we included in our code to our bot.

If it returns the response as shown in the image below, then your chatbot is working.

If you encounter any issues with the API, this document might be helpful.

Deploying the Bot

To deploy your Telegram bot, you don't need any special permissions or a specific server. You can easily deploy your Node.js code on AWS (Amazon Web Services) or Heroku. For instructions on deploying Node.js code on Heroku, check out this official blog. For AWS, refer to this official blog.

The Heroku deployment process is simpler and easier compared to AWS. If you are building a bot that will handle many users, you should consider AWS because it offers many services that can help your Node.js code scale more effectively.

Adding advanced features

So, we have built a simple crypto Telegram bot that sends the price when we ask for it. To add more advanced features, you can include multiple commands for the prices of other crypto coins, or you can get a list of prices for all coins at once.

One feature you can add is to automate your Telegram bot to send you the Crypto Coin price every hour or so. To do this, you need to incorporate a Task Scheduler into your Node.js code. You can check out this article where I explain how to implement a Task Scheduler in Node.js. You can also integrate multiple APIs into your bot and, if necessary, add a database as well. Choose a topic that interests you, and then you can add any feature you want.

With a bot, you can accept payments, include custom tools, integrate entire websites, connect with other services, host games using HTML5, create a social network, and much more.

Conclusion

Building a Telegram bot using Node.js opens up a world of possibilities for developers, businesses, and enthusiasts alike. From creating AI-driven bots that assist with learning, to developing interactive games and business tools that automate customer interactions, the potential applications are vast.

This guide has walked you through the essential steps to get started, from setting up your bot with BotFather, writing the code to fetch cryptocurrency prices, to testing and deploying your bot on platforms like AWS or Heroku.

By harnessing the power of NodeJS and Telegram's Bot API, you're now equipped to venture further into the exciting world of bot development, adding advanced features and expanding the capabilities of your bot to meet the needs of a growing audience. The journey into bot development is just beginning, and the future is as limitless as your imagination.

Thank you for reading my article. Please Follow Me, Feel free to comment and share your suggestions/thoughts ๐Ÿ˜Š

Resources

Did you find this article valuable?

Support Pradhumansinh Padhiyar by becoming a sponsor. Any amount is appreciated!

ย