2021-01-25 01:14:21 +02:00
|
|
|
package telegram
|
|
|
|
|
|
|
|
import (
|
2021-01-30 23:20:02 +02:00
|
|
|
"strconv"
|
|
|
|
|
2021-01-25 01:14:21 +02:00
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
const defaultParseMode = tgbotapi.ModeHTML
|
2021-01-25 01:14:21 +02:00
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// Telegram struct holds necessary data to communicate with the Telegram API.
|
2021-01-25 01:14:21 +02:00
|
|
|
type Telegram struct {
|
2021-01-29 20:24:22 +02:00
|
|
|
client *tgbotapi.BotAPI
|
|
|
|
chatIDs []int64
|
2021-01-25 01:14:21 +02:00
|
|
|
}
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// New returns a new instance of a Telegram notification service.
|
2021-01-26 12:31:33 +02:00
|
|
|
// For more information about telegram api token:
|
|
|
|
// -> https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#NewBotAPI
|
2021-01-25 01:14:21 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// 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.
|
2021-01-30 23:20:02 +02:00
|
|
|
func (t *Telegram) AddReceivers(chatIDs ...string) {
|
|
|
|
for _, v := range chatIDs {
|
2021-01-31 14:14:48 +02:00
|
|
|
chatID, err := strconv.ParseInt(v, 10, 64)
|
|
|
|
if err != nil {
|
2021-01-30 23:20:02 +02:00
|
|
|
t.chatIDs = append(t.chatIDs, chatID)
|
|
|
|
}
|
|
|
|
}
|
2021-01-25 01:14:21 +02:00
|
|
|
}
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// Send takes a message subject and a message body and sends them to all previously set chats. Message body supports
|
|
|
|
// html as markup language.
|
2021-01-25 01:14:21 +02:00
|
|
|
func (t Telegram) Send(subject, message string) error {
|
|
|
|
fullMessage := subject + "\n" + message // Treating subject as message title
|
|
|
|
|
|
|
|
msg := tgbotapi.NewMessage(0, fullMessage)
|
|
|
|
msg.ParseMode = defaultParseMode
|
|
|
|
|
|
|
|
for _, chatID := range t.chatIDs {
|
|
|
|
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
|
|
|
|
}
|