-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscord.go
53 lines (43 loc) · 938 Bytes
/
discord.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
package webhoook_poster
import (
"bytes"
"encoding/json"
"errors"
"net/http"
)
type DiscordPoster struct {
WebhookURL string `json:"webhook_url"`
}
func NewDiscordPoster(webhook_url string) *DiscordPoster {
return &DiscordPoster{
WebhookURL: webhook_url,
}
}
func (m *DiscordPoster) Send(msg string) error {
// 构建消息体
message := map[string]string{
"content": msg,
}
// 将消息体编码为JSON格式
jsonBytes, err := json.Marshal(message)
if err != nil {
return err
}
// 创建POST请求
req, err := http.NewRequest("POST", m.WebhookURL, bytes.NewBuffer(jsonBytes))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusNoContent {
return errors.New("Discord message send failed")
}
defer resp.Body.Close()
return nil
}