...

Source file src/github.com/prometheus/alertmanager/notify/telegram/telegram.go

Documentation: github.com/prometheus/alertmanager/notify/telegram

     1  // Copyright 2022 Prometheus Team
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package telegram
    15  
    16  import (
    17  	"context"
    18  	"fmt"
    19  	"net/http"
    20  
    21  	"github.com/go-kit/log"
    22  	"github.com/go-kit/log/level"
    23  	commoncfg "github.com/prometheus/common/config"
    24  	"gopkg.in/telebot.v3"
    25  
    26  	"github.com/prometheus/alertmanager/config"
    27  	"github.com/prometheus/alertmanager/notify"
    28  	"github.com/prometheus/alertmanager/template"
    29  	"github.com/prometheus/alertmanager/types"
    30  )
    31  
    32  // Telegram supports 4096 chars max - from https://limits.tginfo.me/en.
    33  const maxMessageLenRunes = 4096
    34  
    35  // Notifier implements a Notifier for telegram notifications.
    36  type Notifier struct {
    37  	conf    *config.TelegramConfig
    38  	tmpl    *template.Template
    39  	logger  log.Logger
    40  	client  *telebot.Bot
    41  	retrier *notify.Retrier
    42  }
    43  
    44  // New returns a new Telegram notification handler.
    45  func New(conf *config.TelegramConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
    46  	httpclient, err := commoncfg.NewClientFromConfig(*conf.HTTPConfig, "telegram", httpOpts...)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	client, err := createTelegramClient(conf.BotToken, conf.APIUrl.String(), conf.ParseMode, httpclient)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  
    56  	return &Notifier{
    57  		conf:    conf,
    58  		tmpl:    t,
    59  		logger:  l,
    60  		client:  client,
    61  		retrier: &notify.Retrier{},
    62  	}, nil
    63  }
    64  
    65  func (n *Notifier) Notify(ctx context.Context, alert ...*types.Alert) (bool, error) {
    66  	var (
    67  		err  error
    68  		data = notify.GetTemplateData(ctx, n.tmpl, alert, n.logger)
    69  		tmpl = notify.TmplText(n.tmpl, data, &err)
    70  	)
    71  
    72  	if n.conf.ParseMode == "HTML" {
    73  		tmpl = notify.TmplHTML(n.tmpl, data, &err)
    74  	}
    75  
    76  	key, ok := notify.GroupKey(ctx)
    77  	if !ok {
    78  		return false, fmt.Errorf("group key missing")
    79  	}
    80  
    81  	messageText, truncated := notify.TruncateInRunes(tmpl(n.conf.Message), maxMessageLenRunes)
    82  	if truncated {
    83  		level.Warn(n.logger).Log("msg", "Truncated message", "alert", key, "max_runes", maxMessageLenRunes)
    84  	}
    85  
    86  	message, err := n.client.Send(telebot.ChatID(n.conf.ChatID), messageText, &telebot.SendOptions{
    87  		DisableNotification:   n.conf.DisableNotifications,
    88  		DisableWebPagePreview: true,
    89  	})
    90  	if err != nil {
    91  		return true, err
    92  	}
    93  	level.Debug(n.logger).Log("msg", "Telegram message successfully published", "message_id", message.ID, "chat_id", message.Chat.ID)
    94  
    95  	return false, nil
    96  }
    97  
    98  func createTelegramClient(token config.Secret, apiURL, parseMode string, httpClient *http.Client) (*telebot.Bot, error) {
    99  	secret := string(token)
   100  	bot, err := telebot.NewBot(telebot.Settings{
   101  		Token:     secret,
   102  		URL:       apiURL,
   103  		ParseMode: parseMode,
   104  		Client:    httpClient,
   105  		Offline:   true,
   106  	})
   107  	if err != nil {
   108  		return nil, err
   109  	}
   110  
   111  	return bot, nil
   112  }
   113  

View as plain text