Through DingTalk's open API interface, you can easily send messages to DingTalk, which is more stable and timely than sending emails
document
- Official website: https://www.dingtalk.com/
- API Explorer debugging https://open-dev.dingtalk.com/apiExplorer
Table of contents
Method 1: webhook method
Documentation: https://open.dingtalk.com/document/robots/custom-robot-access
Usage scenario: send a message to a chat group
Preliminary preparation: you need to create a new group chat and add a robot to the group chat
# -*- coding: utf-8 -*-
"""
@File : demo.py
@Date : 2023-06-22
"""
import requests
url = 'https://oapi.dingtalk.com/robot/send?access_token=xxx'
data = {
"msgtype": "text",
"text": {
"content": "监控报警: 服务异常"
}
}
res = requests.post(url, json=data)
Method 2: Send work notification
Documentation: https://open.dingtalk.com/document/orgapp/asynchronous-sending-of-enterprise-session-messages
Usage scenario: sending notification messages
Preliminary preparation: the following parameters need to be prepared
- DingTalk Open Platform Create enterprise internal applications/DingTalk applications and obtain application credentials (AgentId, AppKey, AppSecret)
- DingTalk management background address book/member management, get employee's UserID
sample code
# -*- coding: utf-8 -*-
"""
@File : dingtalk_api.py
@Date : 2023-03-08
"""
import requests
def get_access_token(appkey, appsecret):
"""
获取access_token
https://open.dingtalk.com/document/orgapp/obtain-orgapp-token
:param appkey: 应用的唯一标识key
:param appsecret: 应用的密钥
:return:
{
"errcode": 0,
"access_token": "96fc7a7axxx",
"errmsg": "ok",
"expires_in": 7200
}
"""
url = 'https://oapi.dingtalk.com/gettoken'
params = {
'appkey': appkey,
'appsecret': appsecret
}
res = requests.get(url, params=params)
return res.json()
def send_message(access_token, body):
"""
发送应用消息
https://open.dingtalk.com/document/orgapp/asynchronous-sending-of-enterprise-session-messages
:param access_token:
:param body: 消息体
:return:
{
"errcode":0,
"task_id":256271667526,
"request_id":"4jzllmte0wau"
}
"""
url = 'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2'
params = {
'access_token': access_token,
}
res = requests.post(url, params=params, json=body)
return res.json()
if __name__ == '__main__':
# 应用的唯一标识key
appkey = ''
# 应用的密钥
appsecret = ''
# 发送消息时使用的微应用的AgentID
agent_id = ''
# 接收者的userid列表
userid_list = ''
token = get_access_token(appkey, appsecret)
ret = send_message(token['access_token'], {
"agent_id": agent_id,
"userid_list": userid_list,
"msg": {
"msgtype": "text",
"text": {
"content": "你好,钉钉"
},
},
})