feat: initial commit
This commit is contained in:
50
internal/infrastructure/telegram/update_poller.go
Normal file
50
internal/infrastructure/telegram/update_poller.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
)
|
||||
|
||||
type UpdateHandler interface {
|
||||
Handle(ctx context.Context, update tgbotapi.Update)
|
||||
}
|
||||
|
||||
type UpdatePoller struct {
|
||||
bot *tgbotapi.BotAPI
|
||||
handler UpdateHandler
|
||||
logger *slog.Logger
|
||||
timeout int
|
||||
}
|
||||
|
||||
func NewUpdatePoller(bot *tgbotapi.BotAPI, handler UpdateHandler, logger *slog.Logger) *UpdatePoller {
|
||||
return &UpdatePoller{
|
||||
bot: bot,
|
||||
handler: handler,
|
||||
logger: logger,
|
||||
timeout: 60,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *UpdatePoller) Start(ctx context.Context) error {
|
||||
u := tgbotapi.NewUpdate(0)
|
||||
u.Timeout = p.timeout
|
||||
|
||||
updates := p.bot.GetUpdatesChan(u)
|
||||
p.logger.InfoContext(ctx, "update poller started")
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
p.bot.StopReceivingUpdates()
|
||||
p.logger.InfoContext(ctx, "update poller stopped")
|
||||
return ctx.Err()
|
||||
case update, ok := <-updates:
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
go p.handler.Handle(ctx, update)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user