forked from benjojo/alertmanager-discord
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
98 lines (87 loc) · 2.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"os"
"io/ioutil"
"net/http"
"strings"
)
type alertManOut struct {
Alerts []struct {
Annotations struct {
Description string `json:"description"`
Summary string `json:"summary"`
} `json:"annotations"`
EndsAt string `json:"endsAt"`
GeneratorURL string `json:"generatorURL"`
Labels map[string]string `json:"labels"`
StartsAt string `json:"startsAt"`
Status string `json:"status"`
} `json:"alerts"`
CommonAnnotations struct {
Summary string `json:"summary"`
} `json:"commonAnnotations"`
CommonLabels struct {
Alertname string `json:"alertname"`
} `json:"commonLabels"`
ExternalURL string `json:"externalURL"`
GroupKey string `json:"groupKey"`
GroupLabels struct {
Alertname string `json:"alertname"`
} `json:"groupLabels"`
Receiver string `json:"receiver"`
Status string `json:"status"`
Version string `json:"version"`
}
type discordOut struct {
Content string `json:"content"`
Name string `json:"username"`
}
func main() {
webhookUrl := os.Getenv("DISCORD_WEBHOOK")
if webhookUrl == "" {
fmt.Fprintf(os.Stderr, "error: environment variable DISCORD_WEBHOOK not found\n")
os.Exit(1)
}
whURL := flag.String("webhook.url", webhookUrl, "")
flag.Parse()
fmt.Fprintf(os.Stdout, "info: Listening on 0.0.0.0:9094\n")
http.ListenAndServe(":9094", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
amo := alertManOut{}
err = json.Unmarshal(b, &amo)
if err != nil {
panic(err)
}
DO := discordOut{
Name: amo.Status,
}
emoji := "bell"
// Let's have a nice emoji
if strings.ToUpper(amo.Status) == "FIRING" {
emoji = ":airplane_arriving: :fire:"
} else {
emoji = ":wine_glass: :cheese:"
}
Content := "```"
if amo.CommonAnnotations.Summary != "" {
Content = fmt.Sprintf("%s %s\n```\n", emoji, amo.CommonAnnotations.Summary)
}
for _, alert := range amo.Alerts {
realname := alert.Labels["instance"]
if strings.Contains(realname, "localhost") && alert.Labels["exported_instance"] != "" {
realname = alert.Labels["exported_instance"]
}
Content += fmt.Sprintf("[%s]: %s on %s\n%s\n\n", strings.ToUpper(amo.Status), alert.Labels["alertname"], realname, alert.Annotations.Description)
}
DO.Content = Content + "```"
DOD, _ := json.Marshal(DO)
http.Post(*whURL, "application/json", bytes.NewReader(DOD))
}))
}