feat: 新增钉钉DWS推送模块,废弃旧钉钉推送脚本并更新全流程

1. 标记dingtalk_sender.py为废弃,新增dingtalk_dws_push.py基于DWS CLI实现钉钉单聊推送
2. 为花名册导出添加TTL缓存功能,支持强制重新导出
3. 更新考勤、排班异常脚本的推送逻辑,适配新的推送模块
4. 新增钉钉推送自测脚本
5. 更新项目文档与业务说明
This commit is contained in:
2026-08-28 13:38:17 +08:00
parent 24332ca371
commit 79f3d2d206
9 changed files with 702 additions and 55 deletions
+416
View File
@@ -0,0 +1,416 @@
# -*- coding: utf-8 -*-
"""
@FileName: dingtalk_dws_push.py
@Description: 钉钉单聊推送共享模块(文本 / 文件,基于 dws 命令行)。
供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉单聊推送」的模块源码。
入口:
main(messages, record_dir='') 影刀自定义指令「37du钉钉单聊推送」调用入口。
传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址):
msg_type 消息类型:'text'/'文本' 或 'file'/'文件'
name 接收人姓名(文本/文件均按姓名解析 openDingTalkId;同名多人时按工号精确定位)
user_id 接收人工号(同名消歧;发文件且对方无会话时用于先建会话)
content 消息内容(msg_type=text 时必填)
file_path 文件地址(msg_type=file 时必填,本地绝对路径)
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='') # 单条发送(内部/业务脚本复用)
推送原理(DWS CLI,零第三方 Python 依赖,仅标准库):
- 文本:按姓名解析 openDingTalkId 后 dws chat message send --open-dingtalk-id <openId> --text <内容>
(dws 的 --user 只认钉钉 org userId,与工号不同,故文本/文件统一走 --open-dingtalk-id;
单聊会话由首条消息自动创建,遇 11056 自动等待后重试一次,无需对方先聊过天)
- 文件:按姓名查 openDingTalkId → 取单聊会话共享空间 ID → 上传文件到钉盘
→ 按 dentry 信息发文件消息;对方未建立会话(11056)时自动先发一条
文本建立会话再发文件。
防风控限流:
每次实际发送前经滑动窗口限流(默认 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:
"""按姓名查询 openDingTalkId;同名多人时优先用工号精确匹配,无工号才列候选。
查询结果按 (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}」的成员")
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"]
# 同名多人:优先用工号精确定位(调用方手上应有候选的工号)
if user_id:
for u in users:
if u.get("userId") == user_id:
print(f"[INFO] 按工号命中: {u['name']} | userId={u['userId']} | {u.get('title') or ''}")
_OPEN_ID_CACHE[key] = u["openDingTalkId"]
return u["openDingTalkId"]
# 同名多人且无匹配工号:批量拉详情(含部门)帮助区分,禁止默认选第一个
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 []
info_map = {d["orgEmployeeModel"]["orgUserId"]: d for d in details}
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)
hints.append(
f" {u.get('name')} | userId={u.get('userId')} | "
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, "--text", 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 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 main(messages, record_dir=""):
"""影刀自定义指令「37du钉钉单聊推送」调用入口。
传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址),
缺省字段按空处理:
msg_type 'text'/'文本' 或 'file'/'文件'
name 接收人姓名
user_id 接收人工号
content 消息内容(文本类型必填)
file_path 文件地址(文件类型必填,可留空)
record_dir(可选):非空时每条结果写入 <record_dir>/YYYY-MM-DD/推送记录.csv,
并把记录文件路径写入影刀全局变量 push_record_path,供流程自行处理失败名单。
逐条发送,返回: {"success": bool, "message": str, "results": [...]}
"""
results = []
for item in messages or []:
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 后调用
# main([("文本", "姓名", "工号", "消息内容", ""),
# ("文件", "姓名", "工号", "", r"文件绝对路径")])
messages = [
{"msg_type": "text", "name": "李泽燕", "user_id": "37001979", "content": "你好,测试一条由ai推送的文本消息"},
# {"msg_type": "file", "name": "李泽燕", "user_id": "37001979", "file_path": r"C:\Users\admin\Desktop\test.xlsx"},
]
result = main(messages)
print(result)