How to Write a Telegram Bot with Node.js

Updated: December 30, 2023 By: Guest Contributor Post a comment

Overview & Setup

Creating a Telegram bot can be an enriching way to interact with users or automate tasks. In this tutorial, using Node.js, we will learn how to build a bot from scratch employing modern JavaScript syntax and techniques, including ES modules and async/await features. Let’s dive into the exciting world of chatbots.

Before starting, ensure you have Node.js installed on your system (and a registered Telegram account, of course). Start by setting up a new Node.js project. Create a folder for your project, initialize it with npm, and install necessary packages:

mkdir my_telegram_bot
cd my_telegram_bot
npm init -y
npm install node-telegram-bot-api dotenv

Create a .env file to hold your bot token securely, which you receive from BotFather on Telegram (if you don’t know what BothFather is, see the next section of this article). Also, set up .gitignore to avoid uploading your secrets to version control.

Get Telegram Token from BotFather

BotFather is a special bot on the Telegram platform. It’s designed to help users create new bot accounts and manage their existing bots.

Here’s how it works:

  • You contact BotFather and issue the /newbot command (you need to install Telegram app on your phone or computer).
  • You follow the steps provided by BotFather until you’re given a new token.
  • This token is a unique string that authenticates your bot (not your account) on the Telegram Bot API.
  • Each bot has a unique token which can also be revoked at any time via BotFather.
  • Your token will look like a long random string. Treat this token like a password and don’t share it with anyone.

Once you have your token, you can start building your bot. The Telegram Bot API provides JSON-encoded responses to your queries. You can interact with the API using basic or advanced requests3. For larger applications, it’s recommended to use libraries and frameworks along with some basic programming skills to build a more robust and scalable project.

Remember, official Telegram chatbots have a blue checkmark next to their name4. So, when you’re interacting with BotFather, make sure you see this checkmark.

Basic Bot Structure

Start by creating a simple bot that can respond to messages. Begin with importing your dependencies and initializing the Telegram bot API:

import TelegramBot from 'node-telegram-bot-api';
import dotenv from 'dotenv';
dotenv.config();

const token = process.env.TELEGRAM_BOT_TOKEN;
const bot = new TelegramBot(token, { polling: true });

Next, implement a basic echo feature which replies with the user’s message:

bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, `Echo: ${msg.text}`);
});

Commands and Interactions

Enhance your bot to support commands by listening to specific message patterns:

bot.onText(/\/start/, (msg) => {
  bot.sendMessage(msg.chat.id, 'Welcome to your new Telegram bot!');
});

We can also handle more complex commands with arguments, giving your bot additional functionality.

Asynchronous Operations and API Calls

Many bot operations will require asynchronous API calls. We use modern async/await syntax in Node.js to make our calls clean and straightforward:

bot.onText(/\/weather (.+)/, async (msg, match) => {
  const chatId = msg.chat.id;
  const location = match[1];
  try {
    const weatherData = await getWeatherData(location);
    const response = formatWeatherResponse(weatherData);
    bot.sendMessage(chatId, response);
  } catch (error) {
    bot.sendMessage(chatId, 'Sorry, Could not fetch weather data.');
  }
});

Remember to handle errors effectively to ensure your bot doesn’t crash when faced with an unexpected situation.

Working with Media and Files

The Telegram API allows bots to send various types of media. We can send images, videos, and more with the following example code:

bot.onText(/\/cat/, async (msg) => {
  const chatId = msg.chat.id;
  const catPictureStream = await getCatPictureStream();
  bot.sendPhoto(chatId, catPictureStream);
});

This uses an imaginary function getCatPictureStream, which you would need to implement based on your application’s logic and a third-party API.

Inline Queries

Expand the capabilities of your bot with inline queries, allowing for real-time feedback to users’ messages:

bot.on('inline_query', async (query) => {
  const results = await getInlineQueryResults(query.query);
  bot.answerInlineQuery(query.id, results);
});

Creating a dynamic inline query handler requires formatting query results properly as per the Telegram API specifications.

Error Handling and Logging

A stable bot should handle errors gracefully and log essential information for debugging:

bot.on('polling_error', (error) => {
  console.error(error.code);  // Log the polling error code for troubleshooting
});

Combine Node.js’s built-in console methods with more sophisticated logging libraries for a robust logging system.

Conclusion

We’ve covered the essentials needed to launch your personalized Telegram bot using Node.js and modern JavaScript features. Remember, building a bot is an iterative process with endless possibilities for expansion. With your newfound knowledge, you can embrace the creativity and utility that Telegram bots offer.