How to avoid receiving outdated messages when reconnecting Telegram bot webhook

I’m building a Telegram bot using their API and I have a webhook endpoint that processes incoming messages. My server responds with 200 OK to every request it receives.

When I shut down my bot, I properly remove the webhook URL so Telegram stops sending updates. But here’s my problem: every time I restart the bot and register the webhook again, Telegram sends me a bunch of old messages that accumulated while the bot was offline.

Is there a way to skip these old messages without having to call /getUpdates multiple times to clear the queue?

Here’s my basic setup:

const https = require('https');
const request = require('request');
const botToken = 'YOUR_BOT_TOKEN';

// Register webhook
request.post('https://api.telegram.org/bot' + botToken + '/setWebhook', {
    form: {
        url: 'https://myserver.com/webhook/telegram'
    }
});

process.on('SIGINT', function() {
    // Remove webhook on shutdown
    request.post('https://api.telegram.org/bot' + botToken + '/setWebhook', {
        form: {
            url: ''
        }
    });
});

// Webhook handler
const express = require('express');
const app = express();

app.post('/webhook/telegram', (req, res) => {
    res.status(200).send('OK');
});

app.listen(3000);

Any suggestions would be helpful.

Timestamp filtering works great here. Save the current timestamp before your bot shuts down, then compare incoming message timestamps to that saved time when you restart. If a message timestamp is older than your shutdown time, just ignore it. You’ll find the timestamp in req.body.message.date in your webhook handler. No extra API calls needed and you get exact control over which messages to handle. I’ve been using this for about six months - handles reconnection issues perfectly with zero performance hit.

I’ve encountered a similar issue in the past. Instead of completely removing your webhook, consider utilizing the drop_pending_updates parameter when setting the webhook again. By including drop_pending_updates: true in your setWebhook request, Telegram will automatically clear all queued updates for your bot, which saves you from the hassle of making multiple getUpdates calls or processing outdated messages. This approach has worked reliably for me over several months, ensuring a clean restart without any old messages.