1
0
mirror of https://github.com/nikoksr/notify.git synced 2024-12-16 10:29:42 +02:00
notify/service/telegram/telegram.go

64 lines
1.6 KiB
Go
Raw Normal View History

2021-01-25 01:14:21 +02:00
package telegram
import (
"strconv"
2021-01-25 01:14:21 +02:00
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/pkg/errors"
)
const defaultParseMode = tgbotapi.ModeHTML
2021-01-25 01:14:21 +02:00
// Telegram struct holds necessary data to communicate with the Telegram API.
2021-01-25 01:14:21 +02:00
type Telegram struct {
client *tgbotapi.BotAPI
chatIDs []int64
2021-01-25 01:14:21 +02:00
}
// 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
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
}
// 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 ...string) {
for _, v := range chatIDs {
2021-01-31 14:14:48 +02:00
chatID, err := strconv.ParseInt(v, 10, 64)
if err != nil {
t.chatIDs = append(t.chatIDs, chatID)
}
}
2021-01-25 01:14:21 +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
}