-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.go
56 lines (47 loc) · 1.17 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
package main
import (
"fmt"
"strconv"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/pkg/errors"
)
var (
tgBot *tgbotapi.BotAPI
tgRooms []int64
)
// initTgBot initialize telegram bot
//
// apiToken: telegram bot api token
// roomIDs: telegram room id (slice of string)
func initTgBot(apiToken string, roomIDs string) error {
if tgBot != nil {
return fmt.Errorf("tgBot already initialized")
}
var err error
tgBot, err = tgbotapi.NewBotAPI(apiToken)
if err != nil {
return errors.Wrap(err, "fail to init telegram bot")
}
for _, roomID := range strings.Split(roomIDs, ",") {
id, err := strconv.ParseInt(strings.TrimSpace(roomID), 10, 64)
if err != nil {
return errors.Wrap(err, "fail to init telegram bot")
}
tgRooms = append(tgRooms, id)
}
return nil
}
// sendMsgToTelegram send msg to telegram multiple rooms
func sendMsgToTelegram(msg string) error {
if len(tgRooms) == 0 {
return fmt.Errorf("no telegram room to send")
}
for _, roomID := range tgRooms {
c := tgbotapi.NewMessage(roomID, msg)
if _, err := tgBot.Send(c); err != nil {
return errors.Wrap(err, "fail to send msg to telegram")
}
}
return nil
}