telegram.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. m "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/services/alerting"
  9. )
  10. var (
  11. telegeramApiUrl string = "https://api.telegram.org/bot%s/%s"
  12. )
  13. func init() {
  14. alerting.RegisterNotifier(&alerting.NotifierPlugin{
  15. Type: "telegram",
  16. Name: "Telegram",
  17. Description: "Sends notifications to Telegram",
  18. Factory: NewTelegramNotifier,
  19. OptionsTemplate: `
  20. <h3 class="page-heading">Telegram API settings</h3>
  21. <div class="gf-form">
  22. <span class="gf-form-label width-9">BOT API Token</span>
  23. <input type="text" required
  24. class="gf-form-input"
  25. ng-model="ctrl.model.settings.bottoken"
  26. placeholder="Telegram BOT API Token"></input>
  27. </div>
  28. <div class="gf-form">
  29. <span class="gf-form-label width-9">Chat ID</span>
  30. <input type="text" required
  31. class="gf-form-input"
  32. ng-model="ctrl.model.settings.chatid"
  33. data-placement="right">
  34. </input>
  35. <info-popover mode="right-absolute">
  36. Integer Telegram Chat Identifier
  37. </info-popover>
  38. </div>
  39. `,
  40. })
  41. }
  42. type TelegramNotifier struct {
  43. NotifierBase
  44. BotToken string
  45. ChatID string
  46. log log.Logger
  47. }
  48. func NewTelegramNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  49. if model.Settings == nil {
  50. return nil, alerting.ValidationError{Reason: "No Settings Supplied"}
  51. }
  52. botToken := model.Settings.Get("bottoken").MustString()
  53. chatId := model.Settings.Get("chatid").MustString()
  54. if botToken == "" {
  55. return nil, alerting.ValidationError{Reason: "Could not find Bot Token in settings"}
  56. }
  57. if chatId == "" {
  58. return nil, alerting.ValidationError{Reason: "Could not find Chat Id in settings"}
  59. }
  60. return &TelegramNotifier{
  61. NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),
  62. BotToken: botToken,
  63. ChatID: chatId,
  64. log: log.New("alerting.notifier.telegram"),
  65. }, nil
  66. }
  67. func (this *TelegramNotifier) ShouldNotify(context *alerting.EvalContext) bool {
  68. return defaultShouldNotify(context)
  69. }
  70. func (this *TelegramNotifier) Notify(evalContext *alerting.EvalContext) error {
  71. this.log.Info("Sending alert notification to", "bot_token", this.BotToken)
  72. this.log.Info("Sending alert notification to", "chat_id", this.ChatID)
  73. bodyJSON := simplejson.New()
  74. bodyJSON.Set("chat_id", this.ChatID)
  75. bodyJSON.Set("parse_mode", "html")
  76. message := fmt.Sprintf("<b>%s</b>\nState: %s\nMessage: %s\n", evalContext.GetNotificationTitle(), evalContext.Rule.Name, evalContext.Rule.Message)
  77. ruleUrl, err := evalContext.GetRuleUrl()
  78. if err == nil {
  79. message = message + fmt.Sprintf("URL: %s\n", ruleUrl)
  80. }
  81. if evalContext.ImagePublicUrl != "" {
  82. message = message + fmt.Sprintf("Image: %s\n", evalContext.ImagePublicUrl)
  83. }
  84. metrics := ""
  85. fieldLimitCount := 4
  86. for index, evt := range evalContext.EvalMatches {
  87. metrics += fmt.Sprintf("\n%s: %s", evt.Metric, evt.Value)
  88. if index > fieldLimitCount {
  89. break
  90. }
  91. }
  92. if metrics != "" {
  93. message = message + fmt.Sprintf("\n<i>Metrics:</i>%s", metrics)
  94. }
  95. bodyJSON.Set("text", message)
  96. url := fmt.Sprintf(telegeramApiUrl, this.BotToken, "sendMessage")
  97. body, _ := bodyJSON.MarshalJSON()
  98. cmd := &m.SendWebhookSync{
  99. Url: url,
  100. Body: string(body),
  101. HttpMethod: "POST",
  102. }
  103. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  104. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  105. return err
  106. }
  107. return nil
  108. }