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("发送钉钉成功!")