Skip to content

Commit e7453d0

Browse files
authored
Merge pull request benjojo#7 from prmsrswt/discord-rich-embed
Send alerts in Discord's rich embed format
2 parents 3b4fad8 + db70e42 commit e7453d0

File tree

1 file changed

+41
-8
lines changed

1 file changed

+41
-8
lines changed

main.go

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ import (
1111
"strings"
1212
)
1313

14+
// Discord color values
15+
const (
16+
ColorRed = 10038562
17+
ColorGreen = 3066993
18+
ColorGrey = 9807270
19+
)
20+
1421
type alertManAlert struct {
1522
Annotations struct {
1623
Description string `json:"description"`
@@ -42,8 +49,20 @@ type alertManOut struct {
4249
}
4350

4451
type discordOut struct {
45-
Content string `json:"content"`
46-
Name string `json:"username"`
52+
Content string `json:"content"`
53+
Embeds []discordEmbed `json:"embeds"`
54+
}
55+
56+
type discordEmbed struct {
57+
Title string `json:"title"`
58+
Description string `json:"description"`
59+
Color int `json:"color"`
60+
Fields []discordEmbedField `json:"fields"`
61+
}
62+
63+
type discordEmbedField struct {
64+
Name string `json:"name"`
65+
Value string `json:"value"`
4766
}
4867

4968
func main() {
@@ -76,24 +95,38 @@ func main() {
7695
}
7796

7897
for status, alerts := range groupedAlerts {
79-
DO := discordOut{
80-
Name: status,
98+
DO := discordOut{}
99+
100+
RichEmbed := discordEmbed{
101+
Title: fmt.Sprintf("[%s:%d] %s", strings.ToUpper(status), len(alerts), amo.CommonLabels.Alertname),
102+
Description: amo.CommonAnnotations.Summary,
103+
Color: ColorGrey,
104+
Fields: []discordEmbedField{},
105+
}
106+
107+
if status == "firing" {
108+
RichEmbed.Color = ColorRed
109+
} else if status == "resolved" {
110+
RichEmbed.Color = ColorGreen
81111
}
82112

83-
Content := "```"
84113
if amo.CommonAnnotations.Summary != "" {
85-
Content = fmt.Sprintf(" === %s === \n```", amo.CommonAnnotations.Summary)
114+
DO.Content = fmt.Sprintf(" === %s === \n", amo.CommonAnnotations.Summary)
86115
}
87116

88117
for _, alert := range alerts {
89118
realname := alert.Labels["instance"]
90119
if strings.Contains(realname, "localhost") && alert.Labels["exported_instance"] != "" {
91120
realname = alert.Labels["exported_instance"]
92121
}
93-
Content += fmt.Sprintf("[%s]: %s on %s\n%s\n\n", strings.ToUpper(status), alert.Labels["alertname"], realname, alert.Annotations.Description)
122+
123+
RichEmbed.Fields = append(RichEmbed.Fields, discordEmbedField{
124+
Name: fmt.Sprintf("[%s]: %s on %s", strings.ToUpper(status), alert.Labels["alertname"], realname),
125+
Value: alert.Annotations.Description,
126+
})
94127
}
95128

96-
DO.Content = Content + "```"
129+
DO.Embeds = []discordEmbed{RichEmbed}
97130

98131
DOD, _ := json.Marshal(DO)
99132
http.Post(*whURL, "application/json", bytes.NewReader(DOD))

0 commit comments

Comments
 (0)