/
telegram.go
65 lines (55 loc) · 1.33 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package telegram
import (
"context"
tbot "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/pkg/errors"
)
type (
Service struct {
chatId int64
defaultChatId int64
bot *tbot.BotAPI
isActive bool
traceId string
}
TelegramConfig struct {
IsActive bool `yaml:"is_active"`
BotToken string `yaml:"bot_token"`
ChatId int64 `yaml:"chat_id"`
}
)
func (s *Service) SetDestination(destination interface{}) {
s.chatId = destination.(int64)
}
func (s *Service) resetChatId() {
s.chatId = s.defaultChatId
}
func (s *Service) Type() string {
return "telegram"
}
func (s *Service) SetTraceId(traceId string) {
s.traceId = traceId
}
func New(cfg *TelegramConfig) (*Service, error) {
bot, err := tbot.NewBotAPI(cfg.BotToken)
if err != nil {
return nil, errors.Wrap(err, "pkg.notificications.telegram.NewBot")
}
return &Service{
chatId: cfg.ChatId,
defaultChatId: cfg.ChatId,
bot: bot,
isActive: cfg.IsActive,
}, nil
}
func (s *Service) Send(_ context.Context, text string, attachment interface{}) error {
defer s.resetChatId()
newMessage := tbot.NewMessage(s.chatId, text)
if _, err := s.bot.Send(newMessage); err != nil {
return errors.Wrap(err, "pkg.notifications.telegram.Send")
}
return nil
}
func (s *Service) IsActive() bool {
return s.isActive
}