forked from xthz/ding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathding.go
80 lines (75 loc) · 1.79 KB
/
ding.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
package ding
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type Webhook struct {
AccessToken string
Secret string
EnableAt bool
AtAll bool
}
// SendMessage Function to send message
//goland:noinspection GoUnhandledErrorResult
func (t *Webhook) SendMessage(s string, at ...string) error {
msg := map[string]interface{}{
"msgtype": "text",
"text": map[string]string{
"content": s,
},
}
if t.EnableAt {
if t.AtAll {
if len(at) > 0 {
return errors.New("the parameter \"AtAll\" is \"true\", but the \"at\" parameter of SendMessage is not empty")
}
msg["at"] = map[string]interface{}{
"isAtAll": t.AtAll,
}
} else {
msg["at"] = map[string]interface{}{
"atMobiles": at,
"isAtAll": t.AtAll,
}
}
} else {
if len(at) > 0 {
return errors.New("the parameter \"EnableAt\" is \"false\", but the \"at\" parameter of SendMessage is not empty")
}
}
b, err := json.Marshal(msg)
if err != nil {
return err
}
resp, err := http.Post(t.getURL(), "application/json", bytes.NewBuffer(b))
if err != nil {
return err
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return nil
}
func (t *Webhook) hmacSha256(stringToSign string, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(stringToSign))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func (t *Webhook) getURL() string {
wh := "https://oapi.dingtalk.com/robot/send?access_token=" + t.AccessToken
timestamp := time.Now().UnixNano() / 1e6
stringToSign := fmt.Sprintf("%d\n%s", timestamp, t.Secret)
sign := t.hmacSha256(stringToSign, t.Secret)
url := fmt.Sprintf("%s×tamp=%d&sign=%s", wh, timestamp, sign)
return url
}