waterd - 实现发送钉钉机器人消息
这里需要补充一点姿势。
首先我需要一个钉钉 钉钉没给我广告费
其次我需要新建一个钉钉群 23132096
然后需要添加一个群机器人,赐个名叫 小水 好了
然后我们把里面的 Webhook 内容复制出来备用。
接下来对照钉钉提供的开发文档,看看怎么调用 Webhook 地址才能发送群消息。
快速过一遍,文档里有这么一句
curl 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx' \ -H 'Content-Type: application/json' \ -d '{"msgtype": "text","text": {"content": "我就是我, 是不一样的烟火"}}'
我们对照着实现一个 Send()
函数
// Send
func Send() {
webhook := "https://oapi.dingtalk.com/robot/send?access_token=xxx"
url := webhook
body := strings.NewReader(`{"msgtype": "text","text": {"content": "我就是我, 是不一样的烟火"}}`)
req, err := http.NewRequest(
http.MethodPost, // method string,
url, // url string,
body, // body io.Reader,
)
if err != nil {
log.Fatalln("http.NewRequest error:", err.Error())
}
req.Header.Set("Content-Type", "application/json;charset=utf-8")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalln("http.DefaultClient error:", err.Error())
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln("ioutil.ReadAll error:", err.Error())
}
log.Println("respBody:", string(respBody[:]))
}
再来个专门的测试文件 main_test.go, 稍显专业, 内容如下:
package main
import (
"testing"
)
// TestSend
func TestSend(t *testing.T) {
Send()
}
执行测试
go test
不出意外的话, 输出内容如下:
2020/07/04 19:01:10 respBody: {"errcode":0,"errmsg":"ok"}
PASS
ok gitee.com/taadis/letgo/app/waterd 0.730s
到钉钉群里来看看初步发送成功的效果 我执行了多次测试因此有多条记录
钉钉消息发送函数 Send()
完成了,我们替换掉之前定时调度的打印函数 print()
entryId, err := c.AddFunc(spec, Send)
然后运行程序
go run main.go
然后跟小白一样静静的等几个1分钟
最后输出如下:
go run main.go
2020/07/04 19:04:40 entryId: 1
2020/07/04 19:05:00 respBody: {"errcode":0,"errmsg":"ok"}
2020/07/04 19:06:00 respBody: {"errcode":0,"errmsg":"ok"}
2020/07/04 19:07:00 respBody: {"errcode":0,"errmsg":"ok"}
...
可以按自己需要调整调度时间及发送内容