-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalert_sender.go
115 lines (84 loc) · 2.19 KB
/
alert_sender.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
func SendAlert(alertType, alertValue string, stats DetailedIntervalStat, config *Config) error {
statsString, err := json.Marshal(stats)
if err != nil {
return err
}
message := fmt.Sprintf("Alert: %s at %s\n\n%s", alertType, alertValue, statsString)
if config.TelegramToken != "" {
err = telegramMessage(message, config)
if err != nil {
return err
}
}
if config.DiscordWebhookURL != "" {
err = discordMessage(message, config)
if err != nil {
return err
}
}
if config.CustomWebhookURL != "" {
err = customWebhookMessage(message, config)
if err != nil {
return err
}
}
return nil
}
func telegramMessage(message string, config *Config) error {
baseURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", config.TelegramToken)
params := url.Values{}
params.Add("text", message)
params.Add("chat_id", config.TelegramChatId)
fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
resp, err := http.Get(fullURL)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to send message, status code: %d", resp.StatusCode)
}
return nil
}
func discordMessage(message string, config *Config) error {
baseURL := config.DiscordWebhookURL
var body struct {
Content string `json:"content"`
}
body.Content = message
bodyJson, _ := json.Marshal(body)
resp, err := http.Post(baseURL, "application/json", bytes.NewBuffer(bodyJson))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to send message, status code: %d", resp.StatusCode)
}
return nil
}
func customWebhookMessage(message string, config *Config) error {
baseURL := config.CustomWebhookURL
var body struct {
Content string `json:"text"`
}
body.Content = message
bodyJson, _ := json.Marshal(body)
resp, err := http.Post(baseURL, "application/json", bytes.NewBuffer(bodyJson))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to send message, status code: %d", resp.StatusCode)
}
return nil
}