telebot/poller.go

113 lines
2.3 KiB
Go
Raw Normal View History

package telebot
import (
"time"
2017-12-11 22:27:09 +00:00
)
// Poller is a provider of Updates.
//
// All pollers must implement Poll(), which accepts bot
// pointer and subscription channel and start polling
// synchronously straight away.
//
type Poller interface {
// Poll is supposed to take the bot object
// subscription channel and start polling
// for Updates immediately.
2017-11-27 12:52:16 +00:00
//
// Poller must listen for stop constantly and close
// it as soon as it's done polling.
Poll(b *Bot, updates chan Update, stop chan struct{})
}
2017-11-21 15:56:09 +00:00
// MiddlewarePoller is a special kind of poller that acts
// like a filter for updates. It could be used for spam
// handling, banning or whatever.
//
// For heavy middleware, use increased capacity.
//
type MiddlewarePoller struct {
Capacity int // Default: 1
Poller Poller
Filter func(*Update) bool
2017-11-21 15:56:09 +00:00
}
// NewMiddlewarePoller wait for it... constructs a new middleware poller.
func NewMiddlewarePoller(original Poller, filter func(*Update) bool) *MiddlewarePoller {
2017-11-21 15:56:09 +00:00
return &MiddlewarePoller{
Poller: original,
Filter: filter,
2017-11-21 15:56:09 +00:00
}
}
// Poll sieves updates through middleware filter.
func (p *MiddlewarePoller) Poll(b *Bot, dest chan Update, stop chan struct{}) {
if p.Capacity < 1 {
p.Capacity = 1
2017-11-21 15:56:09 +00:00
}
middle := make(chan Update, p.Capacity)
2017-11-27 12:52:16 +00:00
stopPoller := make(chan struct{})
2017-11-21 15:56:09 +00:00
2017-11-27 12:52:16 +00:00
go p.Poller.Poll(b, middle, stopPoller)
2017-11-21 15:56:09 +00:00
for {
select {
case <-stop:
close(stopPoller)
return
case upd := <-middle:
if p.Filter(&upd) {
dest <- upd
}
2017-11-21 15:56:09 +00:00
}
}
}
// LongPoller is a classic LongPoller with timeout.
type LongPoller struct {
2020-04-26 17:43:17 +00:00
Limit int
Timeout time.Duration
2017-11-27 12:52:16 +00:00
LastUpdateID int
2020-04-26 17:43:17 +00:00
// AllowedUpdates contains the update types
// you want your bot to receive.
//
// Possible values:
// message
// edited_message
// channel_post
// edited_channel_post
// inline_query
// chosen_inline_result
// callback_query
// shipping_query
// pre_checkout_query
// poll
// poll_answer
//
AllowedUpdates []string
}
// Poll does long polling.
func (p *LongPoller) Poll(b *Bot, dest chan Update, stop chan struct{}) {
for {
2020-04-26 18:29:25 +00:00
select {
case <-stop:
return
default:
}
2020-04-26 17:43:17 +00:00
updates, err := b.getUpdates(p.LastUpdateID+1, p.Limit, p.Timeout, p.AllowedUpdates)
2017-11-27 12:52:16 +00:00
if err != nil {
b.debug(err)
2017-11-27 12:52:16 +00:00
continue
}
2017-11-27 12:52:16 +00:00
for _, update := range updates {
p.LastUpdateID = update.ID
dest <- update
}
}
}