forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.go
88 lines (71 loc) · 1.71 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
77
78
79
80
81
82
83
84
85
86
87
88
package push
import (
"errors"
"strconv"
"sync"
"github.com/evcc-io/evcc/util"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func init() {
registry.Add("telegram", NewTelegramFromConfig)
}
// Telegram implements the Telegram messenger
type Telegram struct {
log *util.Logger
sync.Mutex
bot *tgbotapi.BotAPI
chats map[int64]struct{}
}
// NewTelegramFromConfig creates new pushover messenger
func NewTelegramFromConfig(other map[string]interface{}) (Messenger, error) {
var cc struct {
Token string
Chats []int64
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
bot, err := tgbotapi.NewBotAPI(cc.Token)
if err != nil {
return nil, errors.New("telegram: invalid bot token")
}
log := util.NewLogger("telegram").Redact(cc.Token)
_ = tgbotapi.SetLogger(log.ERROR)
for _, i := range cc.Chats {
log.Redact(strconv.FormatInt(i, 10))
}
m := &Telegram{
log: log,
bot: bot,
chats: make(map[int64]struct{}),
}
for _, chat := range cc.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 {
m.log.INFO.Printf("new chat id: %d", update.Message.Chat.ID)
}
m.Unlock()
}
}
// Send sends to all receivers
func (m *Telegram) Send(title, msg string) {
m.Lock()
for chat := range m.chats {
m.log.DEBUG.Printf("sending to %d", chat)
msg := tgbotapi.NewMessage(chat, msg)
if _, err := m.bot.Send(msg); err != nil {
m.log.ERROR.Println("send:", err)
}
}
m.Unlock()
}