forked from nikoksr/notify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.go
85 lines (70 loc) · 2.22 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
package telegram
import (
"context"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/pkg/errors"
)
const (
ModeMarkdown = tgbotapi.ModeMarkdown
ModeHTML = tgbotapi.ModeHTML
)
var parseMode = ModeHTML // HTML is the default mode.
// Telegram struct holds necessary data to communicate with the Telegram API.
type Telegram struct {
client *tgbotapi.BotAPI
chatIDs []int64
}
// New returns a new instance of a Telegram notification service.
// For more information about telegram api token:
//
// -> https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#NewBotAPI
func New(apiToken string) (*Telegram, error) {
client, err := tgbotapi.NewBotAPI(apiToken)
if err != nil {
return nil, err
}
t := &Telegram{
client: client,
chatIDs: []int64{},
}
return t, nil
}
// SetClient set a new custom BotAPI instance.
// For example allowing you to use NewBotAPIWithClient:
//
// -> https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#NewBotAPIWithClient
func (t *Telegram) SetClient(client *tgbotapi.BotAPI) {
t.client = client
}
// SetParseMode sets the parse mode for the message body.
// For more information about telegram constants:
//
// -> https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#pkg-constants
func (t *Telegram) SetParseMode(mode string) {
parseMode = mode
}
// AddReceivers takes Telegram chat IDs and adds them to the internal chat ID list. The Send method will send
// a given message to all those chats.
func (t *Telegram) AddReceivers(chatIDs ...int64) {
t.chatIDs = append(t.chatIDs, chatIDs...)
}
// Send takes a message subject and a message body and sends them to all previously set chats. Message body supports
// html as markup language.
func (t Telegram) Send(ctx context.Context, subject, message string) error {
fullMessage := subject + "\n" + message // Treating subject as message title
msg := tgbotapi.NewMessage(0, fullMessage)
msg.ParseMode = parseMode
for _, chatID := range t.chatIDs {
select {
case <-ctx.Done():
return ctx.Err()
default:
msg.ChatID = chatID
_, err := t.client.Send(msg)
if err != nil {
return errors.Wrapf(err, "failed to send message to Telegram chat '%d'", chatID)
}
}
}
return nil
}