-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdingding.go
85 lines (72 loc) · 2.11 KB
/
dingding.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
package webhoook_poster
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
)
const (
MsgTypeText = "text" //text 类型
MsgTypeLink = "link" //link 类型
MsgTypeMarkdown = "markdown" //markdown 类型
)
// Message 普通消息
type Message struct {
Content string `validate:"required"`
AtPerson []string `json:"atUserIds"`
AtAll bool `json:"isAtAll"`
}
// Link 链接消息
type Link struct {
Content string `json:"text" validate:"required"` // 要发送的消息, 必填
Title string `json:"title" validate:"required"` // 标题, 必填
ContentURL string `json:"messageUrl" validate:"required"` // 点击消息跳转的URL 必填
PictureURL string `json:"picUrl"` // 图片 url
AtPerson []string `json:"atUserIds"`
AtAll bool `json:"isAtAll"`
}
// Markdown markdown 类型
type Markdown struct {
Content string `json:"text" validate:"required"` // 要发送的消息, 必填
Title string `json:"title" validate:"required"` // 标题, 必填
AtPerson []string `json:"atUserIds"`
AtAll bool `json:"isAtAll"`
}
// SimpleMessage push message
type SimpleMessage struct {
Content string
Title string
}
type DingTalkPoster struct {
WebhookURL string `json:"webhook_url"`
Keyword string `json:"keyword"`
}
func NewDingTalkPoster(webhook_url, keyword string) *DingTalkPoster {
return &DingTalkPoster{
WebhookURL: webhook_url,
Keyword: keyword,
}
}
func (m *DingTalkPoster) Send(msg string) error {
// 构建消息体
message := map[string]interface{}{
"msgtype": MsgTypeText,
"text": map[string]string{
"content": fmt.Sprintf("%s\n%s", msg, m.Keyword),
},
}
// 将消息体编码为JSON格式
jsonBytes, _ := json.Marshal(message)
// 创建POST请求
req, _ := http.NewRequest("POST", m.WebhookURL, bytes.NewBuffer(jsonBytes))
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, _ := client.Do(req)
if resp.StatusCode != http.StatusOK {
return errors.New("DingTalk message send failed")
}
defer resp.Body.Close()
return nil
}