Files
37duAutomation/yingdao/share/dingtalk_robot.py
T
puddy 60a177605a refactor: 重构雇主险业务,适配多类别拆分与影刀脚本整合
1.  重构ehr/common/config.py与employer_insurance/config.py,新增多类别配置与工具函数
2.  重写employer_insurance.py,支持按类别调度处理
3.  新增影刀共享模块与业务脚本,统一RPA开发规范
4.  移除旧版冗余的影刀脚本文件
2026-08-19 11:30:23 +08:00

162 lines
7.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@FileName: dingtalk_robot.py
@Description: 钉钉群机器人推送(影刀自定义指令模块源码,单一真源)。
使用方式:main("需要推送的通知文本") 即可,标题/颜色等均可选。
如何在影刀中创建指令:
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_robot,添加 Python 模块;
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
3. 增加一个流程参数(文本类型,如 text),并勾选「参数可见」;
4. 保存并「发版」;在需要钉钉群推送的应用中「获取指令」并安装;
5. 流程中拖入该指令,把业务脚本输出的文本直接传给 text 参数即可。
推送原理(HTTP Webhook,零第三方依赖,仅标准库):
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
约定:
- 影刀运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
「默认配置」区(单一真源),改推送目标时改常量即可;
- 页脚署名默认 "小芒 任务调度平台":
注意:钉钉机器人若配置了"自定义关键词"安全校验,
页脚署名需包含该关键词(如 小芒)才会被接受。
入口:
main(text, title='消息通知', status='info', webhook='', secret='', server_name='')
第一个参数传通知文本即可,其余可选。
返回: {"success": bool, "message": str}
"""
import base64
import hashlib
import hmac
import json
import time
import urllib.parse
import urllib.request
from datetime import datetime
# ==================== 默认配置(改推送目标改这里) ====================
DEFAULT_WEBHOOK = (
'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
)
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
DEFAULT_SERVER_NAME = '小芒 任务调度平台'
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
# 通知状态 → 标题颜色
_STATUS_COLORS = {
'info': '#0077ff', # 蓝色
'success': '#00b300', # 绿色
'warning': '#ff9900', # 橙色
'error': '#ff0000', # 红色
}
def _build_sign(secret, timestamp_ms):
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
string_to_sign = f"{timestamp_ms}\n{secret}"
hmac_code = hmac.new(
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
).digest()
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
def _build_url(webhook, secret=''):
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
if not secret:
return webhook
ts = int(round(time.time() * 1000))
separator = '&' if '?' in webhook else '?'
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
class DingTalkRobot:
"""钉钉群机器人推送器。"""
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
self.secret = (secret or DEFAULT_SECRET).strip()
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
self.timeout = timeout
if not self.webhook:
raise ValueError('webhook 不能为空')
def _post(self, payload):
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
last_err = None
for attempt in range(DEFAULT_RETRY_TIMES):
try:
url = _build_url(self.webhook, self.secret)
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
req = urllib.request.Request(
url,
data=data,
headers={'Content-Type': 'application/json; charset=utf-8'},
)
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
body = resp.read().decode('utf-8')
resp_data = json.loads(body)
if resp_data.get('errcode') != 0:
raise RuntimeError(
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
f"errmsg={resp_data.get('errmsg')}"
)
return
except Exception as e:
last_err = e
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
time.sleep(1)
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
def send(self, title, content, status='info', server_name=''):
"""发送统一通知(Markdown:标题按状态着色,多行内容转引用块,带页脚)。"""
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
text = f"**<font color='{color}'>{title}</font>**\n\n内容详情:\n"
for line in content.strip().splitlines():
line = line.strip()
if line:
# 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示
text += f"> {line} \n"
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
display_name = (server_name or self.server_name).strip()
text += f"\n\n---\n\n###### {display_name} | {now}"
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
self._post(payload)
# ==================== 影刀自定义指令入口 ====================
def main(text, title='消息通知', status='info', webhook='', secret='', server_name=''):
"""
影刀自定义指令「37du钉钉群机器人推送」调用入口。
只需把要推送的通知文本传进来即可,例如:
main("订单同步失败,错误原因:接口超时")
可选参数:
title: 消息标题(默认 消息通知)
status: info|success|warning|error,决定标题颜色(默认 info)
webhook: 机器人 webhook(缺省用内联默认值)
secret: 加签密钥(缺省用内联默认值)
server_name: 页脚署名(缺省用内联默认值)
返回: {"success": bool, "message": str}
"""
try:
if not text or not str(text).strip():
return {'success': False, 'message': '通知文本不能为空'}
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
robot.send(str(title), str(text), status=status, server_name=server_name)
return {'success': True, 'message': f'已推送通知 [{status}]:{title}'}
except Exception as e:
return {'success': False, 'message': str(e)}
if __name__ == '__main__':
text = '测试消息:钉钉机器人连接正常。'
print(main(text))