forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.go
76 lines (62 loc) · 1.51 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
66
67
68
69
70
71
72
73
74
75
76
package push
import (
"errors"
"sync"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
// Telegram implements the Telegram messenger
type Telegram struct {
sync.Mutex
bot *tgbotapi.BotAPI
chats map[int64]struct{}
}
type telegramConfig struct {
Token string
Chats []int64
}
func init() {
if err := tgbotapi.SetLogger(log.ERROR); err != nil {
log.ERROR.Printf("telegram: %v", err)
}
}
// NewTelegramMessenger creates new pushover messenger
func NewTelegramMessenger(token string, chats []int64) (*Telegram, error) {
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
return nil, errors.New("telegram: invalid bot token")
}
m := &Telegram{
bot: bot,
chats: make(map[int64]struct{}),
}
for _, chat := range chats {
m.chats[chat] = struct{}{}
}
go m.trackChats()
return m, nil
}
// trackChats captures ids of all chats that bot participates in
func (m *Telegram) trackChats() {
conf := tgbotapi.NewUpdate(0)
conf.Timeout = 1000
for update := range m.bot.GetUpdatesChan(conf) {
m.Lock()
if _, ok := m.chats[update.Message.Chat.ID]; !ok {
log.INFO.Printf("telegram: new chat id: %d", update.Message.Chat.ID)
// m.chats[update.Message.Chat.ID] = struct{}{}
}
m.Unlock()
}
}
// Send sends to all receivers
func (m *Telegram) Send(title, msg string) {
m.Lock()
for chat := range m.chats {
log.DEBUG.Printf("telegram: sending to %d", chat)
msg := tgbotapi.NewMessage(chat, msg)
if _, err := m.bot.Send(msg); err != nil {
log.ERROR.Print(err)
}
}
m.Unlock()
}