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
- Open Telegram and search for
BotFather
- Click on
BotFather
and start a chat - Type
/newbot
to create a new bot - Follow the instructions to create a new bot
- Once the bot is created, note down the
API Token
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:
node-telegram-bot-api
: A Node.js module to interact with the Telegram Bot APItelegraf
: A modern Telegram Bot framework for 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
- Open Telegram and search for your bot
- Start a chat with your bot
- Type
Hi
orBye
to see the responses
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.
- Send a message to your bot. This step is necessary so your bot has a conversation history with you, which can be used to fetch your chat ID
- Open the following URL in the web browser:
https://api.telegram.org/bot<YOUR_TELEGRAM_BOT_TOKEN>/getUpdates
- Look for
"chat":{"id": number}
in the response
Using userinfobot
You can also use the @userinfobot
to get the CHAT_ID
of the Telegram Bot.