# -*- coding: utf-8 -*- """ @Module: utils.dingtalk_sender @FileName: dingtalk_sender.py @Author: 小布丁 @CreateTime: 2026-08-06 @Description: 钉钉桌面客户端消息推送工具 通过模拟键盘快捷键 + 剪贴板,向指定群/联系人发送文本和文件 操作链路:Ctrl+D 激活钉钉 → Ctrl+Shift+F 搜索 → 回车确认 → 粘贴文本/文件 → 回车发送 @Version: 1.0.0 依赖安装: pip install pyautogui pywin32 pyperclip 使用前提: 1. Windows 系统 2. 钉钉桌面客户端已启动并登录 3. (可选)钉钉已配置 Ctrl+D 全局热键用于唤起主面板;未配置时自动回退到 win32 查窗口激活 使用示例: from app.utils.dingtalk_sender import send_to_group, send_to_person # 发送文本到群 send_to_group("测试群", text="你好,这是一条测试消息") # 发送文件到个人 send_to_person("张三", file_path=r"C:\\report\\月报.xlsx") # 同时发送文本和文件(先发文本,再发文件,分两条消息) send_to_person("张三", text="请查收月报", file_path=r"C:\\report\\月报.xlsx") """ import os import struct import time from app.utils.logger import get_logger, setup_logging from app.utils.intelligent_retry import retry logger = get_logger(__name__) # ==================== 第三方依赖(懒加载,缺失时给出清晰提示) ==================== try: import pyautogui except ImportError: pyautogui = None try: import win32gui import win32con import win32clipboard except ImportError: win32gui = None win32con = None win32clipboard = None try: import pyperclip except ImportError: pyperclip = None # ==================== 默认参数 ==================== DEFAULT_ACTIVATE_METHOD = "auto" # auto | hotkey | win32 DEFAULT_WAIT_AFTER_ACTIVATE = 1.0 # 激活后等待窗口就绪 DEFAULT_WAIT_SEARCH_BOX = 0.5 # Ctrl+Shift+F 后等待搜索框打开 DEFAULT_WAIT_SEARCH_RESULT = 1.0 # 粘贴关键词后等待搜索结果加载 DEFAULT_WAIT_CONVERSATION_LOAD = 1.0 # 回车后等待会话开始加载 DEFAULT_WAIT_SEARCH = 2.5 # 会话加载完成、焦点稳定到消息输入框 DEFAULT_WAIT_SEND = 1.0 # 文本发送后等待 DEFAULT_WAIT_FILE_PREVIEW = 1.5 # 文件粘贴后预览框加载 DINGTALK_WINDOW_KEYWORD = "钉钉" def _check_deps(): """检查必需的第三方依赖是否就绪,缺失时抛出带安装提示的 RuntimeError。""" missing = [] if pyautogui is None: missing.append("pyautogui") if win32gui is None: missing.append("pywin32") if pyperclip is None: missing.append("pyperclip") if missing: raise RuntimeError( f"缺少依赖: {', '.join(missing)},请运行: pip install {' '.join(missing)}" ) # ==================== 窗口激活 ==================== def _find_dingtalk_hwnd(): """用 win32gui.EnumWindows 按标题查找钉钉主窗口句柄。""" matches = [] def _enum(hwnd, _): if not win32gui.IsWindowVisible(hwnd): return title = win32gui.GetWindowText(hwnd) if title and DINGTALK_WINDOW_KEYWORD in title: matches.append((hwnd, title)) win32gui.EnumWindows(_enum, None) if not matches: raise RuntimeError( "未找到标题包含「钉钉」的可见窗口,请确认钉钉桌面端已启动并登录" ) # 标题最短的通常是主窗口("钉钉"),优先返回 matches.sort(key=lambda x: len(x[1])) hwnd, title = matches[0] logger.debug("定位到钉钉窗口: hwnd=%s, title=%s", hwnd, title) return hwnd def _activate_by_win32(): """win32 方式激活:还原最小化 + SetForegroundWindow(含 Alt trick 绕过前台锁)。""" hwnd = _find_dingtalk_hwnd() if win32gui.IsIconic(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) time.sleep(0.3) # SetForegroundWindow 受 Windows 前台锁限制,先发一次 Alt 可放开 pyautogui.press("alt") win32gui.SetForegroundWindow(hwnd) time.sleep(DEFAULT_WAIT_AFTER_ACTIVATE) fg_title = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if DINGTALK_WINDOW_KEYWORD not in fg_title: raise RuntimeError(f"win32 激活后前台窗口仍非钉钉: {fg_title!r}") def _activate_by_hotkey(): """热键方式激活:发送 Ctrl+D 全局热键(需钉钉已配置该热键)。""" pyautogui.hotkey("ctrl", "d") time.sleep(DEFAULT_WAIT_AFTER_ACTIVATE) fg_title = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if DINGTALK_WINDOW_KEYWORD not in fg_title: raise RuntimeError( f"Ctrl+D 未能激活钉钉窗口,当前前台: {fg_title!r};" "请在钉钉设置中确认主面板快捷键,或改用 activate_method='win32'" ) def _is_dingtalk_foreground(): """检查钉钉窗口是否已处于最前。""" hwnd = win32gui.GetForegroundWindow() title = win32gui.GetWindowText(hwnd) return DINGTALK_WINDOW_KEYWORD in title def _activate(method=DEFAULT_ACTIVATE_METHOD): """按指定方式激活钉钉窗口。auto = 先 Ctrl+D,失败回退 win32。 若钉钉已在前台则直接返回——Ctrl+D 是 toggle 热键,窗口已显示时再按会把它隐藏, 导致后续发送失败。连续发送时第二次起会命中此分支。 """ if _is_dingtalk_foreground(): logger.info("钉钉窗口已在前台,跳过激活") return if method == "hotkey": _activate_by_hotkey() elif method == "win32": _activate_by_win32() elif method == "auto": try: _activate_by_hotkey() logger.info("通过 Ctrl+D 激活钉钉窗口") except Exception as e: logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e) _activate_by_win32() logger.info("通过 win32 激活钉钉窗口") else: raise ValueError(f"不支持的 activate_method: {method!r},可选: auto/hotkey/win32") # ==================== 剪贴板 ==================== def _set_text_to_clipboard(text): """文本写入剪贴板(pyperclip,自动处理中文)。""" pyperclip.copy(text) def _set_file_to_clipboard(file_path): """ 将文件放入剪贴板(CF_HDROP 格式),供 Ctrl+V 粘贴发送。 构造 DROPFILES 结构 + UTF-16-LE 编码的绝对路径(以双 \\0 结尾)。 """ abspath = os.path.abspath(file_path) if not os.path.exists(abspath): raise FileNotFoundError(f"文件不存在: {abspath}") # 文件列表:单路径 + 双 \0 结尾 files = abspath + "\0\0" file_bytes = files.encode("utf-16-le") # DROPFILES: pFiles=20, pt.x=0, pt.y=0, fNC=0, fWide=1(5 个 unsigned int = 20 字节) dropfiles = struct.pack("IIIII", 20, 0, 0, 0, 1) data = dropfiles + file_bytes win32clipboard.OpenClipboard() try: win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_HDROP, data) finally: win32clipboard.CloseClipboard() logger.debug("文件已放入剪贴板: %s", abspath) # ==================== 搜索 & 发送 ==================== def _search_and_open(target, wait_search=DEFAULT_WAIT_SEARCH): """Ctrl+Shift+F 打开搜索 → 粘贴目标名 → 回车进入会话。 时序很关键:搜索结果加载、会话跳转都需要时间,等待不足会把消息内容 误贴到搜索框。这里分段等待,确保回车后会话已加载、焦点已落到消息输入框。 """ pyautogui.hotkey("ctrl", "shift", "f") time.sleep(DEFAULT_WAIT_SEARCH_BOX) # 搜索框打开 _set_text_to_clipboard(target) pyautogui.hotkey("ctrl", "v") time.sleep(DEFAULT_WAIT_SEARCH_RESULT) # 搜索结果加载 pyautogui.press("enter") time.sleep(DEFAULT_WAIT_CONVERSATION_LOAD) # 会话开始加载 time.sleep(wait_search) # 焦点稳定到消息输入框 logger.info("已搜索并进入会话: %s", target) def _send_text(text, wait_send=DEFAULT_WAIT_SEND): """粘贴文本 → 回车发送。""" _set_text_to_clipboard(text) pyautogui.hotkey("ctrl", "v") time.sleep(0.3) pyautogui.press("enter") time.sleep(wait_send) preview = text[:50] + ("..." if len(text) > 50 else "") logger.info("文本已发送: %s", preview) def _send_file(file_path, wait_file_preview=DEFAULT_WAIT_FILE_PREVIEW): """文件入剪贴板 → Ctrl+V → 等待预览框 → 回车发送。""" _set_file_to_clipboard(file_path) pyautogui.hotkey("ctrl", "v") time.sleep(wait_file_preview) pyautogui.press("enter") time.sleep(DEFAULT_WAIT_SEND) logger.info("文件已发送: %s", file_path) # ==================== 高层 API ==================== class DingTalkSender: """ 钉钉消息推送器,封装可调参数。多次发送复用同一实例可保持参数一致。 Args: activate_method: 窗口激活方式,auto(默认Ctrl+D回退win32) | hotkey | win32 wait_search: 搜索后等待结果加载的秒数 wait_send: 文本发送后等待的秒数 wait_file_preview: 文件粘贴后等待预览框的秒数 """ def __init__( self, activate_method=DEFAULT_ACTIVATE_METHOD, wait_search=DEFAULT_WAIT_SEARCH, wait_send=DEFAULT_WAIT_SEND, wait_file_preview=DEFAULT_WAIT_FILE_PREVIEW, ): _check_deps() self.activate_method = activate_method self.wait_search = wait_search self.wait_send = wait_send self.wait_file_preview = wait_file_preview @retry(max_attempts=2) def _activate(self): _activate(self.activate_method) @retry(max_attempts=2) def _search(self, target): _search_and_open(target, self.wait_search) def send(self, target, text="", file_path="", is_group=False): """ 向指定目标发送消息。 Args: target: 群名或联系人姓名(用于搜索) text: 要发送的文本,空字符串表示不发送文本 file_path: 要发送的文件绝对/相对路径,空字符串表示不发送文件 is_group: True=群消息,False=个人消息(仅日志区分,搜索流程一致) Raises: ValueError: target 为空,或 text 和 file_path 都为空 FileNotFoundError: file_path 指向的文件不存在 RuntimeError: 激活/搜索失败(自动重试 2 次后仍失败) """ if not target: raise ValueError("target 不能为空") if not text and not file_path: raise ValueError("text 和 file_path 至少需要传一个") kind = "群" if is_group else "个人" logger.info( "开始发送 [%s] 目标=%s, 文本=%s, 文件=%s", kind, target, bool(text), file_path or "无", ) self._activate() self._search(target) if text: _send_text(text, self.wait_send) if file_path: _send_file(file_path, self.wait_file_preview) logger.info("发送完成 [%s]: %s", kind, target) def send_dingtalk_message( target, text="", file_path="", is_group=False, activate_method=DEFAULT_ACTIVATE_METHOD, wait_search=DEFAULT_WAIT_SEARCH, wait_send=DEFAULT_WAIT_SEND, wait_file_preview=DEFAULT_WAIT_FILE_PREVIEW, ): """ 一次性发送钉钉消息的便捷函数(内部创建 DingTalkSender)。 Args: target: 群名或联系人姓名 text: 文本内容 file_path: 文件路径 is_group: 是否群消息 activate_method: auto | hotkey | win32 wait_search: 搜索等待秒数 wait_send: 文本发送等待秒数 wait_file_preview: 文件预览框等待秒数 """ setup_logging() sender = DingTalkSender( activate_method=activate_method, wait_search=wait_search, wait_send=wait_send, wait_file_preview=wait_file_preview, ) sender.send(target, text=text, file_path=file_path, is_group=is_group) def send_to_group(group_name, text="", file_path="", **kwargs): """快捷封装:向指定群发送消息。额外参数透传给 send_dingtalk_message。""" send_dingtalk_message(group_name, text=text, file_path=file_path, is_group=True, **kwargs) def send_to_person(name, text="", file_path="", **kwargs): """快捷封装:向指定联系人发送消息。额外参数透传给 send_dingtalk_message。""" send_dingtalk_message(name, text=text, file_path=file_path, is_group=False, **kwargs) # ==================== 命令行入口(便于手动测试) ==================== def main(): import argparse parser = argparse.ArgumentParser(description="钉钉消息推送工具") parser.add_argument("target", help="群名或联系人姓名") parser.add_argument("-t", "--text", default="", help="文本内容") parser.add_argument("-f", "--file", default="", help="文件路径") parser.add_argument("-g", "--group", action="store_true", help="发送到群") parser.add_argument( "--activate-method", default=DEFAULT_ACTIVATE_METHOD, choices=["auto", "hotkey", "win32"], help="窗口激活方式", ) args = parser.parse_args() send_dingtalk_message( args.target, text=args.text, file_path=args.file, is_group=args.group, activate_method=args.activate_method, ) if __name__ == "__main__": main()