Skip to content

How to build a Telegram Bot using Node.js

In this article, we will learn how to build a simple Telegram Bot in Node.js using node-telegram-bot-api library.

Create the Telegram Bot

Initialize Node.js Project

mkdir telegram-bot
cd telegram-bot
npm init -y

Install dependencies

There are two popular libraries to work with a Telegram Bot in Node.js:

But in our case, we will use node-telegram-bot-api library, since it is simple and easy to use.

npm install node-telegram-bot-api dotenv

Implement the simple Telegram Bot

Let’s create app.js file.

const TelegramBot = require('node-telegram-bot-api');

// Replace 'YOUR_TELEGRAM_BOT_TOKEN' with your bot token
const token = 'YOUR_TELEGRAM_BOT_TOKEN';

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, { polling: true });

// Listen for any message and respond
bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  const text = msg.text;

  // Respond to specific messages
  if (text.toLowerCase() === 'hi') {
    bot.sendMessage(chatId, 'Hello! How can I help you today?');
  } else if (text.toLowerCase() === 'bye') {
    bot.sendMessage(chatId, 'Goodbye! Have a nice day!');
  } else {
    bot.sendMessage(chatId, 'Sorry, I didn’t understand that. Try saying "Hi" or "Bye".');
  }
});

Run the Telegram Bot

node app.js

Test the Telegram Bot

That’s it! You have successfully built a simple Telegram Bot using Node.js.

Obtain CHAT_ID of the Telegram Bot

Using the Bot

To obtain the CHAT_ID of the Telegram Bot, you can use the following code snippet:

bot.onText(/\/start/, (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, `Your chat ID is: ${chatId}`);
});

Run the bot and type /start in the chat to get the CHAT_ID.

Using Web Browser

You can also use the web browser to get the CHAT_ID of the Telegram Bot.

Using userinfobot

You can also use the @userinfobot to get the CHAT_ID of the Telegram Bot.