telegram.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package notifiers
  2. import (
  3. "fmt"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/components/simplejson"
  6. "github.com/grafana/grafana/pkg/log"
  7. "github.com/grafana/grafana/pkg/metrics"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/services/alerting"
  10. )
  11. var (
  12. telegeramApiUrl string = "https://api.telegram.org/bot%s/%s"
  13. )
  14. func init() {
  15. alerting.RegisterNotifier("telegram", NewTelegramNotifier)
  16. }
  17. type TelegramNotifier struct {
  18. NotifierBase
  19. BotToken string
  20. ChatID string
  21. log log.Logger
  22. }
  23. func NewTelegramNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  24. if model.Settings == nil {
  25. return nil, alerting.ValidationError{Reason: "No Settings Supplied"}
  26. }
  27. botToken := model.Settings.Get("bottoken").MustString()
  28. chatId := model.Settings.Get("chatid").MustString()
  29. if botToken == "" {
  30. return nil, alerting.ValidationError{Reason: "Could not find Bot Token in settings"}
  31. }
  32. if chatId == "" {
  33. return nil, alerting.ValidationError{Reason: "Could not find Chat Id in settings"}
  34. }
  35. return &TelegramNotifier{
  36. NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),
  37. BotToken: botToken,
  38. ChatID: chatId,
  39. log: log.New("alerting.notifier.telegram"),
  40. }, nil
  41. }
  42. func (this *TelegramNotifier) Notify(evalContext *alerting.EvalContext) error {
  43. this.log.Info("Sending alert notification to", "bot_token", this.BotToken)
  44. this.log.Info("Sending alert notification to", "chat_id", this.ChatID)
  45. metrics.M_Alerting_Notification_Sent_Telegram.Inc(1)
  46. bodyJSON := simplejson.New()
  47. bodyJSON.Set("chat_id", this.ChatID)
  48. bodyJSON.Set("parse_mode", "html")
  49. message := fmt.Sprintf("%s\nState: %s\nMessage: %s\n", evalContext.GetNotificationTitle(), evalContext.Rule.Name, evalContext.Rule.Message)
  50. ruleUrl, err := evalContext.GetRuleUrl()
  51. if err == nil {
  52. message = message + fmt.Sprintf("URL: %s\n", ruleUrl)
  53. }
  54. bodyJSON.Set("text", message)
  55. url := fmt.Sprintf(telegeramApiUrl, this.BotToken, "sendMessage")
  56. body, _ := bodyJSON.MarshalJSON()
  57. cmd := &m.SendWebhookSync{
  58. Url: url,
  59. Body: string(body),
  60. HttpMethod: "POST",
  61. }
  62. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  63. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  64. return err
  65. }
  66. return nil
  67. }