-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebhook.go
281 lines (254 loc) · 6.53 KB
/
webhook.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package webhook
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// LinkMsg `link message struct`
type LinkMsg struct {
Title string `json:"title"`
MessageURL string `json:"messageUrl"`
PicURL string `json:"picUrl"`
}
// ActionCard `action card message struct`
type ActionCard struct {
Text string `json:"text"`
Title string `json:"title"`
SingleTitle string `json:"singleTitle"`
SingleURL string `json:"singleUrl"`
BtnOrientation string `json:"btnOrientation"`
HideAvatar string `json:"hideAvatar"` // robot message avatar
Buttons []struct {
Title string `json:"title"`
ActionURL string `json:"actionUrl"`
} `json:"btns"`
}
// PayLoad payload
type PayLoad struct {
MsgType string `json:"msgtype"`
Text struct {
Content string `json:"content"`
} `json:"text"`
Link struct {
Title string `json:"title"`
Text string `json:"text"`
PicURL string `json:"picURL"`
MessageURL string `json:"messageUrl"`
} `json:"link"`
Markdown struct {
Title string `json:"title"`
Text string `json:"text"`
} `json:"markdown"`
ActionCard ActionCard `json:"actionCard"`
FeedCard struct {
Links []LinkMsg `json:"links"`
} `json:"feedCard"`
At struct {
AtMobiles []string `json:"atMobiles"`
IsAtAll bool `json:"isAtAll"`
} `json:"at"`
}
// WebHook `web hook base config`
type WebHook struct {
accessToken string
apiUrl string
Secret string
}
// Response `DingTalk web hook response struct`
type Response struct {
ErrorCode int `json:"errcode"`
ErrorMessage string `json:"errmsg"`
}
// NewWebHook `new a WebHook`
func NewWebHook(accessToken string) *WebHook {
baseAPI := "https://oapi.dingtalk.com/robot/send"
return &WebHook{accessToken: accessToken, apiUrl: baseAPI}
}
// reset api URL
func (w *WebHook) resetApiUrl() {
w.apiUrl = "https://oapi.dingtalk.com/robot/send"
}
// real send request to api
func (w *WebHook) sendPayload(payload *PayLoad) error {
params := make(map[string]string)
var apiURL string
if strings.Contains(w.accessToken, w.apiUrl) {
apiURL = w.accessToken
} else {
params["access_token"] = w.accessToken
apiURL = w.apiUrl
}
if w.Secret != "" {
params["timestamp"], params["sign"] = w.getSign()
}
// add params
if len(params) > 0 {
apiURL = addParamsToURL(params, apiURL)
}
// get config
bs, _ := json.Marshal(payload)
// request api
resp, err := http.Post(apiURL, "application/json", bytes.NewReader(bs))
if nil != err {
return errors.New("api request error: " + err.Error())
}
// read response body
body, _ := ioutil.ReadAll(resp.Body)
// api unusual
if 200 != resp.StatusCode {
return fmt.Errorf("api response error: %d", resp.StatusCode)
}
var result Response
// json decode
err = json.Unmarshal(body, &result)
if nil != err {
return errors.New("response struct error: response is not a json anymore, " + err.Error())
}
if 0 != result.ErrorCode {
return fmt.Errorf("api custom error: {code: %d, msg: %s}", result.ErrorCode, result.ErrorMessage)
}
return nil
}
// SendTextMsg `send a text message`
func (w *WebHook) SendTextMsg(content string, isAtAll bool, mobiles ...string) error {
// send request
return w.sendPayload(&PayLoad{
MsgType: "text",
Text: struct {
Content string `json:"content"`
}{
Content: content,
},
At: struct {
AtMobiles []string `json:"atMobiles"`
IsAtAll bool `json:"isAtAll"`
}{
AtMobiles: mobiles,
IsAtAll: isAtAll,
},
})
}
// SendLinkMsg `send a link message`
func (w *WebHook) SendLinkMsg(title, content, picURL, msgURL string) error {
return w.sendPayload(&PayLoad{
MsgType: "link",
Link: struct {
Title string `json:"title"`
Text string `json:"text"`
PicURL string `json:"picURL"`
MessageURL string `json:"messageUrl"`
}{
Title: title,
Text: content,
PicURL: picURL,
MessageURL: msgURL,
},
})
}
// SendMarkdownMsg `send a markdown msg`
func (w *WebHook) SendMarkdownMsg(title, content string, isAtAll bool, mobiles ...string) error {
// send request
return w.sendPayload(&PayLoad{
MsgType: "markdown",
Markdown: struct {
Title string `json:"title"`
Text string `json:"text"`
}{
Title: title,
Text: content,
},
At: struct {
AtMobiles []string `json:"atMobiles"`
IsAtAll bool `json:"isAtAll"`
}{
AtMobiles: mobiles,
IsAtAll: isAtAll,
},
})
}
// SendActionCardMsg `send single action card message`
func (w *WebHook) SendActionCardMsg(title, content string, linkTitles, linkUrls []string, hideAvatar, btnOrientation bool) error {
// validation is empty
if 0 == len(linkTitles) || 0 == len(linkUrls) {
return errors.New("links or titles is empty!")
}
// validation is equal
if len(linkUrls) != len(linkTitles) {
return errors.New("links length and titles length is not equal!")
}
// hide robot avatar
var strHideAvatar = "0"
if hideAvatar {
strHideAvatar = "1"
}
// button sort
var strBtnOrientation = "0"
if btnOrientation {
strBtnOrientation = "1"
}
// button struct
var buttons []struct {
Title string `json:"title"`
ActionURL string `json:"actionUrl"`
}
// inject to button
for i := 0; i < len(linkTitles); i++ {
buttons = append(buttons, struct {
Title string `json:"title"`
ActionURL string `json:"actionUrl"`
}{
Title: linkTitles[i],
ActionURL: linkUrls[i],
})
}
// send request
return w.sendPayload(&PayLoad{
MsgType: "actionCard",
ActionCard: ActionCard{
Title: title,
Text: content,
HideAvatar: strHideAvatar,
BtnOrientation: strBtnOrientation,
Buttons: buttons,
},
})
}
// SendLinkCardMsg `send link card message`
func (w *WebHook) SendLinkCardMsg(messages []LinkMsg) error {
return w.sendPayload(&PayLoad{
MsgType: "feedCard",
FeedCard: struct {
Links []LinkMsg `json:"links"`
}{
Links: messages,
},
})
}
// getSign get sign
func (w *WebHook) getSign() (timestamp, sha string) {
timestamp = strconv.FormatInt(time.Now().UnixNano() / int64(time.Millisecond), 10)
message := timestamp + "\n" + w.Secret
h := hmac.New(sha256.New, []byte(w.Secret))
h.Write([]byte(message))
return timestamp, base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// addPramsToUrl
func addParamsToURL(params map[string]string, originURL string) string {
u, _ := url.Parse(originURL)
q, _ := url.ParseQuery(u.RawQuery)
for key, val := range params {
q.Set(key, val)
}
u.RawQuery = q.Encode()
return u.String()
}