DEV Community

Cover image for telegram webhook
Ukpai Chukwuemeka
Ukpai Chukwuemeka

Posted on

telegram webhook

Unlike polling, which repeatedly requests updates from Telegram, webhook allow Telegram to push updates directly to your server, reducing server resource usage and improving efficiency.
In a previous article, I explained how to set up a Telegram bot using Node.js, where we implemented polling to fetch updates repeatedly. While this setup works well, webhooks are a better alternative if you’re looking to scale, even if you’re not currently experiencing rate limits, switching to webhook ensures your bot runs more efficiently and can handle increased traffic with less strain on your server.

Key Considerations for Telegram Webhook

When using webhook, it’s crucial to understand the following:

Allowed Ports

Telegram supports only four ports for webhooks. While the reason for this limitation is still unclear to me, it might change in the future. For now, these are the supported ports:

  • 443 (recommended for HTTPS)
  • 80
  • 88
  • 8443

Either of these ports must be free and accessible for the webhook to function correctly. If you don’t explicitly specify a port, the webhook will default to using port 8443.

Server Limits

Since only four ports are allowed, you cannot run more than four apps using webhook on the same server.

Prerequisites

Before diving into the setup, ensure you have the following:

  • Node.js Installed: Download and install Node.js from nodejs.org if you haven’t already.

  • Telegram Account: You’ll need a Telegram account to obtain a bot token and interact with your bot.

  • Ngrok for HTTPS URL: Telegram requires an HTTPS endpoint for webhooks. Use Ngrok to expose your local server to the internet.

You can find full code on Github .

Setting Up Telegram Webhook (Node.js Example)

// Import the Telegram Bot API
const TelegramBot = require('node-telegram-bot-api');

// Replace with your bot token
const token = 'your telegram token'; // Check out my article on how to get a bot token from @BotFather on Telegram

const WEB_HOOK_URL = 'https://localhost:3000/telegram-bot-webhook'; 
// NOTE: It won't work on localhost, so use a tunneling service like ngrok.

// Create a bot that uses a webhook
const bot = new TelegramBot(token, {
  webHook: {
    port: 88, // Allowed ports for Telegram webhook: 443, 80, 88, 8443
  },
});

// Initialize the webhook
const initWebHook = async () => {
  const webhookInfo = await bot.getWebHookInfo();
  if (webhookInfo.url !== WEB_HOOK_URL) {
    await bot.setWebHook(WEB_HOOK_URL, {
      max_connections: 100,
    });
  }
};
initWebHook();

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

  // Simple command handling
  if (msg.text.toLowerCase() === '/start') {
    bot.sendMessage(chatId, 'Welcome! How can I assist you today?', {
      reply_markup: {
        keyboard: [['/start', '/help']],
      },
    });
  } else if (msg.text.toLowerCase() === 'hello') {
    bot.sendMessage(chatId, `Hello, ${msg.from.first_name}!`);
  } else {
    bot.sendMessage(chatId, "I'm not sure how to respond to that.");
  }
});

// Export the bot module
module.exports = bot;

Enter fullscreen mode Exit fullscreen mode

Telegram Webhook Route

const express = require("express");
const app = express();
const bot = require("./bot");

// parse json body  for post request
app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello World");
});

app.post("/telegram-bot-webhook", (req, res) => {
  bot.processUpdate(req.body);
  res.sendStatus(200);
});

app.listen(process.env.PORT || 3000, () => {
  console.log("Server is running on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Switching to webhook eliminates telegram rate-limiting issue and improves your bot’s efficiency. Just ensure you configure your server properly, use the allowed ports, and secure your connection with HTTPS.

Kindly follow me to get notified on my next post 📫.

Top comments (0)