tucnak / telebot

Telebot is a Telegram bot framework in Go.
MIT License
4.04k stars 469 forks source link

Skipping pending updates using LongPoller #640

Closed dani0854 closed 10 months ago

dani0854 commented 10 months ago

Sometimes for bots behavior when it doesn't process pending updates since its last getUpdates request is desired.

I could find a clean way to do it using telebot.LongPoller It has LastUpdateID, but no matter what values it set to, it still processes at least 1 update (minimum at value -2, since it passes -1 to offset)

According to bot api docs, the best way to do it, is to request getUpdates with offset=-1, same as LastUpdateID=-2. And ignore the 1st update while long polling.

Can this be achieved in current veriosn of library? If not, then this is a feature request.

JK19 commented 10 months ago

If I understand correctly you need to discard all updates with a timestamp older than the bot start time. I solved this using MiddlewarePoller

...
var startTime = time.now()
...
func main() {
...
// discards updates older than client start time
poller := &tele.MiddlewarePoller {
    Poller: &tele.LongPoller{ Timeout: 10 * time.Second },

    Filter: func(u *tele.Update) bool {
        return u.Message.Time().After(startTime)
    },
}
b, err := tele.NewBot(tele.Settings{
    Token: <token>,
    Poller: poller,
})
...

I hope it fits your use case

dani0854 commented 10 months ago

If I understand correctly you need to discard all updates with a timestamp older than the bot start time. I solved this using MiddlewarePoller

...
var startTime = time.now()
...
func main() {
...
// discards updates older than client start time
poller := &tele.MiddlewarePoller {
    Poller: &tele.LongPoller{ Timeout: 10 * time.Second },

    Filter: func(u *tele.Update) bool {
        return u.Message.Time().After(startTime)
    },
}
b, err := tele.NewBot(tele.Settings{
    Token: <token>,
    Poller: poller,
})
...

I hope it fits your use case

That is actually a neat solution, thanks