When developing Telegram bots using Node.js, there are two main methods for receiving user messages: Polling and Webhook. Both serve the purpose of handling incoming requests, but each has its unique features, making them suitable for different scenarios.
Polling is a method of fetching updates from the Telegram server by periodically sending requests. The bot sends requests at specific time intervals to check for new messages or events.
There are two types of polling: Long Polling and Short Polling.
In Long Polling, the bot sends a request to the server and waits for a response. If there are no new messages, the server holds the request open until a new message arrives or the timeout period ends. Once the bot receives a response, it immediately sends a new request.
Here’s an example where the bot is configured to poll the Telegram server every 3 seconds, with a timeout of 10 seconds:
const TelegramBot = require('node-telegram-bot-api');
const token = 'TOKEN';
// Create a bot instance with Long Polling enabled
const bot = new TelegramBot(token, {
polling: {
interval: 3000, // Interval between requests (3 seconds)
autoStart: true, // Automatically start polling
params: {
timeout: 10 // Request timeout (10 seconds)
}
}
});
bot.on('message', (msg) => {
const chatId = msg.chat.id;
const text = msg.text;
// Respond to the received message
bot.sendMessage(chatId, `You wrote: ${text}`);
});
bot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'Hello! I am a bot using Long Polling.');
});
In Short Polling, the bot sends requests to the server at short intervals, regardless of whether new messages are available. This method is less efficient because it generates more network requests and consumes more resources.
In this case, the bot constantly requests updates from the server without keeping the connection open for a long time. This can lead to high network usage, especially with heavy traffic.
Here’s an example of a bot using Short Polling:
const TelegramBot = require('node-telegram-bot-api');
const token = 'TOKEN';
// Create a bot instance with Short Polling enabled
const bot = new TelegramBot(token, { polling: true });
bot.on('message', (msg) => {
const chatId = msg.chat.id;
const text = msg.text;
bot.sendMessage(chatId, `You wrote: ${text}`);
});
bot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'Hello! I am a bot using Short Polling.');
});
Webhook is a method that allows a bot to receive updates automatically. Instead of periodically polling the Telegram server, the bot provides Telegram with a URL, where POST requests will be sent whenever new updates arrive. This approach helps to use resources more efficiently and minimizes latency.
In the following example, the bot receives requests from Telegram via Webhook, eliminating the need for frequent server polling. This reduces server load and ensures instant message handling.
const TelegramBot = require('node-telegram-bot-api');
const express = require('express');
const bodyParser = require('body-parser');
const token = 'TOKEN';
// Your server URL
const url = 'https://your-server.com';
const port = 3000;
// Create a bot instance without automatic polling
const bot = new TelegramBot(token, { webHook: true });
// Set the Webhook URL for your server
bot.setWebHook(`${url}/bot${token}`);
// Configure the Express server
const app = express();
app.use(bodyParser.json());
// Request handler for incoming updates from Telegram
app.post(`/bot${token}`, (req, res) => {
bot.processUpdate(req.body);
res.sendStatus(200);
});
bot.on('message', (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, `You wrote: ${msg.text}`);
});
// Start the server
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
To run the code and start the bot, install the required libraries:
npm install node-telegram-bot-api express
We need to set up a server to work with Webhook. We'll use Hostman for this.
Since Telegram's API only works with HTTPS, you need to install an SSL certificate. For this, you will need a registered domain name. To set up the web server and install the certificate, execute the following commands sequentially:
Update available package lists:
sudo apt update
Create and open the Nginx configuration file:
sudo nano /etc/nginx/sites-available/your_domain
Inside this file, add the following configuration:
server {
listen 80;
server_name your_domain;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Replace your_domain
with your actual domain name in this file and throughout the console.
Create a symbolic link to the file:
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/
Restart Nginx:
sudo systemctl restart nginx
Install certbot
to create SSL certificates:
sudo apt install certbot python3-certbot-nginx
Use certbot
to configure the SSL certificate:
sudo certbot --nginx -d your_domain
Replace your_domain
with your actual domain name.
Before choosing a method for receiving messages, it is important to consider the characteristics of each approach and its applicability in different situations.
Polling:
Local Development: When developing and testing a bot on a local machine, using Long Polling allows for easy updates without the need to set up a server.
Small Projects: If you are creating a bot for a small group of users or for personal use, and you do not have strict requirements for response time, Polling will be sufficient.
Low Traffic Projects: If your bot is not expecting a large number of messages, using Short Polling can be appropriate as it is simple to implement.
Webhook:
Production Applications: For bots working in a production environment where immediate responses to events are important, Webhook is the preferred choice. For example, bots that handle payments or respond to user queries in real time should use Webhook to ensure high performance.
High Traffic Systems: If you're developing a bot that will serve a large number of users, Webhook will be more efficient since it reduces server load by eliminating continuous requests.
Systems with Long Operations: If your bot performs long operations (such as generating reports or processing data), Webhook can be used to notify users once these operations are complete.
To better understand the differences between the two approaches, here is a comparison table of their characteristics:
Characteristic |
Polling |
Webhook |
Method of Data Retrieval |
Periodic requests to the Telegram server |
Automatic sending of updates to a specified URL |
Setup |
Simple setup, no additional resources required |
Requires HTTPS server setup and SSL certificate |
Response Speed |
May have slight delays due to polling intervals |
Near-instant message reception |
Resource Usage |
Continuously requests updates, taxing the server |
More resource-efficient since updates come automatically |
Infrastructure Requirements |
Does not require a public server |
Requires a public HTTPS server |
Reliability |
Does not depend on the availability of an external server |
Can be unavailable if there are issues with the HTTPS server |
Setup Issues in Local Environment |
Can be used locally for testing |
Difficult to use without public access |
The choice between Polling and Webhook depends on the specific needs of your project. Polling is a simple and quick way to develop, especially in the early stages, while Webhook offers more efficient message processing for production environments.