Python实现钉钉群消息推送

Python实现钉钉群消息推送


对于某些自动化任务执行结果反馈,使用钉钉机器人消息替换繁琐的邮件发送方式使用钉钉机器人API,可以将任何你需要的服务消息推送到钉钉

参考文档:
钉钉机器人API接口文档
python代码

创建基本步骤

  • Step1: 新建钉钉群
  • Step2: 群设置>智能群助手>添加机器人
  • Step3: 自定义机器人
  • Step4: 复制token(token每个机器人具有唯一性【不可外传】)
  • Step5:3种安全设置方式:(1)关键词:所发送的消息必须含有这个关键词;(2)ip地址段:设置可以发送消息的有效ip地址段;(3)加签:使用HmacSHA256算法计算签名。
  • 编写python代码
import requests
import json
def send_dingding(access_token,update, is_at=False):
    # access_token = "xx" # access_token 每个群都不一样
    url = f"""https://oapi.dingtalk.com/robot/send?access_token={access_token }"""
    # 构建请求头部
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    yes_day = '2020-08-14'
    reason = 'tmall_goods 未更新'

    if (update == 1) or (update == 0):
        update_sta = '成功'
        text_succed = f""" ## <font color="#4590a3" size="4px">【{update_sta}】</font> 淘宝商品上架时间更新 \n> 表:spider_analysis_ads.tmall_goods_launchdate\n> ##### 更新日期:{yes_day} \n"""
        mark_text1 = text_succed
    else:
        update_sta = '失败'
        text_failed = f""" ## <font color="#DC143C" size="4px">【{update_sta}】</font> 淘宝商品上架时间更新 \n> 表:spider_analysis_ads.tmall_goods_launchdate\n> ### 失败原因:{reason} \n> ##### 更新日期:{yes_day}  @15927118920 \n"""
        mark_text1 = text_failed
    msg = {
     "msgtype": "markdown",
     "markdown": {
         "title":"数据更新",
         "text": mark_text1
     }
 }
    if is_at:
        msg['at'] = {
            "atMobiles": [
                "15927118920", # mobile
            ],
            "isAtAll": False
        }
    # 对请求的数据进行json封装
    message_json = json.dumps(msg)
    try:
        res = requests.post(url=url, data=message_json, headers=header).json()
    except Exception as e:
        print(e)
    if res["errcode"] == 0:
        print("发送钉钉成功!")
    else:
        print("发送钉钉成功!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值