feat: 多业务模块迭代优化
1. 修复雇主险导入监听逻辑,适配HR端流程变更,补全分页拉取逻辑 2. 为雇主险增员导入添加厂区后缀适配HR侧方案列表 3. 优化电子签审批消息格式适配钉钉markdown渲染 4. 新增请假异常名单钉钉群推送功能 5. 重构银行卡检查脚本,复用共享登录态并优化推送流程 6. 扩展钉钉推送共享模块支持群聊推送
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_dws_push.py
|
||||
@Description: 钉钉单聊推送共享模块(文本 / 文件,基于 dws 命令行)。
|
||||
供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉单聊推送」的模块源码。
|
||||
@Description: 钉钉推送共享模块(单聊 + 群聊,文本 / 文件,基于 dws 命令行)。
|
||||
供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉单聊推送」
|
||||
/「37du钉钉群聊推送」的模块源码。
|
||||
|
||||
入口:
|
||||
main(messages, record_dir='') 影刀自定义指令「37du钉钉单聊推送」调用入口。
|
||||
main(messages, record_dir='') 影刀自定义指令「37du钉钉单聊推送」调用入口。
|
||||
传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址):
|
||||
msg_type 消息类型:'text'/'文本' 或 'file'/'文件'
|
||||
name 接收人姓名(文本/文件均按姓名解析 openDingTalkId;同名多人时按工号精确定位)
|
||||
@@ -16,9 +17,19 @@
|
||||
并把记录文件路径写入影刀全局变量 push_record_path,供流程处理失败名单。
|
||||
返回: {"success": bool, "message": str, "results": [...]}
|
||||
|
||||
send_message(msg_type, name, user_id, content, file_path, record_dir='') # 单条发送(内部/业务脚本复用)
|
||||
main_group(messages, record_dir='') 影刀自定义指令「37du钉钉群聊推送」调用入口。
|
||||
传入消息列表,每项支持 dict 或元组:
|
||||
dict: {"group": 群名, "content": 文本, "file_path": 文件,
|
||||
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
|
||||
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略
|
||||
按群名解析 openconversation_id 后发送(文本/文件可同时存在,@ 需在内容中含占位符)。
|
||||
返回: {"success": bool, "message": str, "results": [...]}
|
||||
|
||||
send_message(msg_type, name, user_id, content, file_path, record_dir='') # 单聊单条发送(内部/业务脚本复用)
|
||||
send_group_message(group_name, content, file_path, title, at_all, at_open_ids, record_dir='') # 群聊单条发送
|
||||
|
||||
推送原理(DWS CLI,零第三方 Python 依赖,仅标准库):
|
||||
单聊:
|
||||
- 文本:按姓名解析 openDingTalkId 后 dws chat message send --open-dingtalk-id <openId> --content <内容>
|
||||
(dws 的 --user 只认钉钉 org userId,与工号不同,故文本/文件统一走 --open-dingtalk-id;
|
||||
内容按钉钉 markdown 渲染:单行换行用 <br>,空行用 <br><br>;单聊会话由首条消息自动创建,
|
||||
@@ -26,6 +37,13 @@
|
||||
- 文件:按姓名查 openDingTalkId → 取单聊会话共享空间 ID → 上传文件到钉盘
|
||||
→ 按 dentry 信息发文件消息;对方未建立会话(11056)时自动先发一条
|
||||
文本建立会话再发文件。
|
||||
群聊:
|
||||
- 按群名 dws chat search --query <群名> 解析 openconversation_id(模糊搜索→精确同名过滤→歧义报错);
|
||||
- 文本:dws chat message send --conversation-id <openconversation_id> --content <内容>
|
||||
(支持 --title 标题、--at-all @所有人、--at-open-dingtalk-ids @指定成员;
|
||||
@ 场景内容里需包含占位符 <@all> / <@openDingTalkId>)
|
||||
- 文件:dws chat message send --conversation-id <id> --msg-type file --file <本地路径>
|
||||
(CLI 自动完成上传并按 file 消息发送,无需像单聊那样手动取会话空间)。
|
||||
|
||||
防风控限流:
|
||||
每次实际发送前经滑动窗口限流(默认 50 条/分钟,见 _RATE_LIMIT),
|
||||
@@ -351,6 +369,157 @@ def send_file(open_id: str, file_path: str):
|
||||
print(f"[INFO] 文件已发送: {os.path.basename(file_path)}")
|
||||
|
||||
|
||||
# ==================== 群聊推送 ====================
|
||||
def search_group(query: str, limit: int = 20) -> list:
|
||||
"""按群名搜索群聊(关键词模糊搜索),返回候选列表。
|
||||
注意:dws 要求 query 使用群名连续核心词(如「项目冲刺」),勿拆成单字搜索。
|
||||
"""
|
||||
data = _run_dws([DWS_BIN, "chat", "search", "--query", query,
|
||||
"--limit", str(limit), "--format", "json"])
|
||||
return data.get("result") or []
|
||||
|
||||
|
||||
def _group_conv_id(group: dict) -> str:
|
||||
"""从群搜索结果条目中提取 openconversation_id(兼容多个候选字段名)。"""
|
||||
for key in ("openConversationId", "conversationId", "chatId", "id"):
|
||||
val = (group or {}).get(key)
|
||||
if val:
|
||||
return str(val)
|
||||
return ""
|
||||
|
||||
|
||||
def resolve_group_id(group_name: str) -> str:
|
||||
"""按群名解析群聊 openconversation_id。
|
||||
先模糊搜索候选,再按精确同名过滤;唯一命中即返回,多候选/无候选则报错带候选清单,
|
||||
绝不自行假定第一个(与 resolve_open_id 的同名歧义处理一致)。
|
||||
"""
|
||||
group_name = str(group_name or "").strip()
|
||||
groups = search_group(group_name)
|
||||
if not groups:
|
||||
raise RuntimeError(f"未找到群「{group_name}」,请确认群名后重试")
|
||||
exact = [g for g in groups if (g.get("name") or "").strip() == group_name]
|
||||
if exact:
|
||||
groups = exact
|
||||
candidates = [g for g in groups if _group_conv_id(g)]
|
||||
if len(candidates) == 1:
|
||||
g = candidates[0]
|
||||
print(f"[INFO] 命中群: {g.get('name')} | openConversationId={_group_conv_id(g)}")
|
||||
return _group_conv_id(g)
|
||||
if not candidates:
|
||||
raise RuntimeError(
|
||||
f"群「{group_name}」搜索结果均无 openconversation_id,原始数据:{groups}")
|
||||
hints = "\n".join(
|
||||
f" {g.get('name') or '未知群名'} | {_group_conv_id(g)}" for g in candidates
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"群名「{group_name}」匹配到 {len(candidates)} 个候选,请使用更精确的群名:\n{hints}"
|
||||
)
|
||||
|
||||
|
||||
def send_group_text(conversation_id: str, text: str, title: str = "",
|
||||
at_all: bool = False, at_open_ids: str = ""):
|
||||
"""向群聊发送文本(纯文本 / Markdown,单行换行用 <br>)。
|
||||
at_all=True 或传 at_open_ids 时,消息内容需包含对应占位符 <@all> / <@openDingTalkId>。
|
||||
"""
|
||||
cmd = [DWS_BIN, "chat", "message", "send",
|
||||
"--conversation-id", conversation_id, "--content", str(text)]
|
||||
if title:
|
||||
cmd += ["--title", str(title)]
|
||||
if at_all:
|
||||
cmd += ["--at-all"]
|
||||
if at_open_ids:
|
||||
cmd += ["--at-open-dingtalk-ids", str(at_open_ids)]
|
||||
cmd += ["--format", "json"]
|
||||
_rate_limit_wait() # 限流:每次实际发送占用一个名额
|
||||
_run_dws(cmd)
|
||||
print(f"[INFO] 群文本已发送: {text}")
|
||||
|
||||
|
||||
def send_group_file(conversation_id: str, file_path: str):
|
||||
"""向群聊发送本地文件(dws CLI 自动上传并按 file 消息发送,无需手动取会话空间)。"""
|
||||
_rate_limit_wait() # 限流:文件消息占用一个名额
|
||||
_run_dws([DWS_BIN, "chat", "message", "send",
|
||||
"--conversation-id", conversation_id,
|
||||
"--msg-type", "file", "--file", str(file_path), "--format", "json"])
|
||||
print(f"[INFO] 群文件已发送: {os.path.basename(file_path)}")
|
||||
|
||||
|
||||
def send_group_message(group_name, content="", file_path="", title="",
|
||||
at_all=False, at_open_ids="", record_dir=""):
|
||||
"""向群聊推送文本/文件(按群名解析 openconversation_id 后发送)。
|
||||
|
||||
Args:
|
||||
group_name: 群名(模糊搜索 → 精确同名过滤;歧义报错)
|
||||
content: 文本内容(发文本时必填;@ 场景需含 <@all> / <@openDingTalkId> 占位符)
|
||||
file_path: 本地文件地址(非空时发送文件;文本与文件可同时存在)
|
||||
title: 消息标题(可选,显示在消息列表)
|
||||
at_all: 是否 @所有人(仅群聊生效)
|
||||
at_open_ids: 逗号分隔的 openDingTalkId 列表(仅群聊生效)
|
||||
record_dir: 非空时写入 <record_dir>/YYYY-MM-DD/推送记录.csv
|
||||
|
||||
Returns:
|
||||
{"success": bool, "message": str}
|
||||
"""
|
||||
name = str(group_name or "").strip()
|
||||
try:
|
||||
if not name:
|
||||
return _record_and_return({"success": False, "message": "群名不能为空"},
|
||||
record_dir, "", name, content, file_path)
|
||||
if not content and not file_path:
|
||||
return _record_and_return({"success": False, "message": "文本内容与文件地址至少传一个"},
|
||||
record_dir, "", name, content, file_path)
|
||||
conv_id = resolve_group_id(name)
|
||||
print(f"[INFO] 目标群 openConversationId: {conv_id}")
|
||||
if file_path:
|
||||
file_path = str(file_path or "").strip()
|
||||
if not os.path.exists(file_path):
|
||||
return _record_and_return({"success": False, "message": f"文件不存在: {file_path}"},
|
||||
record_dir, "", name, content, file_path)
|
||||
send_group_file(conv_id, file_path)
|
||||
if content:
|
||||
send_group_text(conv_id, content, title=title, at_all=at_all, at_open_ids=at_open_ids)
|
||||
return _record_and_return({"success": True, "message": f"已向群「{name}」推送"},
|
||||
record_dir, "", name, content, file_path)
|
||||
except Exception as e:
|
||||
return _record_and_return({"success": False, "message": str(e)},
|
||||
record_dir, "", name, content, file_path)
|
||||
|
||||
|
||||
def main_group(messages, record_dir=""):
|
||||
"""影刀自定义指令「37du钉钉群聊推送」调用入口。
|
||||
传入消息列表,每项支持 dict 或元组:
|
||||
dict: {"group": 群名, "content": 文本, "file_path": 文件,
|
||||
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
|
||||
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略。
|
||||
逐条发送,返回: {"success": bool, "message": str, "results": [...]}
|
||||
"""
|
||||
results = []
|
||||
for item in messages or []:
|
||||
if isinstance(item, dict):
|
||||
group = item.get("group") or item.get("群名") or ""
|
||||
content = item.get("content") or item.get("文本内容") or ""
|
||||
file_path = item.get("file_path") or item.get("文件地址") or ""
|
||||
title = item.get("title") or item.get("标题") or ""
|
||||
at_all = bool(item.get("at_all") or item.get("@所有人"))
|
||||
at_open_ids = item.get("at_open_ids") or item.get("@成员") or ""
|
||||
else:
|
||||
group = item[0] if len(item) > 0 else ""
|
||||
content = item[1] if len(item) > 1 else ""
|
||||
file_path = item[2] if len(item) > 2 else ""
|
||||
title = item[3] if len(item) > 3 else ""
|
||||
at_all = bool(item[4]) if len(item) > 4 else False
|
||||
at_open_ids = item[5] if len(item) > 5 else ""
|
||||
results.append(send_group_message(group, content, file_path, title,
|
||||
at_all, at_open_ids, record_dir))
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
_write_record_path_to_glv(record_dir)
|
||||
return {
|
||||
"success": ok == len(results),
|
||||
"message": f"共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}",
|
||||
"results": results,
|
||||
}
|
||||
|
||||
|
||||
# ==================== 统一入口 ====================
|
||||
def send_message(msg_type, name, user_id, content, file_path="", record_dir=""):
|
||||
"""单条推送:按消息类型分发文本 / 文件。
|
||||
@@ -437,6 +606,8 @@ if __name__ == "__main__":
|
||||
# 本地自测/接口说明:不实际发送。业务脚本请 import 后调用
|
||||
# main([("文本", "姓名", "工号", "消息内容", ""),
|
||||
# ("文件", "姓名", "工号", "", r"文件绝对路径")])
|
||||
# main_group([{"group": "群名", "content": "消息内容"},
|
||||
# {"group": "群名", "content": "", "file_path": r"文件绝对路径"}])
|
||||
messages = [
|
||||
{"msg_type": "text", "name": "夏一平", "user_id": "37036361", "content": "你好,这是由ai推送的文本消息"},
|
||||
# {"msg_type": "file", "name": "夏一平", "user_id": "37036361", "file_path": r"C:\Users\admin\Desktop\test.xlsx"},
|
||||
|
||||
Reference in New Issue
Block a user