Setting up a Telegram bot webhook using node-telegram-bot-api

Hey everyone! I’m new to making Telegram bots and I picked the node-telegram-bot-api package for my hobby project. It was pretty easy to use with polling during development. But now I want to deploy it on Netlify or Vercel, and I found out I need to use a webhook instead.

Does anyone know how to set this up? I’m looking for a step-by-step guide specifically for node-telegram-bot-api. I’ve seen some examples for other languages, but I’m not sure how to put it all together for this package.

Any help would be awesome! Thanks in advance!

yo, i’ve been there too! its a bit tricky but heres wat worked for me:

use serverless functions on netlify/vercel. make an api route for telegram updates. switch to webhook mode in ur code:

const bot = new TelegramBot(token, {webHook: true});
bot.setWebHook(process.env.WEBHOOK_URL);

handle updates in ur api route. dont forget to set env vars!

Setting up a webhook for node-telegram-bot-api can be tricky, but it’s doable. First, ensure your deployment platform supports serverless functions. Create an API route that accepts POST requests from Telegram. In your bot code, use the ‘webhook’ option instead of polling:

const bot = new TelegramBot(token, {webHook: {port: process.env.PORT}});

Then set the webhook URL:

bot.setWebHook(${process.env.WEBHOOK_URL}/api/webhook);

In your API route, handle incoming updates:

export default async function handler(req, res) {
if (req.method === ‘POST’) {
await bot.processUpdate(req.body);
res.status(200).json({ok: true});
} else {
res.status(405).json({error: ‘Method not allowed’});
}
}

Remember to set environment variables for your token and webhook URL. Test thoroughly before deploying.

I ran into a similar challenge when switching from polling to webhooks. I found that the key is to properly configure your bot for the new mode. In my case, I replaced the polling setup with the webhook initialization like so:

const bot = new TelegramBot(token, { webHook: { port: process.env.PORT } });
bot.setWebHook(`${process.env.URL}/bot${token}`);

After that, I created a POST endpoint to handle Telegram’s webhook updates using serverless functions on my deployment platform. Make sure to configure your environment variables correctly for both the bot token and your app’s URL. Once set up, initiating the webhook via Telegram’s API completes the process. This approach streamlined my deployment on Vercel considerably.