欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

golang 调用钉钉来发送群组僵尸消息

最编程 2024-05-02 13:57:58
...
package ding import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net/http" "time" ) type ClientImpl struct { AccessToken string Secret string EnableAt bool AtAll bool } func NewClient(token, secret string, opt ...DingOptionFn) Client { r := &ClientImpl{ AccessToken: token, Secret: secret, } for _, v := range opt { v(r) } return r } type DingOptionFn func(*ClientImpl) func WithEnableAt() DingOptionFn { return func(client *ClientImpl) { client.EnableAt = true } } func WithAtAll() DingOptionFn { return func(client *ClientImpl) { client.AtAll = true } } // From https://github.com/wanghuiyt/ding // SendMessage Function to send message // //goland:noinspection GoUnhandledErrorResult func (p *ClientImpl) SendMessage(s string, at ...string) error { msg := map[string]interface{}{ "msgtype": "text", "text": map[string]string{ "content": s, }, } if p.EnableAt { if p.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": p.AtAll, } } else { msg["at"] = map[string]interface{}{ "atMobiles": at, "isAtAll": p.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(p.getURL(), "application/json", bytes.NewBuffer(b)) if err != nil { return err } defer resp.Body.Close() _, err = io.ReadAll(resp.Body) if err != nil { return err } return nil } func (p *ClientImpl) 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 (p *ClientImpl) getURL() string { wh := "https://oapi.dingtalk.com/robot/send?access_token=" + p.AccessToken timestamp := time.Now().UnixNano() / 1e6 stringToSign := fmt.Sprintf("%d\n%s", timestamp, p.Secret) sign := p.hmacSha256(stringToSign, p.Secret) url := fmt.Sprintf("%s&timestamp=%d&sign=%s", wh, timestamp, sign) return url }