2025年3月24日 星期一 甲辰(龙)年 月廿三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python:使用钉钉dingtalk发送通知消息

时间:05-24来源:作者:点击数:24

通过钉钉的开放API接口,可以很容易的将消息发送到钉钉dingtalk,比起邮件发送更稳定,及时

文档

方式一: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

使用场景:发送通知类的消息

前期准备:需要准备以下参数

  1. 钉钉开放平台 创建企业内部应用/钉钉应用,获取应用凭证(AgentId、AppKey、AppSecret)
  2. 钉钉管理后台 通讯录/成员管理,获取员工的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": "你好,钉钉"
  • },
  • },
  • })
在这里插入图片描述
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门