Files
puddy 2350ca671f feat: 新增多个业务需求脚本与共享模块
新增内容包括:
1. 7个业务需求占位文档目录与README
2. 共享OA登录、钉钉机器人推送工具模块
3. 雇主险变更清单导出脚本
4. 考勤月报封存检查两个检查脚本
5. 重庆社保停保导入名单生成脚本
2026-09-08 16:16:15 +08:00

640 lines
32 KiB
Python
Raw Permalink 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_dws_push.py
@Description: 钉钉推送共享模块(单聊 + 群聊,文本 / 文件,基于 dws 命令行)。
供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉推送」的模块源码
(同一入口,chat_type 参数决定单聊还是群聊)。
入口(统一 main,按消息结构自动识别单聊/群聊):
main(messages, record_dir='', chat_type='') 影刀自定义指令「37du钉钉推送」调用入口。
通道判定:chat_type 留空(默认)时按每条消息结构自动判断——dict 含 group/群名 键为群聊,
其余为单聊;显式传 'single'/'group' 时整批强制用该通道(兼容旧流程)。
chat_type='single'/单聊:传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址):
msg_type 消息类型:'text'/'文本' 或 'file'/'文件'
name 接收人姓名(文本/文件均按姓名解析 openDingTalkId;同名多人时按工号精确定位)
user_id 接收人工号(同名消歧;发文件且对方无会话时用于先建会话)
content 消息内容(msg_type=text 时必填)
file_path 文件地址(msg_type=file 时必填,本地绝对路径)
chat_type='group'/群聊:传入消息列表,每项支持 dict 或元组:
dict: {"group": 群名, "content": 文本, "file_path": 文件,
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略
按群名解析 openconversation_id 后发送(文本/文件可同时存在,@ 需在内容中含占位符)。
record_dir(可选):非空时每条结果写入 <record_dir>/YYYY-MM-DD/推送记录.csv,
并把记录文件路径写入影刀全局变量 push_record_path,供流程处理失败名单。
逐条发送,返回: {"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>;单聊会话由首条消息自动创建,
遇 11056 自动等待后重试一次,无需对方先聊过天)
- 文件:按姓名查 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),
窗口已满时自动等待、不丢消息;批量推送请合理控制总量。
依赖:dws.exe 命令行工具(路径见下方配置区 DWS_BIN)。
"""
import csv
import json
import os
import subprocess
import time
from datetime import datetime
# ==================== 配置区 ====================
DWS_BIN = r"C:\Users\admin\.local\bin\dws.exe" # dws 命令行工具路径
# ==================== 异常与工具 ====================
class DwsError(RuntimeError):
"""dws 命令执行失败;code 为上游 server_error_code(如 11056=会话不存在)"""
def __init__(self, message: str, code: str = ""):
super().__init__(message)
self.code = code
def _extract_error_code(text: str) -> str:
"""从 dws 错误输出里尽量提取 server_error_code"""
try:
data = json.loads(text[text.find("{"):])
return str(data.get("error", {}).get("server_error_code") or "")
except Exception:
return ""
def _run_dws(cmd_list) -> dict:
"""执行 dws 命令并返回完整 JSON(含 success/result 顶层字段)"""
result = subprocess.run(cmd_list, capture_output=True, text=True,
encoding="utf-8", errors="replace")
if result.returncode != 0:
raise DwsError(f"命令失败: {result.stderr.strip()}",
code=_extract_error_code(result.stderr))
raw = result.stdout
data = json.loads(raw[raw.find("{"):])
if not data.get("success"):
raise DwsError(f"命令未成功: {data}",
code=_extract_error_code(raw))
return data
def _normalize_msg_type(msg_type: str) -> str:
"""消息类型归一化:'文本'/'text' → 'text';'文件'/'file' → 'file'"""
key = str(msg_type or "").strip().lower()
if key in ("text", "文本", "txt", "文字"):
return "text"
if key in ("file", "文件"):
return "file"
raise ValueError(f"未知消息类型「{msg_type}」,仅支持:文本 / 文件")
# ==================== 接口限流(防风控) ====================
_RATE_LIMIT = 50 # 每分钟最大实际发送条数
_RATE_WINDOW_SEC = 60 # 限流窗口(秒)
_RATE_HISTORY = [] # 本进程内窗口内各次实际发送的时间戳(秒)
def _rate_limit_wait():
"""滑动窗口限流:1 分钟窗口内实际发送最多 _RATE_LIMIT 条(默认 50),
避免短时间高频推送触发风控。窗口已满时阻塞等待最早一条滑出窗口后再放行,
保证整批消息最终都能发出、不丢消息。在每次真正调用 dws 发送前调用并占名额。
"""
now = time.time()
while True:
_RATE_HISTORY[:] = [t for t in _RATE_HISTORY if now - t < _RATE_WINDOW_SEC]
if len(_RATE_HISTORY) < _RATE_LIMIT:
break
sleep_sec = max(0.1, _RATE_HISTORY[0] + _RATE_WINDOW_SEC - now)
print(f"[WARN] 已达限流上限({_RATE_LIMIT} 条/分钟),等待 {sleep_sec:.1f} 秒后继续…")
time.sleep(min(sleep_sec, 1.0))
now = time.time()
_RATE_HISTORY.append(time.time())
# ==================== 推送记录(main 传 record_dir 时自动写入,best-effort) ====================
_RECORD_COLUMNS = ["推送时间", "工号", "姓名", "结果", "消息摘要"]
_RECORD_SUMMARY_MAX_CHARS = 200
_GLV_RECORD_PATH = "push_record_path" # 推送记录文件路径(影刀全局变量,供流程自行取用/发送失败名单)
def _set_glv(name, value):
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
try:
glv[name] = value
except Exception:
pass
def _record_csv_path(record_dir):
return os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d"), "推送记录.csv")
def _record_push(user_id, name, result, summary="", record_dir=""):
"""尽力追加一条推送记录到 <record_dir>/YYYY-MM-DD/推送记录.csv。
record_dir 为空串时不记录(本模块供所有场景复用,由调用方传位置)。
best-effort,任何失败都不影响推送。返回记录文件路径(未记录返回空串)。
"""
if not record_dir:
return ""
try:
path = _record_csv_path(record_dir)
os.makedirs(os.path.dirname(path), exist_ok=True)
new_file = not os.path.exists(path)
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
summary = str(summary or "").replace("\r\n", "\n").replace("\r", "\n")
if len(summary) > _RECORD_SUMMARY_MAX_CHARS:
summary = summary[:_RECORD_SUMMARY_MAX_CHARS] + "..."
with open(path, "a", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=_RECORD_COLUMNS)
if new_file:
writer.writeheader()
writer.writerow({
"推送时间": now,
"工号": user_id,
"姓名": name,
"结果": result,
"消息摘要": summary,
})
print(f"[INFO] 推送记录已写入:{path}({result})")
return path
except Exception as e:
print(f"[WARN] 推送记录写入失败(不影响推送):{e}")
return ""
def _write_record_path_to_glv(record_dir):
"""把推送记录文件路径写入影刀全局变量 push_record_path。
未传 record_dir 时写空串,由流程自行读取记录文件处理失败名单。
"""
path = _record_csv_path(record_dir) if record_dir else ""
_set_glv(_GLV_RECORD_PATH, path)
if path:
print(f"[INFO] 推送记录文件路径已写入全局变量 {_GLV_RECORD_PATH}:{path}")
def _record_and_return(result, record_dir, name, user_id, content, file_path):
"""记录推送结果后返回 result(best-effort,写失败不影响推送)。
消息摘要:文本取内容,文件取文件名。
"""
if record_dir:
summary = str(content or "").strip() or os.path.basename(str(file_path))
_record_push(user_id, name, "成功" if result.get("success") else "失败",
summary, record_dir=record_dir)
return result
# ==================== 联系人解析 ====================
_OPEN_ID_CACHE = {} # 按 (name, user_id) 缓存 openDingTalkId,批量推送同一个人只查一次通讯录
def resolve_open_id(name: str, user_id: str = "") -> str:
"""先按姓名搜索候选,再按工号(jobNumber)锁定唯一推送人;未传工号才按姓名判定。
查询结果按 (name, user_id) 缓存于进程内;通讯录有变动时需重启进程生效。
"""
# 入口归一化:避免业务脚本直接调用时带空格(" 张三 " vs "张三")导致缓存键不一致
name = str(name or "").strip()
user_id = str(user_id or "").strip()
key = (name, user_id)
cached = _OPEN_ID_CACHE.get(key)
if cached:
print(f"[INFO] 命中缓存: {name} | userId={user_id}")
return cached
data = _run_dws([DWS_BIN, "contact", "user", "search",
"--query", name, "--format", "json"])
users = data.get("result") or []
if not users:
raise RuntimeError(f"未找到姓名为「{name}」的成员")
# 批量拉详情(含工号 jobNumber、部门)。注意:search 是关键词模糊搜索(会误命中「陈杰顺」
# 等近似名)且返回里没有工号字段,工号只在 get 详情的 orgEmployeeModel.jobNumber,
# 故不能拿 search 的 userId(钉钉长 id)当工号匹配。
ids = ",".join(u["userId"] for u in users)
detail_data = _run_dws([DWS_BIN, "contact", "user", "get",
"--ids", ids, "--format", "json"])
details = detail_data.get("result") or []
# search 的 userId 与 get 返回的 orgEmployeeModel.orgUserId 同源,据此关联详情
info_map = {}
for d in details:
org = d.get("orgEmployeeModel") or {}
if org.get("orgUserId"):
info_map[org["orgUserId"]] = d
# 传入工号:在姓名候选里按工号(jobNumber)锁定实际推送人,命中即唯一,绝不猜第一个
if user_id:
for u in users:
org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
if str(org_model.get("jobNumber") or "").strip() == user_id:
print(f"[INFO] 按工号锁定: {u['name']} | 工号={user_id} | {org_model.get('orgTitle') or ''}")
_OPEN_ID_CACHE[key] = u["openDingTalkId"]
return u["openDingTalkId"]
hints = []
for u in users:
org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
job = str(org_model.get("jobNumber") or "").strip() or "未知"
hints.append(f" {u.get('name')} | 工号={job}")
raise RuntimeError(
f"按姓名「{name}」搜索的候选中未找到工号 {user_id},请核对姓名与工号是否匹配:\n"
+ "\n".join(hints)
)
# 未传工号:按姓名搜索结果判定(候选唯一 → 采用;多个 → 精确同名过滤 → 歧义报错)
if len(users) == 1:
u = users[0]
print(f"[INFO] 命中 1 人: {u['name']} | userId={u['userId']} | {u.get('title') or '无职位'}")
_OPEN_ID_CACHE[key] = u["openDingTalkId"]
return u["openDingTalkId"]
# 按姓名精确过滤:search 为关键词模糊搜索,剔除「陈杰顺」这类误命中后再判
exact = [u for u in users if (u.get("name") or "").strip() == name]
if len(exact) == 1:
u = exact[0]
print(f"[INFO] 按姓名精确命中: {u['name']} | userId={u['userId']} | {u.get('title') or ''}")
_OPEN_ID_CACHE[key] = u["openDingTalkId"]
return u["openDingTalkId"]
# 仍无法唯一确定:禁止默认选第一个,报歧义错误并带工号辅助人工核对
hints = []
for u in users:
org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
depts = org_model.get("depts") or []
dept = ",".join(x.get("deptName", "") for x in depts)
job = str(org_model.get("jobNumber") or "").strip() or "未知"
hints.append(
f" {u.get('name')} | 工号={job} | "
f"部门={dept or '未知'} | 职位={org_model.get('orgTitle') or u.get('title') or '未知'}"
)
raise RuntimeError(
f"「{name}」有 {len(users)} 个同名,请核对工号后再调用:\n" + "\n".join(hints)
)
# ==================== 会话空间与文件 ====================
def get_chat_space_id(open_id: str) -> str:
"""获取单聊会话共享空间 ID;无会话(11056 或缺字段)时返回空串"""
data = _run_dws([DWS_BIN, "chat", "conversation-info",
"--open-dingtalk-id", open_id, "--format", "json"])
try:
return data["result"]["conversationInfo"]["extension"].get("newCSpaceIdIM", "")
except (KeyError, TypeError, AttributeError):
return ""
def upload_file(space_id: str, file_path: str) -> dict:
data = _run_dws([DWS_BIN, "drive", "upload",
"--file", file_path, "--space-id", space_id,
"--format", "json"])
return data["result"]
def get_dentry(file_id: str, space_id: str) -> dict:
data = _run_dws([DWS_BIN, "drive", "info",
"--node", file_id, "--space-id", space_id,
"--format", "json"])
return data["result"]
# ==================== 发送实现 ====================
def send_text(open_id: str, text: str):
"""向单聊发送文本:--user 需要的是钉钉 org userId(≠工号),故统一用
resolve_open_id 解析出的 openDingTalkId 走 --open-dingtalk-id 发送。
兜底:单聊会话由首条消息自动创建;若发送遇 11056(会话不存在),等待 1s
后重试一次——11056 意味着该条未投递,重试不会造成重复发送。
"""
def _do_send():
_rate_limit_wait() # 限流:每次实际发送占用一个名额
_run_dws([DWS_BIN, "chat", "message", "send",
"--open-dingtalk-id", open_id, "--content", text, "--format", "json"])
try:
_do_send()
except DwsError as e:
if e.code != "11056":
raise
print("[INFO] 会话不存在(11056),等待 1s 后重试一次(首条单聊消息即自动建会话)…")
time.sleep(1)
_do_send()
print(f"[INFO] 文本已发送: {text}")
def send_file(open_id: str, file_path: str):
"""发送文件到单聊:取会话空间 ID → 上传 → 发文件消息。
无会话(11056 或缺字段)时 space_id 为空,自动先发一条文本建立会话再发文件。
"""
try:
space_id = get_chat_space_id(open_id)
except DwsError as e:
if e.code != "11056":
raise
space_id = ""
if not space_id:
print("[INFO] 对方未建立会话,先发送一条文本建立会话…")
send_text(open_id, "建立会话")
space_id = get_chat_space_id(open_id)
if not space_id:
raise RuntimeError("建立会话后仍拿不到会话空间 ID(newCSpaceIdIM),请检查")
up = upload_file(space_id, file_path)
info = get_dentry(up["fileId"], up["spaceId"])
_rate_limit_wait() # 限流:文件消息占用一个名额(建会话文本已在 send_text 内计过一次)
_run_dws([DWS_BIN, "chat", "message", "send",
"--open-dingtalk-id", open_id,
"--msg-type", "file",
"--dentry-id", info["dentryId"],
"--space-id", up["spaceId"],
"--file-name", info["name"],
"--file-type", info.get("extension", "file"),
"--file-path", info.get("path", "/" + info["name"]),
"--file-size", str(info["fileSize"]),
"--format", "json"])
print(f"[INFO] 文件已发送: {os.path.basename(file_path)}")
# ==================== 群聊推送 ====================
def search_group(query: str, limit: int = 20) -> list:
"""按群名搜索群聊(关键词模糊搜索),返回候选列表。
注意:dws 要求 query 使用群名连续核心词(如「项目冲刺」),勿拆成单字搜索。
dws chat search 返回结构为 result.groups(result 是字典),此处统一提取列表。
"""
data = _run_dws([DWS_BIN, "chat", "search", "--query", query,
"--limit", str(limit), "--format", "json"])
result = data.get("result") or {}
if isinstance(result, dict):
return result.get("groups") or []
return 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 _group_title(group: dict) -> str:
"""群搜索条目里的群名:dws chat search 返回的群名字段是 title(个别场景可能是 name)。"""
for key in ("title", "name"):
val = (group or {}).get(key)
if val:
return str(val)
return ""
def resolve_group_id(group_name: str) -> str:
"""按群名精确解析群聊 openconversation_id(群名一律传全称)。
先按全称搜索,再对 title 做全等过滤:唯一命中即返回;无匹配或同名多个直接报错,
不采用模糊候选(绝不推给相近群名)。
"""
group_name = str(group_name or "").strip()
if not group_name:
raise RuntimeError("群名不能为空(请传群全称)")
groups = search_group(group_name)
if not groups:
raise RuntimeError(f"未找到群「{group_name}」,请确认群全称后重试")
exact = [g for g in groups if _group_title(g) == group_name]
if len(exact) == 1:
g = exact[0]
print(f"[INFO] 命中群: {_group_title(g)} | openConversationId={_group_conv_id(g)}")
return _group_conv_id(g)
if not exact:
hints = "\n".join(
f" {_group_title(g) or '未知群名'}" for g in groups)
raise RuntimeError(
f"未找到与「{group_name}」全等匹配的群,附近候选:\n{hints}")
hints = "\n".join(
f" {_group_title(g) or '未知群名'} | {_group_conv_id(g)}" for g in exact)
raise RuntimeError(
f"群名「{group_name}」匹配到 {len(exact)} 个同名候选,请确认后重试:\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 send_message(msg_type, name, user_id, content, file_path="", record_dir=""):
"""单条推送:按消息类型分发文本 / 文件。
参数(5 个):msg_type 消息类型、name 姓名、user_id 工号、
content 消息内容、file_path 文件地址。
record_dir(可选):非空时写入 <record_dir>/YYYY-MM-DD/推送记录.csv。
返回 {"success": bool, "message": str}。
"""
name = str(name or "").strip()
user_id = str(user_id or "").strip()
try:
mtype = _normalize_msg_type(msg_type)
if mtype == "text":
if not content or not str(content).strip():
return _record_and_return({"success": False, "message": "文本消息内容不能为空"},
record_dir, name, user_id, content, file_path)
if not name:
return _record_and_return({"success": False, "message": "发送文本需要姓名(name)以解析 openDingTalkId"},
record_dir, name, user_id, content, file_path)
# --user 只认钉钉 org userId(≠工号),文本与文件统一按姓名解析 openDingTalkId 后发送
open_id = resolve_open_id(name, user_id)
print(f"[INFO] 接收人 openDingTalkId: {open_id}")
send_text(open_id, str(content))
return _record_and_return({"success": True, "message": f"已向「{name}」发送文本"},
record_dir, name, user_id, content, file_path)
# 文件
file_path = str(file_path or "").strip()
if not file_path or not os.path.exists(file_path):
return _record_and_return({"success": False, "message": f"文件不存在: {file_path}"},
record_dir, name, user_id, content, file_path)
if not name:
return _record_and_return({"success": False, "message": "发送文件需要姓名(name)以解析 openDingTalkId"},
record_dir, name, user_id, content, file_path)
open_id = resolve_open_id(name, user_id)
print(f"[INFO] 接收人 openDingTalkId: {open_id}")
send_file(open_id, file_path)
return _record_and_return({"success": True, "message": f"已向「{name}」发送文件"},
record_dir, name, user_id, content, file_path)
except Exception as e:
return _record_and_return({"success": False, "message": str(e)},
record_dir, name, user_id, content, file_path)
def _normalize_chat_type(chat_type: str) -> str:
"""推送通道归一化:'single'/'单聊' → 'single';'group'/'群聊' → 'group'"""
key = str(chat_type or "").strip().lower()
if key in ("single", "单聊", "single_chat", "person", "个人", "私聊"):
return "single"
if key in ("group", "群聊", "group_chat", "群"):
return "group"
raise ValueError(f"未知推送通道「{chat_type}」,仅支持:single/单聊、group/群聊")
def _item_is_group(item) -> bool:
"""按消息结构自动判断推送通道:dict 含 group/群名 键 → 群聊;其余(元组 / msg_type dict)→ 单聊。"""
return isinstance(item, dict) and bool(item.get("group") or item.get("群名"))
def main(messages, record_dir="", chat_type=""):
"""影刀自定义指令「37du钉钉推送」统一调用入口。
通道判定(二选一):
- chat_type 显式传 'single'/'group':整批消息强制按该通道发送(兼容旧流程);
- chat_type 留空(默认):按每条消息结构自动判断——dict 含 group/群名 键为群聊,其余为单聊。
因此流程只需传消息列表,群聊消息自带 group 字段即可,无需单独配置 chat_type。
chat_type='single'/单聊:每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址),
或 dict 含 msg_type/name/user_id(缺省字段按空处理):
msg_type 'text'/'文本' 或 'file'/'文件'
name 接收人姓名
user_id 接收人工号
content 消息内容(文本类型必填)
file_path 文件地址(文件类型必填,可留空)
chat_type='group'/群聊:每项支持 dict 或元组:
dict: {"group": 群名, "content": 文本, "file_path": 文件,
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略
record_dir(可选):非空时每条结果写入 <record_dir>/YYYY-MM-DD/推送记录.csv,
并把记录文件路径写入影刀全局变量 push_record_path,供流程自行处理失败名单。
逐条发送,返回: {"success": bool, "message": str, "results": [...]}
"""
forced_channel = _normalize_chat_type(chat_type) if chat_type else ""
results = []
for item in messages or []:
if (forced_channel == "group") or (not forced_channel and _item_is_group(item)):
# 群聊:按群名解析 openconversation_id 后发送(文本/文件可同时存在)
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))
else:
# 单聊:按姓名解析 openDingTalkId 后发送
if isinstance(item, dict):
msg_type = item.get("msg_type") or item.get("消息类型") or ""
name = item.get("name") or item.get("姓名") or ""
user_id = item.get("user_id") or item.get("工号") or ""
content = item.get("content") or item.get("消息内容") or ""
file_path = item.get("file_path") or item.get("文件地址") or ""
else:
msg_type = item[0] if len(item) > 0 else ""
name = item[1] if len(item) > 1 else ""
user_id = item[2] if len(item) > 2 else ""
content = item[3] if len(item) > 3 else ""
file_path = item[4] if len(item) > 4 else ""
results.append(send_message(msg_type, name, user_id, content, file_path, 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,
}
if __name__ == "__main__":
# 本地自测/接口说明:不实际发送。业务脚本请 import 后调用
# 单聊(chat_type 留空自动识别):
# main([("文本", "姓名", "工号", "消息内容", ""),
# ("文件", "姓名", "工号", "", r"文件绝对路径")])
# 群聊(消息 dict 含 group 键自动识别,无需传 chat_type):
# main([{"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"},
]
result = main(messages)
print(result)