通过钉钉的开放API接口,可以很容易的将消息发送到钉钉dingtalk,比起邮件发送更稳定,及时
文档
- 官网:https://www.dingtalk.com/
- API Explorer调试 https://open-dev.dingtalk.com/apiExplorer
目录
- 方式一:webhook方式
- 方式二:发送工作通知
方式一:webhook方式
文档:https://open.dingtalk.com/document/robots/custom-robot-access
使用场景:发送消息到聊天群
前期准备:需要新建一个群聊,在群聊中添加机器人
# -*- 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)
方式二:发送工作通知
文档:https://open.dingtalk.com/document/orgapp/asynchronous-sending-of-enterprise-session-messages
使用场景:发送通知类的消息
前期准备:需要准备以下参数
- 钉钉开放平台 创建企业内部应用/钉钉应用,获取应用凭证(AgentId、AppKey、AppSecret)
- 钉钉管理后台 通讯录/成员管理,获取员工的UserID
示例代码
# -*- 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": "你好,钉钉"
},
},
})