-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotify.go
68 lines (57 loc) · 1.54 KB
/
notify.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
const maxContentLength = 2000 - 6 // ``` and ```
func main() {
webhookURL := os.Getenv("DISCORD_WEBHOOK_URL")
if webhookURL == "" {
fmt.Fprintf(os.Stderr, "Error: DISCORD_WEBHOOK_URL environment variable is not set\n")
os.Exit(1)
}
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading stdin: %v\n", err)
os.Exit(1)
}
content := string(input)
chunks := splitContent(content, maxContentLength)
for _, chunk := range chunks {
payload := map[string]string{
"content": "```" + chunk + "```",
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Fprintf(os.Stderr, "Error encoding payload to JSON: %v\n", err)
os.Exit(1)
}
resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Fprintf(os.Stderr, "Error sending request to Discord: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Fprintf(os.Stderr, "Discord webhook returned error: %s\n", string(body))
os.Exit(1)
}
}
fmt.Println("Notification sent to Discord successfully.")
}
func splitContent(content string, length int) []string {
var chunks []string
for len(content) > length {
chunks = append(chunks, content[:length])
content = content[length:]
}
if len(content) > 0 {
chunks = append(chunks, content)
}
return chunks
}