Python|钉钉消息通知对接

钉钉相比微信的好处在于接口丰富(《钉钉接口文档》),今天通过两种方式实现钉钉通知的对接:

方式一:钉钉群聊机器人

步骤

  1. 在钉钉中创建一个群聊机器人。在安全设置中选择“加签”,之后会生成一个密钥,复制下来后续有用;webhook也复制下来后续有用。
  2. 参照接口文档中即时通信IM-机器人部分的文档进行调用。

简单聊天信息的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

import json
import hashlib
import base64
import hmac
import os
import time
import requests
from urllib.parse import quote_plus

class Messenger:
def __init__(self, token=os.getenv("DD_ACCESS_TOKEN"), secret=os.getenv("DD_SECRET")):
self.timestamp = str(round(time.time() * 1000))
self.URL = "https://oapi.dingtalk.com/robot/send"
self.headers = {'Content-Type': 'application/json'}
secret = secret
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(self.timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
self.sign = quote_plus(base64.b64encode(hmac_code))
self.params = {'access_token': token, "sign": self.sign}

def send_text(self, content):
"""
发送文本
@param content: str, 文本内容
"""
data = {"msgtype": "text", "text": {"content": content}}
self.params["timestamp"] = self.timestamp
return requests.post(
url=self.URL,
data=json.dumps(data),
params=self.params,
headers=self.headers
)
def send_md(self, title, content):
"""
发送Markdown文本
@param title: str, 标题
@param content: str, 文本内容
"""
data = {"msgtype": "markdown", "markdown": {"title": title, "text": content}}
self.params["timestamp"] = self.timestamp
return requests.post(
url=self.URL,
data=json.dumps(data),
params=self.params,
headers=self.headers
)

if __name__ == "__main__":
# markdown_text = "\n".join(open("D://UiAuto_ecologyFileDownload.md", encoding="utf-8").readlines())
m = Messenger(
token="webhook中的token信息",
secret="在安全设置勾选加签后生成的密钥"
)
# m.send_md("测试Markdown", markdown_text)
m.send_text("数字员工机器人test")

方式二:钉钉应用工作通知

步骤

  1. 在钉钉管理后台创建一个应用,复制生成的应用凭证信息(AgentId,AppKey,AppSecret)。
  2. 参照接口文档中即时通信IM-工作通知部分的文档进行调用。

工作通知源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import requests

def getAccessToken(AppKey,AppSecret):
url = r'https://oapi.dingtalk.com/gettoken?appkey={}&appsecret={}'.format(AppKey,AppSecret)
response = requests.get(url)
return response.json().get('access_token')
def sendMsg(access_token,json):
url = r'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={}'.format(access_token)
response = requests.post(url,data=json)
return response.json()
def recallMsg(access_token,task_id,agent_id):
url = r'https://oapi.dingtalk.com/topapi/message/corpconversation/recall?access_token={}'.format(access_token)
msg = {
"msg_task_id":task_id,
"agent_id":agent_id
}
responce = requests.post(url,msg)
return responce.json()

if __name__ == "__main__":
agent_id = '复制的AgentId'
AppKey = '复制的AppKey'
AppSecret = '复制的AppSecret'
access_token = getAccessToken(AppKey = AppKey,AppSecret= AppSecret)
msg = '''{
"msg":{
"text":{
"content":"我是数字员工。高效办公、事项提醒、消息通知一网打尽。"
},

"markdown":{
"text":"我是数字员工\n + 高效办公\n+ 事项提醒\n + 消息通知 \n\n如有需要可联系金融科技部 ",
"title":"提醒"
},

"action_card":{
"btn_json_list":{
"action_url":"http://www.baidu.com",
"title":"title2"
},
"single_url":"https://www.toutiao.com/article/7249711322559185448/?log_from=0a46e2448d138_1688028529113",
"btn_orientation":"0",
"single_title":"海上风电机组成功吊装",
"markdown":"今日热点",
"title":"测试"
},
"link":{
"picUrl":"https://img1.imgtp.com/2023/06/29/1cZT9PvV.jpg",
"messageUrl":"http://www.baidu.com",
"text":"万众一心,破浪而行",
"title":"端午安康"
},
"voice":{
"duration":"100",
"media_id":"100"
},
"image":{
"media_id":"@123"
},
"file":{
"media_id":"media_id"
},
"oa":{
"head":{
"bgcolor":"bgcolor",
"text":"text"
},
"pc_message_url":"http://www.baidu.com",
"status_bar":{
"status_value":"进行中",
"status_bg":"0xFFF65E5E"
},
"body":{
"file_count":"2",
"image":"https://img1.imgtp.com/2023/06/29/1cZT9PvV.jpg",
"form":[{
"value":"小智",
"key":"姓名:"
},{
"value":"1",
"key":"年龄:"
},{
"value":"RPA、人工智能",
"key":"能力:"
}],
"author":"陈迪",
"rich":{
"unit":"大领域能力",
"num":"5"
},
"title":"简介",
"content":""
},
"message_url":"message_url"
},

"msgtype":"markdown"
},
"to_all_user":"false",
"agent_id":"复制的AgentId",
"userid_list":"683"
}
'''
# 发送消息
result = sendMsg(access_token,msg.encode('utf-8'))
# # 撤回消息
# result = recallMsg(access_token,'2902475260697',agent_id)
print(result)

商业转载请联系作者获得授权,非商业转载请注明出处。

支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

Python|钉钉消息通知对接
http://hncd1024.github.io/2023/06/29/Python_dingtalk/
作者
CHEN DI
发布于
2023-06-29
许可协议