Files
Message-Push-Nest/pkg/message/dtalk.go
T

95 lines
2.0 KiB
Go
Raw Normal View History

2023-12-30 17:40:20 +08:00
package message
2024-01-06 17:44:45 +08:00
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
type response struct {
Code int `json:"errcode"`
Msg string `json:"errmsg"`
2023-12-30 17:40:20 +08:00
}
2024-01-06 17:44:45 +08:00
type Dtalk struct {
AccessToken string
Secret string
}
2023-12-30 17:40:20 +08:00
2024-01-06 17:44:45 +08:00
func (t *Dtalk) Request(msg interface{}) ([]byte, error) {
b, err := json.Marshal(msg)
if err != nil {
return nil, err
}
resp, err := http.Post(t.getURL(), "application/json", bytes.NewBuffer(b))
if err != nil {
return nil, err
}
2024-01-07 00:25:35 +08:00
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
2024-01-06 17:44:45 +08:00
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var r response
err = json.Unmarshal(body, &r)
if err != nil {
return body, err
}
if r.Code != 0 {
return body, errors.New(fmt.Sprintf("response error: %s", string(body)))
}
return body, err
}
// SendMessageText Function to send message
func (t *Dtalk) SendMessageText(text string, at ...string) ([]byte, error) {
msg := map[string]interface{}{
"msgtype": "text",
"text": map[string]string{
"content": text,
},
}
resp, err := t.Request(msg)
return resp, err
}
func (t *Dtalk) SendMessageMarkdown(title, text string, at ...string) ([]byte, error) {
msg := map[string]interface{}{
"msgtype": "markdown",
"markdown": map[string]string{
"title": title,
"text": text,
},
}
resp, err := t.Request(msg)
return resp, err
}
func (t *Dtalk) 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 *Dtalk) 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&timestamp=%d&sign=%s", wh, timestamp, sign)
return url
2023-12-30 17:40:20 +08:00
}