/
telegram.go
47 lines (37 loc) · 912 Bytes
/
telegram.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package infrastructure
import (
"context"
"sync"
"github.com/capcom6/service-monitor-tgbot/internal/config"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type TelegramBot struct {
Config config.Telegram
apiOnce sync.Once
api *tgbotapi.BotAPI
}
func NewTelegramBot(cfg config.Telegram) *TelegramBot {
return &TelegramBot{
Config: cfg,
apiOnce: sync.Once{},
}
}
func (b *TelegramBot) Api() (api *tgbotapi.BotAPI, err error) {
b.apiOnce.Do(func() {
b.api, err = tgbotapi.NewBotAPI(b.Config.Token)
if err == nil {
b.api.Debug = b.Config.Debug
}
})
return b.api, err
}
func (b *TelegramBot) Listen(ctx context.Context) (tgbotapi.UpdatesChannel, error) {
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
u.AllowedUpdates = []string{"message", "callback_query"}
go func() {
<-ctx.Done()
b.api.StopReceivingUpdates()
}()
return b.api.GetUpdatesChan(u), nil
}