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:
@@ -92,6 +92,14 @@ DEFAULT_PAGE_SIZE = 100
|
||||
PAGE_MAX_SIZE = 500 # 排班查询单页最大条数
|
||||
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||||
APPROVE_ENABLED = False
|
||||
# 审批按钮:仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
|
||||
@@ -1095,25 +1103,77 @@ def show_rpa_result_popup(page: ChromiumPage,
|
||||
|
||||
|
||||
def _build_push_messages(texts, push_type="group", target=None):
|
||||
"""把文本列表转成推送消息列表(字典列表)。
|
||||
"""把推送内容列表转成推送消息列表(字典列表)。
|
||||
|
||||
push_type 推送类型:"group" 群消息(仅 text,钉钉群机器人 webhook 推送);
|
||||
texts 项可为:
|
||||
- 纯文本:包成 {"text": ...}(单条消息)
|
||||
- 块格式分组 dict(含 blocks):原样保留,交由钉钉机器人模块内部分批推送
|
||||
push_type 推送类型:"group" 群消息(钉钉群机器人 webhook 推送);
|
||||
"person" 单聊(含 target,钉钉联系人 OCR 推送)。
|
||||
"""
|
||||
messages = []
|
||||
for text in texts:
|
||||
msg = {"text": text}
|
||||
if isinstance(text, dict) and text.get("blocks") is not None:
|
||||
msg = dict(text)
|
||||
else:
|
||||
msg = {"text": text}
|
||||
if push_type == "person":
|
||||
msg["target"] = target
|
||||
messages.append(msg)
|
||||
return messages
|
||||
|
||||
|
||||
def _format_leave_block(r):
|
||||
"""将单条请假审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
name = info.get("请假人员") or r.get("creator") or "未知"
|
||||
vtype = info.get("假期类型") or ""
|
||||
lines = [f"**🔹 {name}‑{vtype}**"]
|
||||
label_map = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("所属部门", "所属部门"),
|
||||
("假期类型", "假期类型"),
|
||||
]
|
||||
for key, label in label_map:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
start = info.get("开始日期")
|
||||
start_seg = info.get("开始段")
|
||||
if start:
|
||||
if start_seg:
|
||||
lines.append(f"> 开始日期:{start}|开始段:{start_seg}")
|
||||
else:
|
||||
lines.append(f"> 开始日期:{start}")
|
||||
end = info.get("结束日期")
|
||||
end_seg = info.get("结束段")
|
||||
if end:
|
||||
if end_seg:
|
||||
lines.append(f"> 结束日期:{end}|结束段:{end_seg}")
|
||||
else:
|
||||
lines.append(f"> 结束日期:{end}")
|
||||
for key, label in [("请假天数", "请假天数"), ("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"), ("填报天数", "填报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:{url}")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""
|
||||
按结果类型生成多条推送消息文本(每条一类,含该类的单笔明细)。
|
||||
返回:字符串列表,每项是一条独立完整消息,供推送指令逐条发送
|
||||
(通过 / 校验不通过未处理 / 人工复核 / 处理失败 各一条)。无业务结果时返回空列表。
|
||||
按结果类型生成块格式 Markdown 推送分组。
|
||||
|
||||
返回:字典列表,每项 {"title": 分组标题, "blocks": [每条记录格式化后的 block 字符串]},
|
||||
分批/推送由「37du钉钉群机器人推送」指令内部完成(调用方不关心批次)。
|
||||
"""
|
||||
if not results:
|
||||
return []
|
||||
@@ -1125,55 +1185,23 @@ def build_push_summary(results, subject=""):
|
||||
if not passed and not rejected and not review and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
def _detail(r):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
name = info.get("请假人员") or r.get("title") or "未知"
|
||||
vtype = info.get("假期类型") or ""
|
||||
head = f"{name}-{vtype}" if vtype else name
|
||||
extra = _format_detail(info)
|
||||
return f"{head} {extra}" if extra else head
|
||||
|
||||
messages = []
|
||||
if passed:
|
||||
lines = [f"【{subject}审批】通过 {len(passed)} 条:"]
|
||||
lines += [f" {_detail(r)}" for r in passed]
|
||||
lines.append(f"以上 {len(passed)} 条{subject}申请已审批通过")
|
||||
messages.append("\n".join(lines))
|
||||
if rejected:
|
||||
lines = [f"【{subject}审批】校验不通过未处理 {len(rejected)} 条:"]
|
||||
for r in rejected:
|
||||
lines.append(f" {_detail(r)}")
|
||||
lines.append(f" 校验不通过原因:{r.get('note') or r.get('error') or '未知'}")
|
||||
messages.append("\n".join(lines))
|
||||
if review:
|
||||
lines = [f"【{subject}审批】需人工复核 {len(review)} 条:"]
|
||||
for r in review:
|
||||
lines.append(f" {_detail(r)}")
|
||||
lines.append(f" 详情页:{r.get('detail_url') or '无'}")
|
||||
messages.append("\n".join(lines))
|
||||
if abnormal:
|
||||
lines = [f"【{subject}审批】审批异常 {len(abnormal)} 条(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进):"]
|
||||
for r in abnormal:
|
||||
lines.append(f" {_detail(r)}")
|
||||
lines.append(f" 详情页:{r.get('detail_url') or '无'}")
|
||||
messages.append("\n".join(lines))
|
||||
if failed:
|
||||
lines = [f"【{subject}审批】处理失败 {len(failed)} 条:"]
|
||||
for r in failed:
|
||||
lines.append(f" {r.get('title') or '未知'}:{r.get('error') or '未知'}")
|
||||
messages.append("\n".join(lines))
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_leave_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
_push_group(f"【{subject}审批】通过", passed)
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||||
APPROVE_ENABLED = True
|
||||
# 审批按钮:仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
@@ -1737,12 +1765,10 @@ def main(push_type="group", target=None):
|
||||
push_type=push_type,
|
||||
target=target,
|
||||
)
|
||||
# 写入影刀全局变量 messages(列表,每项一条消息,按结果类型分组),
|
||||
# 供「37du钉钉群机器人推送」指令读取后逐条发送;本地独立运行时静默跳过
|
||||
_set_glv("messages", [
|
||||
str(m.get("text", "") or "").strip()
|
||||
for m in push_messages if str(m.get("text", "") or "").strip()
|
||||
])
|
||||
# 写入影刀全局变量 messages(块格式分组列表:{title, blocks}),
|
||||
# 供「37du钉钉群机器人推送」指令读取后整体传入 main(),由模块内部分批逐条发送;
|
||||
# 本地独立运行时静默跳过
|
||||
_set_glv("messages", [m for m in push_messages if str(m.get("text", "") or m.get("blocks", "") or "").strip()])
|
||||
return push_messages
|
||||
|
||||
|
||||
|
||||
@@ -112,6 +112,13 @@ OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||||
APPROVE_ENABLED = False
|
||||
# 审批按钮:仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
@@ -775,26 +782,69 @@ def show_rpa_result_popup(page: ChromiumPage,
|
||||
|
||||
|
||||
def _build_push_messages(texts, push_type="group", target=None):
|
||||
"""把文本列表转成推送消息列表(字典列表)。
|
||||
"""把推送内容列表转成推送消息列表(字典列表)。
|
||||
|
||||
push_type 推送类型:"group" 群消息(仅 text,钉钉群机器人 webhook 推送);
|
||||
texts 项可为:
|
||||
- 纯文本:包成 {"text": ...}(单条消息)
|
||||
- 块格式分组 dict(含 blocks):原样保留,交由钉钉机器人模块内部分批推送
|
||||
push_type 推送类型:"group" 群消息(钉钉群机器人 webhook 推送);
|
||||
"person" 单聊(含 target,钉钉联系人 OCR 推送)。
|
||||
"""
|
||||
messages = []
|
||||
for text in texts:
|
||||
msg = {"text": text}
|
||||
if isinstance(text, dict) and text.get("blocks") is not None:
|
||||
msg = dict(text)
|
||||
else:
|
||||
msg = {"text": text}
|
||||
if push_type == "person":
|
||||
msg["target"] = target
|
||||
messages.append(msg)
|
||||
return messages
|
||||
|
||||
|
||||
def _format_overtime_block(r):
|
||||
"""将单条加班审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
name = info.get("加班人员") or r.get("creator") or "未知"
|
||||
otype = info.get("加班类型") or ""
|
||||
lines = [f"**🔹 {name}‑{otype}**"]
|
||||
for key, label in [("加班人员", "加班人员"), ("所属部门", "所属部门"),
|
||||
("加班类型", "加班类型"), ("补贴类型", "补贴类型")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
date = info.get("加班日期")
|
||||
if date:
|
||||
lines.append(f"> 加班日期:{date}")
|
||||
start = info.get("加班开始时间")
|
||||
end = info.get("加班结束时间")
|
||||
if start or end:
|
||||
lines.append(f"> 加班时段:{start or ''} ~ {end or ''}")
|
||||
for key, label in [("加班时长(小时)", "加班时长"), ("加班天数(天)", "加班天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("申报天数(天)", "申报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:{url}")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""
|
||||
按结果类型生成多条推送消息文本(每条一类,含该类的单笔明细)。
|
||||
返回:字符串列表,每项是一条独立完整消息,供推送指令逐条发送
|
||||
(通过 / 校验不通过未处理 / 人工复核 / 超期待人资处理 / 处理失败 各一条)。
|
||||
无业务结果时返回空列表。
|
||||
按结果类型生成块格式 Markdown 推送分组。
|
||||
|
||||
返回:字典列表,每项 {"title": 分组标题, "blocks": [每条记录格式化后的 block 字符串]},
|
||||
分批/推送由「37du钉钉群机器人推送」指令内部完成(调用方不关心批次)。
|
||||
"""
|
||||
if not results:
|
||||
return []
|
||||
@@ -807,61 +857,23 @@ def build_push_summary(results, subject=""):
|
||||
if not passed and not rejected and not review and not overdue and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
def _detail(r):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
name = info.get("加班人员") or r.get("title") or "未知"
|
||||
vtype = info.get("加班类型") or ""
|
||||
head = f"{name}-{vtype}" if vtype else name
|
||||
extra = _format_detail(info)
|
||||
return f"{head} {extra}" if extra else head
|
||||
|
||||
messages = []
|
||||
if passed:
|
||||
lines = [f"【{subject}审批】通过 {len(passed)} 条:"]
|
||||
lines += [f" {_detail(r)}" for r in passed]
|
||||
lines.append(f"以上 {len(passed)} 条{subject}申请已审批通过")
|
||||
messages.append("\n".join(lines))
|
||||
if rejected:
|
||||
lines = [f"【{subject}审批】校验不通过未处理 {len(rejected)} 条:"]
|
||||
for r in rejected:
|
||||
lines.append(f" {_detail(r)}")
|
||||
lines.append(f" 校验不通过原因:{r.get('note') or r.get('error') or '未知'}")
|
||||
messages.append("\n".join(lines))
|
||||
if review:
|
||||
lines = [f"【{subject}审批】需人工复核 {len(review)} 条:"]
|
||||
for r in review:
|
||||
lines.append(f" {_detail(r)}")
|
||||
lines.append(f" 详情页:{r.get('detail_url') or '无'}")
|
||||
messages.append("\n".join(lines))
|
||||
if overdue:
|
||||
lines = [f"【{subject}审批】超期待人资处理 {len(overdue)} 条:"]
|
||||
for r in overdue:
|
||||
lines.append(f" {_detail(r)}")
|
||||
lines.append(f" 处理原因:{r.get('note') or r.get('error') or '未知'}")
|
||||
messages.append("\n".join(lines))
|
||||
if abnormal:
|
||||
lines = [f"【{subject}审批】审批异常 {len(abnormal)} 条(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进):"]
|
||||
for r in abnormal:
|
||||
lines.append(f" {_detail(r)}")
|
||||
lines.append(f" 详情页:{r.get('detail_url') or '无'}")
|
||||
messages.append("\n".join(lines))
|
||||
if failed:
|
||||
lines = [f"【{subject}审批】处理失败 {len(failed)} 条:"]
|
||||
for r in failed:
|
||||
lines.append(f" {r.get('title') or '未知'}:{r.get('error') or '未知'}")
|
||||
messages.append("\n".join(lines))
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_overtime_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
_push_group(f"【{subject}审批】通过", passed)
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】超期待人资处理", overdue)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||||
APPROVE_ENABLED = True
|
||||
# 审批按钮:仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
@@ -1739,12 +1751,10 @@ def main(push_type="group", target=None):
|
||||
push_type=push_type,
|
||||
target=target,
|
||||
)
|
||||
# 写入影刀全局变量 messages(列表,每项一条消息,按结果类型分组),
|
||||
# 供「37du钉钉群机器人推送」指令读取后逐条发送;本地独立运行时静默跳过
|
||||
_set_glv("messages", [
|
||||
str(m.get("text", "") or "").strip()
|
||||
for m in push_messages if str(m.get("text", "") or "").strip()
|
||||
])
|
||||
# 写入影刀全局变量 messages(块格式分组列表:{title, blocks}),
|
||||
# 供「37du钉钉群机器人推送」指令读取后整体传入 main(),由模块内部分批逐条发送;
|
||||
# 本地独立运行时静默跳过
|
||||
_set_glv("messages", [m for m in push_messages if str(m.get("text", "") or m.get("blocks", "") or "").strip()])
|
||||
return push_messages
|
||||
|
||||
|
||||
|
||||
+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