工作中,經常會遇到事件通知,目前用比較多的是釘釘,群自定義機器人可以讓我們快速實現消息通知。
包
package dingtalk
?
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strconv"
"time"
)
?
// SendMessage 發送釘釘機器人消息
func SendMessage(url, message string, ats ...string) (respContent string, err error) {
c := &http.Client{
Timeout: time.Second * 30,
}
data := map[string]interface{}{
"msgtype": "text",
"text": map[string]string{"content": message},
}
if len(ats) != 0 {
isAtAll := false
atMobiles := []string{}
for i := range ats {
if ats[i] == "all" {
isAtAll = true
} else {
atMobiles = Append(atMobiles, ats[i])
}
}
data["at"] = map[string]interface{}{
"isAtAll": isAtAll,
"atMobiles": atMobiles,
}
}
b, _ := json.Marshal(data)
resp, err := c.Post(url, "application/json", bytes.NewReader(b))
if err != nil {
return "post請求失敗", err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode == 200 {
return string(body), nil
}
return string(body), errors.New(strconv.Itoa(resp.StatusCode))
}
測試
package main
?
import (
"fmt"
"dingtalk"
)
?
func main() {
result, err := dingtalk.SendMessage("https://oapi.dingtalk.com/robot/send?access_token=XXXXXX", "測試消息通知", "all")
if err != nil {
fmt.Println("發送失敗", result)
return
}
fmt.Println("發送成功", result)
}