具体的细节可以参考官方文档-自定义钉钉群机器人开发
官方提供的Python版本SDK bug太多,而且开发文档没有提供具体的代码示例,不建议使用
1. 实现代码
import requests
import json
def dingtalk_robot():
url = "https://oapi.dingtalk.com/robot/send?access_token=xxxxxx"
headers = {'Content-Type':'application/json'}
data_dict = {
"msgtype":"markdown",
"markdown":{
"title":"Spark Monitor",
"text":"### Spark application运行时间监控Test\n\n"
"> **Application_ID:** app-20201208100505-58622\n\n"
"> **Name:** compute_04\n\n"
"> **Duration:** 4.4 h"
}
}
json_data =json.dumps(data_dict)
response = requests.post(url, data = json_data,headers = headers)
print(response.text) # {"errcode":0,"errmsg":"ok"}
if __name__ == '__main__':
dingtalk_robot()
2. 钉钉群收到的消息
3. 代码说明
- 只需通过post方式向群机器人的webhook发送消息即可,本文使用的是markdown,其它类型如text、link类型,只需参考官网的消息类型及数据格式部分,修改代码中的data_dict就可以了
4. shell脚本版本
token="xxxxxx"
Name="compute_04"
curl 'https://oapi.dingtalk.com/robot/send?access_token='$token \
-H 'Content-Type: application/json' \
-d '{"msgtype": "markdown","markdown": {"title": "Spark Monitor",
"text": "
### Spark application运行时间监控Test\n\n
> **Application_ID:** app-20201208100505-58622\n\n
> **Name:** '${Name}'\n\n
> **Duration:** 4.4 h
"}}'