|
| 1 | +package bot |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + |
| 9 | + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" |
| 10 | +) |
| 11 | + |
| 12 | +type Bot struct { |
| 13 | + tg *tgbotapi.BotAPI |
| 14 | + handler Handler |
| 15 | +} |
| 16 | + |
| 17 | +func New(apiToken string, handler Handler) (*Bot, error) { |
| 18 | + if apiToken == "" { |
| 19 | + return nil, errors.New("[app_bot] api token must be provided") |
| 20 | + } |
| 21 | + |
| 22 | + if handler == nil { |
| 23 | + return nil, errors.New("[app_bot] handler must be provided") |
| 24 | + } |
| 25 | + |
| 26 | + tg, err := tgbotapi.NewBotAPI(apiToken) |
| 27 | + if err != nil { |
| 28 | + return nil, errors.New("[app_bot] failed to create telegram bot instance") |
| 29 | + } |
| 30 | + |
| 31 | + return &Bot{tg: tg, handler: handler}, nil |
| 32 | +} |
| 33 | + |
| 34 | +func Must(apiToken string, handler Handler) *Bot { |
| 35 | + b, err := New(apiToken, handler) |
| 36 | + if err != nil { |
| 37 | + panic(err) |
| 38 | + } |
| 39 | + |
| 40 | + return b |
| 41 | +} |
| 42 | + |
| 43 | +func (b *Bot) PollUpdates(ctx context.Context) error { |
| 44 | + if b.handler == nil { |
| 45 | + panic("handler must be set before running updater") |
| 46 | + } |
| 47 | + |
| 48 | + updateConfig := tgbotapi.NewUpdate(0) |
| 49 | + updateConfig.Timeout = 60 |
| 50 | + |
| 51 | + updates, err := b.tg.GetUpdatesChan(updateConfig) |
| 52 | + if err != nil { |
| 53 | + return fmt.Errorf("failed to get updates channel: %w", err) |
| 54 | + } |
| 55 | + |
| 56 | + for { |
| 57 | + select { |
| 58 | + case <-ctx.Done(): |
| 59 | + return ctx.Err() |
| 60 | + case update, ok := <-updates: |
| 61 | + if !ok { |
| 62 | + return nil |
| 63 | + } |
| 64 | + |
| 65 | + b.handler.Handle(ctx, b, &update) |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func (b *Bot) UpdateFromRequest(r *http.Request) (*tgbotapi.Update, error) { |
| 71 | + return b.tg.HandleUpdate(r) |
| 72 | +} |
| 73 | + |
| 74 | +func (b *Bot) HandleUpdate(ctx context.Context, update *tgbotapi.Update) { |
| 75 | + if update == nil { |
| 76 | + return |
| 77 | + } |
| 78 | + |
| 79 | + b.handler.Handle(ctx, b, update) |
| 80 | +} |
| 81 | + |
| 82 | +func (b *Bot) Send(c tgbotapi.Chattable) (tgbotapi.Message, error) { |
| 83 | + return b.tg.Send(c) |
| 84 | +} |
| 85 | + |
| 86 | +func (b *Bot) GetFileDirectURL(fileID string) (string, error) { |
| 87 | + return b.tg.GetFileDirectURL(fileID) |
| 88 | +} |
0 commit comments