graphicek/server/integrations/telegram.go

58 lines
1.3 KiB
Go

package integrations
import (
"encoding/json"
"fmt"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type TelegramIntegration struct{}
type TelegramNotificationChannelConfig struct {
Id int64 `json:"id"`
ApiKey string `json:"apiKey"`
TargetChannel int64 `json:"targetChannel"`
}
func (s TelegramIntegration) ProcessEvent(evt *ContactPointEvent, rawConfig string) error {
config := TelegramNotificationChannelConfig{}
err := json.Unmarshal([]byte(rawConfig), &config)
if err != nil {
return fmt.Errorf("failed to parse telegram integration config - %w", err)
}
bot, err := tgbotapi.NewBotAPI(config.ApiKey)
if err != nil {
return err
}
switch evt.Type {
case ContactPointEventAlertTriggered:
data := evt.AlertTriggeredEvent
text := fmt.Sprintf("🚨 %s is at {value}", data.Sensor.Name)
if data.Alert.CustomMessage != "" {
text = data.Alert.CustomMessage
}
text = strings.Replace(text, "{value}", fmt.Sprintf("%f", data.LastValue), -1)
msg := tgbotapi.NewMessage(config.TargetChannel, text)
msg.ParseMode = "Markdown"
_, err = bot.Send(msg)
return err
}
return nil
}
func (s TelegramIntegration) ValidateConfig(rawConfig string) error {
config := TelegramNotificationChannelConfig{}
return json.Unmarshal([]byte(rawConfig), &config)
}