refactor(oa&dingtalk): 重构审批推送逻辑,改用块格式Markdown并支持分批推送
1. 统一请假、加班审批的推送实现,新增`_format_leave_block`/`_format_overtime_block`格式化审批详情为标准Markdown块 2. 重构`build_push_summary`生成分组推送数据,不再拆分单条消息,直接返回带标题和块列表的分组结构 3. 升级钉钉机器人推送模块,支持块格式分组自动分批推送,兼容原有纯文本推送逻辑 4. 临时关闭自动审批开关`APPROVE_ENABLED`,适配影刀运行环境 5. 重构影刀端钉钉推送指令入口,支持传入块格式分组数据并自动处理分批
This commit is contained in:
+139
-18
@@ -31,6 +31,7 @@ import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
@@ -121,30 +122,70 @@ class DingTalkRobot:
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,多行内容用 ```text 代码块包裹,带页脚)。
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。
|
||||
|
||||
内容整体放入 ```text 代码块,钉钉按纯文本渲染、不再做 Markdown 解析:
|
||||
- 不再逐行转引用块,避免空行被丢弃导致多段落合并成一个段落;
|
||||
- 报告里的 '====' 分隔线若被当作标题下划线(setext 语法),会让该行之前的
|
||||
全部内容渲染成超大加粗标题;代码块内按字面显示,彻底规避。
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(Markdown,引用块/加粗/超链接/列表等语法会被钉钉渲染)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
server_name: 页脚署名
|
||||
"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n内容详情:\n"
|
||||
text += "```text\n"
|
||||
text += content.strip() + "\n"
|
||||
text += "```\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}"
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。
|
||||
|
||||
当钉钉消息内容超过 max_chars 字符时,自动按行拆成多批发送,
|
||||
每批带「第 N/M 批」标题前缀,便于接收方识别。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(长文本)
|
||||
status: info|success|warning|error,决定标题颜色
|
||||
server_name: 页脚署名
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000)
|
||||
"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1 # +1 for newline
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
print(f"[INFO] 分批推送 {i}/{total}: {batch_title}")
|
||||
self.send(batch_title, batch_content, status=status,
|
||||
server_name=server_name)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='', env='prod'):
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉群机器人推送」调用入口。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
@@ -152,7 +193,17 @@ def main(text, title='消息通知', status='info', webhook='', secret='', serve
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
支持逐条推送多条:text 传「文本列表」时按顺序逐条发送,列表项可为纯文本,
|
||||
也可为字典 {text, title?, status?} 自定义该条标题与颜色(缺省用 main 的 title/status)。
|
||||
也可为字典 {text, title?, status?, batch?} 自定义该条标题、颜色与格式。
|
||||
消息正文一律按 Markdown 渲染(引用块/加粗/超链接/列表等语法直接生效)。
|
||||
|
||||
块格式分组(推荐,调用方不关心分批):
|
||||
text 传字典列表,每项形如 {title, blocks, status?, batch_size?},
|
||||
blocks 为每条记录格式化好的 block 字符串列表。模块自动按 batch_size
|
||||
(默认 10)分批、每批带「第N/M批」标题并逐条推送。示例:
|
||||
main([
|
||||
{"title": "【请假审批】通过",
|
||||
"blocks": ["**🔹 张三‑特殊事假**\n> 工号:...", "..."]},
|
||||
])
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
@@ -161,6 +212,11 @@ def main(text, title='消息通知', status='info', webhook='', secret='', serve
|
||||
secret: 加签密钥(缺省按 env 选择;显式传入则优先)
|
||||
server_name: 页脚署名(缺省按 env 选择;显式传入则优先)
|
||||
env: 环境 prod|dev,决定缺省 webhook/secret/server_name(默认 prod)
|
||||
batch: 是否启用分批发送(默认 False)。
|
||||
True: 当内容超长时自动按行拆成多批发送,每批标题带「第N/M批」;
|
||||
False: 单条发送(内容超长可能被钉钉截断或报错)。
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000),
|
||||
仅在 batch=True 时生效。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
@@ -183,15 +239,33 @@ def main(text, title='消息通知', status='info', webhook='', secret='', serve
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
# 块格式分组:调用方只传格式化好的 block 列表 + 标题,
|
||||
# 分批、加批次标题、逐条推送全部由本模块负责(调用方不关心批次)
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st,
|
||||
server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st = item, title, status
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
@@ -203,7 +277,54 @@ def main(text, title='消息通知', status='info', webhook='', secret='', serve
|
||||
return {'success': False, 'message': str(e)}
|
||||
|
||||
|
||||
# ==================== 块格式工具:调用方把每条记录格式化为 block 字符串列表,
|
||||
# 这里统一负责分批、加头尾、生成最终待推送的消息文本列表 ====================
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 字符串列表按 batch_size 条一批,生成带批次标题的消息文本列表。
|
||||
|
||||
Args:
|
||||
blocks: 每条记录格式化后的 block 字符串列表(调用方负责格式化业务字段)
|
||||
title_prefix: 批次标题前缀,如 "【请假审批】通过"
|
||||
batch_size: 每批最大条数(默认 10)
|
||||
|
||||
Returns:
|
||||
字符串列表,每项是一条完整的待推送 Markdown 文本,可直接传给 main(text=...)
|
||||
配合 batch=True 发送。
|
||||
"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
# 钉钉中引用块尾行后需空行(双换行)再进入新标题,否则会紧贴渲染
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
if __name__ == '__main__':
|
||||
text = ['测试消息:钉钉机器人连接正常。', '测试消息:钉钉机器人连接正常。']
|
||||
notice_type='dev'
|
||||
print(main(text, env=notice_type))
|
||||
# ==================== 本地自测/演示入口 ====================
|
||||
# 影刀中本模块作为「37du钉钉群机器人推送」指令源码,由流程传 text 参数调用 main();
|
||||
# 此处 __main__ 仅用于本地命令行自测:演示块格式分组用法(调用方只传 {title, blocks},
|
||||
# 分批/推送由模块内部负责)。注意:demo 数据为占位示例,勿用于生产;
|
||||
# env='dev' 走测试环境机器人,避免误发生产群。
|
||||
texts = [
|
||||
{
|
||||
"title": "【请假审批】通过",
|
||||
"blocks": [
|
||||
"**🔹 示例员工‑特殊事假**\n\n"
|
||||
"> 工号:00000000\n\n"
|
||||
"> 所属部门:示例部门\n\n"
|
||||
"> 开始日期:2026-08-19|开始段:上半段\n\n"
|
||||
"> 结束日期:2026-08-19|结束段:下半段\n\n"
|
||||
"> 请假天数:1.0\n\n"
|
||||
"> 实际上班天数:1\n\n"
|
||||
"> 填报天数:1.0\n\n",
|
||||
],
|
||||
},
|
||||
]
|
||||
notice_type = 'dev'
|
||||
print(main(texts, env=notice_type))
|
||||
Reference in New Issue
Block a user