通过钉钉的开放API接口,可以很容易的将消息发送到钉钉dingtalk,比起邮件发送更稳定,及时
文档
文档: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
使用场景:发送通知类的消息
前期准备:需要准备以下参数
示例代码
- # -*- 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": "你好,钉钉"
- },
- },
- })
-
-