
利用钉钉机器人,实现python向钉钉发送消息
参考钉钉的开发文档 https://open.dingtalk.com/document/robots/customize-robot-security-settings。加签方式需要把timestamp+“\n”+密钥当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。最终
·
(1)添加群机器人
我添加的是自定义机器人,安全设置选择的是“加签”。
(2)在python中调用
①url的获取
参考钉钉的开发文档 https://open.dingtalk.com/document/robots/customize-robot-security-settings。加签方式需要把timestamp+“\n”+密钥当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。该文档提供了python签名计算的代码,直接粘贴即可。最终拼接到调用的url中:https://oapi.dingtalk.com/robot/send?access_token=XXXXXX×tamp=XXX&sign=XXX
参数 | 说明 |
---|---|
https://oapi.dingtalk.com/robot/send?access_token=XXXXXX | 钉钉定义的Webhook |
timestamp | python中获得的时间戳 |
sign | python中获得的签名值 |
②调用函数。以下代码为通用函数,需结合安全方式做调整。
import requests
import json
def send_dingtalk_message(webhook_url, message):
data = {
"msgtype": "text",
"text": {
"content": message
}
}
headers = {
"Content-Type": "application/json;charset=utf-8"
}
response = requests.post(webhook_url, data=json.dumps(data), headers=headers)
return response.json()
webhook_url = "您的Webhook地址"
message = "您要发送的消息"
response = send_dingtalk_message(webhook_url, message)
print(response)
③消息格式
如上段代码,可发送普通消息。如需发送markdown格式的消息,则需要调整代码。
import requests
import json
def send_dingtalk_message(webhook_url, title, message):
data = {
"msgtype": "markdown",
"markdown": {
"title": "Markdown消息",
"text": message
}
}
headers = {
"Content-Type": "application/json;charset=utf-8"
}
response = requests.post(webhook_url, data=json.dumps(data), headers=headers)
return response.json()
title= "题目"
webhook_url = "您的Webhook地址"
message = "**加粗**和*斜体*的文本"
response = send_dingtalk_message(webhook_url, message)
print(response)
其中markdown格式的消息,钉钉支持如下格式:
标题
# 一级标题
## 二级标题
### 三级标题
#### 四级标题
##### 五级标题
###### 六级标题
引用
> A man who stands for nothing will fall for anything.
文字加粗、斜体
**bold**
*italic*
链接
[this is a link](http://name.com)
图片(建议不要超过20张)

无序列表
- item1
- item2
有序列表
1. item1
2. item2
效果如下:
更多推荐
所有评论(0)