Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include screenshot URL to Telegram message #240

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions receivers/telegram/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Config struct {
DisableWebPagePreview bool `json:"disable_web_page_preview,omitempty" yaml:"disable_web_page_preview,omitempty"`
ProtectContent bool `json:"protect_content,omitempty" yaml:"protect_content,omitempty"`
DisableNotifications bool `json:"disable_notifications,omitempty" yaml:"disable_notifications,omitempty"`
IncludeScreenshotURL bool `json:"include_screenshot_url,omitempty" yaml:"include_screenshot_url,omitempty"`
}

func NewConfig(jsonData json.RawMessage, decryptFn receivers.DecryptFunc) (Config, error) {
Expand Down
9 changes: 9 additions & 0 deletions receivers/telegram/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: false,
ProtectContent: false,
DisableNotifications: false,
IncludeScreenshotURL: false,
},
},
{
Expand All @@ -66,6 +67,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: false,
ProtectContent: false,
DisableNotifications: false,
IncludeScreenshotURL: false,
},
},
{
Expand All @@ -82,6 +84,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: false,
ProtectContent: false,
DisableNotifications: false,
IncludeScreenshotURL: false,
},
},
{
Expand All @@ -103,6 +106,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: false,
ProtectContent: false,
DisableNotifications: false,
IncludeScreenshotURL: false,
},
},
{
Expand All @@ -117,6 +121,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: true,
ProtectContent: true,
DisableNotifications: true,
IncludeScreenshotURL: true,
},
},
{
Expand All @@ -132,6 +137,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: true,
ProtectContent: true,
DisableNotifications: true,
IncludeScreenshotURL: true,
},
},
{
Expand All @@ -156,6 +162,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: false,
ProtectContent: false,
DisableNotifications: false,
IncludeScreenshotURL: false,
},
},
{
Expand All @@ -172,6 +179,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: false,
ProtectContent: false,
DisableNotifications: false,
IncludeScreenshotURL: false,
},
},
{
Expand All @@ -188,6 +196,7 @@ func TestNewConfig(t *testing.T) {
DisableWebPagePreview: false,
ProtectContent: false,
DisableNotifications: false,
IncludeScreenshotURL: false,
},
},
{
Expand Down
60 changes: 36 additions & 24 deletions receivers/telegram/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,34 +74,37 @@ func (tn *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error
}

// Create the cmd to upload each image
_ = images.WithStoredImages(ctx, tn.log, tn.images, func(_ int, image images.Image) error {
cmd, err = tn.newWebhookSyncCmd("sendPhoto", func(w *multipart.Writer) error {
f, err := os.Open(image.Path)
if err != nil {
return fmt.Errorf("failed to open image: %w", err)
}
defer func() {
if err := f.Close(); err != nil {
tn.log.Warn("failed to close image", "error", err)
// Works only if IncludeScreenshotURL is set to false.
if !tn.settings.IncludeScreenshotURL {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's invert this expression. Go's best practices recommend reducing nesting, and this is a good candidate.

_ = images.WithStoredImages(ctx, tn.log, tn.images, func(_ int, image images.Image) error {
cmd, err = tn.newWebhookSyncCmd("sendPhoto", func(w *multipart.Writer) error {
f, err := os.Open(image.Path)
if err != nil {
return fmt.Errorf("failed to open image: %w", err)
}
defer func() {
if err := f.Close(); err != nil {
tn.log.Warn("failed to close image", "error", err)
}
}()
fw, err := w.CreateFormFile("photo", image.Path)
if err != nil {
return fmt.Errorf("failed to create form file: %w", err)
}
}()
fw, err := w.CreateFormFile("photo", image.Path)
if _, err := io.Copy(fw, f); err != nil {
return fmt.Errorf("failed to write to form file: %w", err)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to create form file: %w", err)
return fmt.Errorf("failed to create image: %w", err)
}
if _, err := io.Copy(fw, f); err != nil {
return fmt.Errorf("failed to write to form file: %w", err)
if err := tn.ns.SendWebhook(ctx, cmd); err != nil {
return fmt.Errorf("failed to upload image to telegram: %w", err)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to create image: %w", err)
}
if err := tn.ns.SendWebhook(ctx, cmd); err != nil {
return fmt.Errorf("failed to upload image to telegram: %w", err)
}
return nil
}, as...)
}, as...)
}

return true, nil
}
Expand All @@ -116,7 +119,16 @@ func (tn *Notifier) buildTelegramMessage(ctx context.Context, as []*types.Alert)

tmpl, _ := templates.TmplText(ctx, tn.tmpl, as, tn.log, &tmplErr)
// Telegram supports 4096 chars max
messageText, truncated := receivers.TruncateInRunes(tmpl(tn.settings.Message), telegramMaxMessageLenRunes)
rawMessage := tmpl(tn.settings.Message)
if tn.settings.IncludeScreenshotURL {
_ = images.WithStoredImages(ctx, tn.log, tn.images, func(_ int, image images.Image) error {
if len(image.URL) != 0 {
rawMessage += " " + image.URL
}
return nil
}, as...)
}
messageText, truncated := receivers.TruncateInRunes(rawMessage, telegramMaxMessageLenRunes)
if truncated {
key, err := notify.ExtractGroupKey(ctx)
if err != nil {
Expand Down
33 changes: 33 additions & 0 deletions receivers/telegram/telegram_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func TestNotify(t *testing.T) {
DisableWebPagePreview: true,
ProtectContent: true,
DisableNotifications: true,
IncludeScreenshotURL: false,
},
alerts: []*types.Alert{
{
Expand Down Expand Up @@ -131,6 +132,38 @@ func TestNotify(t *testing.T) {
"text": strings.Repeat("1", 4096-1) + "…",
}},
expMsgError: nil,
}, {
name: "A single alert with default template and inline image URL",
settings: Config{
BotToken: "abcdefgh0123456789",
ChatID: "someid",
MessageThreadID: "threadid",
Message: templates.DefaultMessageEmbed,
ParseMode: "Markdown",
DisableWebPagePreview: true,
ProtectContent: true,
DisableNotifications: true,
IncludeScreenshotURL: true,
},
alerts: []*types.Alert{
{
Alert: model.Alert{
Labels: model.LabelSet{"alertname": "alert1", "lbl1": "val1"},
Annotations: model.LabelSet{"ann1": "annv1", "__dashboardUid__": "abcd", "__panelId__": "efgh", "__alertImageToken__": "test-image-1"},
GeneratorURL: "a URL",
},
},
},
expMsg: []map[string]string{{
"chat_id": "someid",
"message_thread_id": "threadid",
"parse_mode": "Markdown",
"text": "**Firing**\n\nValue: [no value]\nLabels:\n - alertname = alert1\n - lbl1 = val1\nAnnotations:\n - ann1 = annv1\nSource: a URL\nSilence: http://localhost/alerting/silence/new?alertmanager=grafana&matcher=alertname%3Dalert1&matcher=lbl1%3Dval1\nDashboard: http://localhost/d/abcd\nPanel: http://localhost/d/abcd?viewPanel=efgh\n https://www.example.com/test-image-1",
"disable_web_page_preview": "true",
"protect_content": "true",
"disable_notification": "true",
}},
expMsgError: nil,
},
}

Expand Down
3 changes: 2 additions & 1 deletion receivers/telegram/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const FullValidConfigForTesting = `{
"parse_mode" :"html",
"disable_web_page_preview" :true,
"protect_content" :true,
"disable_notifications" :true
"disable_notifications" :true,
"include_screenshot_url" :true
}`

// FullValidSecretsForTesting is a string representation of JSON object that contains all fields that can be overridden from secrets
Expand Down