# -*- coding: utf-8 -*- """钉钉单聊推送(文本 / 文件)— 外部终端自测版,含重名处理""" import json import os import subprocess DWS_BIN = r"C:\Users\admin\.local\bin\dws.exe" # ↓↓↓ 配置区(测试时改这里)↓↓↓ RECIPIENT_USER_ID = "37036359" # 接收人 userId(发文本用) RECIPIENT_OPEN_ID = "" # 接收人 openDingTalkId(发文件用;留空则按 RECIPIENT_NAME 查询) RECIPIENT_NAME = "张峻杰" # 接收人姓名(OPEN_ID 为空时用于查询,可留空) MESSAGE_TEXT = "测试文件推送" FILE_PATH = r"C:\Users\admin\Desktop\test.xlsx" # 要推送的本地文件路径;留空则只发文本 # ↑↑↑ ↑↑↑ 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 resolve_open_id(name: str, user_id: str = "") -> str: """按姓名查询 openDingTalkId;同名多人时优先用 userId 精确匹配,无 userId 才列候选""" 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"👤 命中 1 人: {u['name']} | userId={u['userId']} | {u.get('title') or '无职位'}") return u["openDingTalkId"] # 同名多人:优先用 userId 精确定位(用户手上有各候选的 userId) if user_id: for u in users: if u.get("userId") == user_id: print(f"👤 按 userId 命中: {u['name']} | userId={u['userId']} | {u.get('title') or ''}") return u["openDingTalkId"] # 同名多人且无匹配 userId:批量拉详情(含部门)帮助区分,禁止默认选第一个 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)} 个同名,请在配置里填 RECIPIENT_OPEN_ID:\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(user_id: str, text: str): _run_dws([DWS_BIN, "chat", "message", "send", "--user", user_id, "--text", text, "--format", "json"]) print(f"✅ 文本已发送: {text}") def send_file(open_id: str, file_path: str, user_id: 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: if not user_id: raise RuntimeError("拿不到会话空间 ID 且未提供 userId,无法发文件") print("ℹ️ 对方未建立会话,先发送一条文本建立会话…") send_text(user_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"]) _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"✅ 文件已发送: {os.path.basename(file_path)}") if __name__ == "__main__": open_id = RECIPIENT_OPEN_ID or (resolve_open_id(RECIPIENT_NAME, RECIPIENT_USER_ID) if RECIPIENT_NAME else "") if open_id: print(f"🔑 接收人 openDingTalkId: {open_id}") # 打印查询到的 OPEN_ID if MESSAGE_TEXT: send_text(RECIPIENT_USER_ID, MESSAGE_TEXT) if FILE_PATH: if not open_id: raise RuntimeError("发文件需要 openDingTalkId:请填 RECIPIENT_OPEN_ID 或 RECIPIENT_NAME") send_file(open_id, FILE_PATH, RECIPIENT_USER_ID)