From ce388951fc75e3aded4bb872cf944ff235f8bacc Mon Sep 17 00:00:00 2001 From: spudding <1115683088@qq.com> Date: Sat, 15 Aug 2026 19:25:47 +0800 Subject: [PATCH] =?UTF-8?q?refactor(dingtalk):=20=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E9=92=89=E9=92=89=E5=8F=91=E9=80=81=E5=B7=A5=E5=85=B7=E4=B8=BA?= =?UTF-8?q?OCR=E8=A7=86=E8=A7=89=E6=96=B9=E6=A1=88=EF=BC=8C=E6=9B=BF?= =?UTF-8?q?=E6=8D=A2=E6=97=A7UI=E8=87=AA=E5=8A=A8=E5=8C=96=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 重写核心逻辑为屏幕OCR识别+键盘自动化,大幅提升稳定性 - 移除旧版UIAutomation依赖,新增psutil、rapidocr等依赖 - 拆分新增dingtalk_demo.py作为手动测试入口 - 替换tests/test.py为新的视觉方案测试示例 - 兼容保留旧版API接口(send_to_person/send_to_group等) - 优化窗口激活策略,规避快捷键切换隐藏窗口问题 --- app/utils/dingtalk_sender.py | 919 ++++++++++++++++++++++------------- tests/dingtalk_demo.py | 24 + tests/test.py | 38 -- 3 files changed, 595 insertions(+), 386 deletions(-) create mode 100644 tests/dingtalk_demo.py delete mode 100644 tests/test.py diff --git a/app/utils/dingtalk_sender.py b/app/utils/dingtalk_sender.py index 48749a8..4e04b07 100644 --- a/app/utils/dingtalk_sender.py +++ b/app/utils/dingtalk_sender.py @@ -4,18 +4,26 @@ @FileName: dingtalk_sender.py @Author: 小布丁 @CreateTime: 2026-08-06 -@Description: 钉钉桌面客户端消息推送工具 - 通过模拟键盘快捷键 + 剪贴板,向指定群/联系人发送文本和文件 - 操作链路:Ctrl+D 激活钉钉 → Ctrl+Shift+F 搜索 → 回车确认 → 粘贴文本/文件 → 回车发送 -@Version: 1.0.0 +@Description: 钉钉桌面客户端消息推送工具(视觉方案) + 基于「屏幕截图 + OCR 识别 + 键盘自动化」,向指定群/联系人发送文本和文件。 + 相比旧版(UI Automation / 固定坐标模拟)大幅提升稳定性: + - 窗口查找排除 0 尺寸阴影/辅助窗口,只认主窗口(标题"钉钉/DingTalk") + - 多策略激活(快捷键 → Win32 API → 组合),并规避 Ctrl+Alt+D 切换键把已显示窗口隐藏 + - 搜索框/标签/输入框/激活状态全部通过 OCR 校验后再操作 + - 文件通过 CF_HDROP 剪贴板粘贴发送,无需操作文件对话框 + 操作链路:查找窗口 → 多策略激活 → Ctrl+Shift+F 搜索 → 点击标签 → 回车进入会话 + → OCR 定位输入框 → 粘贴文本/文件 → 回车发送 + 支持向指定联系人/群组发送文本与文件,兼容旧版公共 API + (send_to_person / send_to_group / send_dingtalk_message / DingTalkSender)。 +@Version: 2.0.0 -依赖安装: - pip install pyautogui pywin32 pyperclip uiautomation +依赖(项目虚拟环境已安装): + pyautogui pywin32 pyperclip psutil pillow numpy rapidocr_onnxruntime 使用前提: 1. Windows 系统 2. 钉钉桌面客户端已启动并登录 - 3. (可选)钉钉已配置 Ctrl+D 全局热键用于唤起主面板;未配置时自动回退到 win32 查窗口激活 + 3. 钉钉已配置 Ctrl+Alt+D 全局热键(唤起主面板) 使用示例: from app.utils.dingtalk_sender import send_to_group, send_to_person @@ -28,360 +36,604 @@ # 同时发送文本和文件(先发文本,再发文件,分两条消息) send_to_person("张三", text="请查收月报", file_path=r"C:\\report\\月报.xlsx") + + # 视觉方案底层能力(指定 联系人/群组 类型) + from app.utils.dingtalk_sender import send_text_to, send_file_to + send_text_to("群组", "测试群", "你好") """ import os import struct import time -from app.utils.logger import get_logger, setup_logging -from app.utils.intelligent_retry import retry +from app.utils.logger import get_logger 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 - -try: - import uiautomation as ua -except ImportError: - ua = None - +# ==================== 第三方依赖 ==================== +import pyautogui +import pyperclip +import win32gui +import win32con +import win32api +import win32clipboard +import win32process +import psutil +from PIL import ImageGrab +import numpy as np +from rapidocr_onnxruntime import RapidOCR # ==================== 默认参数 ==================== -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 = "钉钉" +TIMEOUT = 8 # 会话打开/搜索框验证超时(秒) +SEARCH_RETRY = 3 # 搜索重试次数 +RETRY_TIMES = 3 # 发送整体重试次数 +TOP_HEIGHT_RATIO = 0.18 # 顶部区域占窗口高度的比例(用于OCR截取) -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)}" - ) +# ---------- OCR 初始化 ---------- +ocr = None + +def get_ocr(): + """获取 RapidOCR 实例(单例)""" + global ocr + if ocr is None: + ocr = RapidOCR() + return ocr -# ==================== 窗口激活 ==================== -def _find_dingtalk_hwnd(): - """用 win32gui.EnumWindows 按标题查找钉钉主窗口句柄。""" - matches = [] +# ---------- 窗口操作 ---------- +def get_process_name_by_pid(pid): + """根据进程 ID 获取进程名称,失败返回 None""" + try: + return psutil.Process(pid).name() + except Exception: + return None - def _enum(hwnd, _): - if not win32gui.IsWindowVisible(hwnd): - return + +def find_dingtalk_window(include_hidden=True): + """ + 查找钉钉“主窗口”句柄。 + 匹配策略(按优先级): + 1. 窗口标题精确等于“钉钉”或“DingTalk” + 2. 若标题不匹配,检查窗口所属进程名是否为 DingTalk.exe(后备) + 候选窗口必须是有有效尺寸(width/height > 0)的窗口, + 排除 0 尺寸的阴影/辅助窗口(如 DuiShadowWnd、Qt 保存位图等)。 + 选择优先级:主标题且可见 → 主标题 → 任意有效尺寸(优先可见)。 + 返回最合适的句柄,未找到返回 None。 + """ + def has_valid_rect(hwnd): + try: + left, top, right, bottom = win32gui.GetWindowRect(hwnd) + return (right - left) > 0 and (bottom - top) > 0 + except Exception: + return False + + def is_main_title(hwnd): + return win32gui.GetWindowText(hwnd) in ('钉钉', 'DingTalk') + + candidates = [] + def enum_callback(hwnd, _): + if not include_hidden and not win32gui.IsWindowVisible(hwnd): + return True title = win32gui.GetWindowText(hwnd) - if title and DINGTALK_WINDOW_KEYWORD in title: - matches.append((hwnd, title)) + if title == '钉钉' or title == 'DingTalk': + candidates.append(hwnd) + return True + try: + _, pid = win32process.GetWindowThreadProcessId(hwnd) + proc_name = get_process_name_by_pid(pid) + if proc_name and proc_name.lower() == 'dingtalk.exe': + candidates.append(hwnd) + return True + except Exception: + pass + return True + win32gui.EnumWindows(enum_callback, None) - 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) + valid = [h for h in candidates if has_valid_rect(h)] + if not valid: + return None + # 1. 主标题且可见 + for h in valid: + if is_main_title(h) and win32gui.IsWindowVisible(h): + return h + # 2. 主标题(隐藏到托盘时主窗口仍保留有效矩形) + for h in valid: + if is_main_title(h): + return h + # 3. 兜底:任意有效尺寸,优先可见 + for h in valid: + if win32gui.IsWindowVisible(h): + return h + return valid[0] + + +def activate_window(hwnd): + """强制激活窗口(最小化、隐藏、托盘均可恢复)""" + if win32gui.IsIconic(hwnd): + win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) + time.sleep(0.3) + if not win32gui.IsWindowVisible(hwnd): + win32gui.ShowWindow(hwnd, win32con.SW_SHOW) + time.sleep(0.3) + win32gui.SetForegroundWindow(hwnd) + win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) + time.sleep(0.3) + + +def get_window_rect(hwnd): + """获取窗口矩形 (left, top, right, bottom)""" + return win32gui.GetWindowRect(hwnd) + + +def is_dingtalk_main_visible(): + """钉钉主窗口当前是否可见(能找到标题为“钉钉/DingTalk”的可见窗口)""" + hwnd = find_dingtalk_window(include_hidden=True) + return bool(hwnd) and win32gui.IsWindowVisible(hwnd) + + +def is_dingtalk_foreground(): + """钉钉主窗口是否已处于最前(循环调用时第一步检测,已激活则跳过,避免切换键把窗口关闭/切走)""" + fg = win32gui.GetForegroundWindow() + if not fg: + return False + title = win32gui.GetWindowText(fg) or "" + return '钉钉' in title or 'DingTalk' in title + + +# ---------- 截图与 OCR(带空图保护) ---------- +def capture_region(x, y, w, h): + """截取屏幕指定区域,若区域无效则返回 None""" + if w <= 0 or h <= 0: + logger.warning("截图区域无效: (%s, %s, %s, %s),跳过", x, y, w, h) + return None + img = ImageGrab.grab(bbox=(x, y, x + w, y + h)) + if img is None or img.size[0] == 0 or img.size[1] == 0: + logger.warning("抓取图像为空") + return None + return img + + +def ocr_image(img): + """对图像进行 OCR 识别,返回 (text, (x1,y1,x2,y2)) 列表;若 img 为 None 返回空列表""" + if img is None: + return [] + img_np = np.array(img) + result, _ = get_ocr()(img_np) + ocr_data = [] + if result is not None: + for box, text, score in result: + xs = [p[0] for p in box] + ys = [p[1] for p in box] + x1, y1 = min(xs), min(ys) + x2, y2 = max(xs), max(ys) + ocr_data.append((text, (x1, y1, x2, y2))) + if ocr_data: + logger.debug("OCR识别文字: %s", [t for t, _ in ocr_data]) + return ocr_data + + +def find_text_center(ocr_data, target_text): + """在 OCR 结果中查找包含 target_text 的文本框,返回中心坐标 (x, y)""" + for text, (x1, y1, x2, y2) in ocr_data: + if target_text in text: + return (x1 + x2) // 2, (y1 + y2) // 2 + return None + + +# ---------- 搜索框验证 ---------- +def wait_for_tab(hwnd, expected_tab, timeout=TIMEOUT): + """ + 循环检测窗口顶部是否出现 expected_tab 标签(如“联系人”或“群组”), + 用于验证搜索框已打开。 + """ + left, top, right, bottom = get_window_rect(hwnd) + width = right - left + height = bottom - top + top_height = max(40, int(height * TOP_HEIGHT_RATIO)) + start = time.time() + while time.time() - start < timeout: + img = capture_region(left, top, width, top_height) + ocr_data = ocr_image(img) + if find_text_center(ocr_data, expected_tab): + logger.info("检测到'%s'标签", expected_tab) + return True + time.sleep(0.5) + logger.warning("未检测到'%s'标签", expected_tab) + return False + + +# ---------- 核心功能 ---------- +def search_and_open(hwnd, target_name, chat_type="联系人"): + """ + 搜索并打开指定的联系人或群组会话。 + chat_type: "联系人" 或 "群组" + """ + activate_window(hwnd) + # 1. 打开搜索框并输入关键字 + for attempt in range(SEARCH_RETRY): + pyautogui.hotkey('ctrl', 'shift', 'f') + time.sleep(0.8) + pyautogui.hotkey('ctrl', 'a') + pyautogui.press('delete') + pyperclip.copy(target_name) + pyautogui.hotkey('ctrl', 'v') + time.sleep(0.5) + pyautogui.press('enter') + logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1) + time.sleep(0.8) + # 检测对应的标签(联系人/群组)出现,表示搜索已就绪 + if wait_for_tab(hwnd, chat_type, timeout=3): + break + else: + pyautogui.press('esc') + time.sleep(0.5) + else: + logger.error("搜索框未正常打开") + return False + + # 2. 点击对应标签(联系人/群组) + left, top, right, bottom = get_window_rect(hwnd) + width = right - left + height = bottom - top + top_height = max(40, int(height * TOP_HEIGHT_RATIO)) + img = capture_region(left, top, width, top_height) + ocr_data = ocr_image(img) + pos = find_text_center(ocr_data, chat_type) + if pos: + cx, cy = pos + pyautogui.click(left + cx, top + cy) + logger.info("点击'%s'标签", chat_type) + else: + logger.warning("未识别'%s'标签", chat_type) + time.sleep(0.5) + + # 3. 选中第一个结果并打开 + pyautogui.press('enter') + logger.info("打开第一个匹配项") + time.sleep(1.5) + + # 4. 验证会话是否成功打开(检测顶部标题是否出现目标名称) + start = time.time() + while time.time() - start < TIMEOUT: + if is_chat_opened(hwnd, target_name): + logger.info("成功进入会话 '%s'", target_name) + return True + activate_window(hwnd) + time.sleep(0.5) + logger.warning("未检测到会话名 '%s'", target_name) + return False + + +def is_chat_opened(hwnd, target_name): + """截取窗口顶部区域,OCR识别是否有目标名称""" + left, top, right, bottom = get_window_rect(hwnd) + width = right - left + height = bottom - top + top_height = max(40, int(height * TOP_HEIGHT_RATIO)) + img = capture_region(left, top, width, top_height) + ocr_data = ocr_image(img) + for text, _ in ocr_data: + if target_name in text: + logger.debug("标题识别到: '%s'", text) + return True + return False + + +def find_input_box_by_ocr(hwnd): + """通过OCR识别“请输入消息”等提示文字,返回屏幕坐标""" + left, top, right, bottom = get_window_rect(hwnd) + width = right - left + height = bottom - top + bottom_region_top = top + int(height * 0.6) + bottom_region_height = int(height * 0.4) + img = capture_region(left, bottom_region_top, width, bottom_region_height) + ocr_data = ocr_image(img) + keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"] + for keyword in keywords: + pos = find_text_center(ocr_data, keyword) + if pos: + cx, cy = pos + screen_x = left + cx + screen_y = bottom_region_top + cy + logger.info("定位输入框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y) + return screen_x, screen_y + logger.warning("未识别到输入框提示") + return None + + +def focus_input_box(hwnd): + """定位并点击输入框,使其获得焦点""" + input_pos = find_input_box_by_ocr(hwnd) + if input_pos: + pyautogui.click(input_pos[0], input_pos[1]) + return True + # 降级:点击窗口底部中央 + left, top, right, bottom = get_window_rect(hwnd) + width = right - left + height = bottom - top + pyautogui.click(left + width // 2, top + height - 60) + logger.warning("使用固定坐标点击输入框") + return False + + +# ---------- 多策略激活(检测主界面关键词) ---------- +def send_hotkey_to_activate(): + """模拟按下全局快捷键 Ctrl+Alt+D 以激活钉钉窗口""" + logger.info("尝试快捷键 Ctrl+Alt+D 激活") + pyautogui.hotkey('ctrl', 'alt', 'd') + time.sleep(0.8) + + +def is_dingtalk_activated(hwnd, target_name=None): + """ + 通过 OCR 检测钉钉窗口是否已激活到前台(主界面可见)。 + 检测主界面固定文字:搜索框占位、消息、未读等。 + 注意:激活时搜索框未打开,因此不检测“联系人”。 + """ + try: + left, top, right, bottom = get_window_rect(hwnd) + width = right - left + height = bottom - top + if width <= 0 or height <= 0: + return False + + top_height = max(50, int(height * 0.18)) + img = capture_region(left, top, width, top_height) + if img is None: + return False + + ocr_data = ocr_image(img) + + # 若传入了目标名称(仅在会话已打开的场景使用,但激活时不传) + if target_name: + for text, _ in ocr_data: + if target_name in text: + logger.debug("检测到目标名称 '%s'", target_name) + return True + + # 检测主界面关键词(钉钉主窗口必定包含这些之一) + main_keywords = ["搜索或提问", "消息", "未读", "搜索", "提问"] + for kw in main_keywords: + for text, _ in ocr_data: + if kw in text: + logger.debug("检测到主界面关键词 '%s',窗口已激活", kw) + return True + + return False + except Exception as e: + logger.warning("激活检测异常: %s", e) + return False + + +def ensure_activate_dingtalk(hwnd, target_name=None, timeout=10): + """ + 采用多种策略确保钉钉窗口激活到前台(主界面可见),并等待验证。 + 策略:快捷键 → Win32 API → 组合 + 注意:Ctrl+Alt+D 是“切换”快捷键——窗口已显示时按下会将其隐藏到托盘, + 因此只有主窗口当前不可见时才允许按键,否则直接走 API 激活。 + 每次按键/API 后都会重新查找窗口句柄再验证,避免句柄指向 0 尺寸的辅助窗口。 + """ + def wait_for_valid_rect(hwnd, max_wait=1.5): + end = time.time() + max_wait + while time.time() < end: + left, top, right, bottom = get_window_rect(hwnd) + if (right - left) > 0 and (bottom - top) > 0: + return True + time.sleep(0.2) + return False + + def find_current(): + """重新查找当前最合适的钉钉窗口句柄(找不到则回退到传入句柄)""" + return find_dingtalk_window(include_hidden=True) or hwnd + + def verify(hwnd): + """等待并验证窗口已激活到前台(主界面可见)""" + start = time.time() + while time.time() - start < timeout: + if is_dingtalk_activated(hwnd, target_name=None): # 不传名称 + return True + time.sleep(0.5) + return False + + # 策略0:已在前台则直接返回(循环调用时避免重复激活/切换键误关窗口) + if is_dingtalk_foreground(): + logger.info("钉钉已在最前,跳过激活") + return True + + # 策略1:快捷键(仅在主窗口不可见时使用,避免切换键把已显示的窗口隐藏) + if not is_dingtalk_main_visible(): + send_hotkey_to_activate() + cur = find_current() + if cur and wait_for_valid_rect(cur) and verify(cur): + logger.info("快捷键激活成功") + win32gui.SetForegroundWindow(cur) + return True + logger.warning("快捷键后窗口尺寸无效") + else: + logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)") + + # 策略2:API + logger.info("尝试 Win32 API 激活") + cur = find_current() + if cur: + activate_window(cur) + if wait_for_valid_rect(cur) and verify(cur): + logger.info("API激活成功") + return True + logger.warning("API后窗口尺寸无效") + + # 策略3:组合(同样避免对已显示窗口重复按键,防止切换成隐藏) + logger.info("组合激活") + if not is_dingtalk_main_visible(): + send_hotkey_to_activate() + time.sleep(0.5) + cur = find_current() + if cur: + activate_window(cur) + time.sleep(1) + if wait_for_valid_rect(cur) and verify(cur): + logger.info("组合激活成功") + return True + + raise RuntimeError("所有激活策略失败") + + +# ---------- 主发送函数(视觉方案底层) ---------- +def _find_hwnd_or_raise(): + """查找钉钉窗口,失败时给出可读的错误信息。""" + hwnd = find_dingtalk_window(include_hidden=True) + if not hwnd: + dingtalk_running = any(p.name().lower() == 'dingtalk.exe' for p in psutil.process_iter()) + if not dingtalk_running: + raise RuntimeError("钉钉进程未运行,请手动启动并登录") + else: + raise RuntimeError("找到进程但无窗口,请手动激活") 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): - """激活钉钉窗口:先找窗口,托盘中则 Ctrl+D 唤起,win32 置前,点击确保焦点。 - - 若钉钉已在前台则直接返回--Ctrl+D 是 toggle 热键,窗口已显示时再按会把它隐藏, - 导致后续发送失败。连续发送时第二次起会命中此分支。 +def send_text_to(chat_type, name, text): """ - if _is_dingtalk_foreground(): - logger.info("钉钉窗口已在前台,跳过激活") - return + 向指定联系人或群组发送文本消息(视觉方案底层能力) + 参数: + chat_type: "联系人" 或 "群组" + name: 联系人或群组名称 + text: 要发送的消息内容 + 流程:查找窗口 → 多策略激活 → 搜索并打开会话 → 定位输入框 → 粘贴发送 + """ + if chat_type not in ["联系人", "群组"]: + raise ValueError("chat_type 必须为 '联系人' 或 '群组'") + if not text or not text.strip(): + raise ValueError("text 不能为空") - # 先尝试找到已打开的钉钉窗口 - hwnd = None - try: - hwnd = _find_dingtalk_hwnd() - except RuntimeError: - pass - - if hwnd is None: - # 钉钉在系统托盘,用 Ctrl+D 全局热键唤起 - pyautogui.hotkey("ctrl", "d") - time.sleep(1.5) + for attempt in range(RETRY_TIMES): try: - hwnd = _find_dingtalk_hwnd() - except RuntimeError: - raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键") + # 1. 查找钉钉窗口(含隐藏) + hwnd = _find_hwnd_or_raise() - # win32 置前台 - if win32gui.IsIconic(hwnd): - win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) - time.sleep(0.3) - pyautogui.press("alt") - win32gui.SetForegroundWindow(hwnd) - time.sleep(DEFAULT_WAIT_AFTER_ACTIVATE) + # 2. 激活窗口(验证主界面出现) + ensure_activate_dingtalk(hwnd, target_name=None, timeout=10) - # 点击窗口中心确保键盘焦点落在钉钉上(SetForegroundWindow 只切前台,不保证键盘焦点) - rect = win32gui.GetWindowRect(hwnd) - cx = (rect[0] + rect[2]) // 2 - cy = (rect[1] + rect[3]) // 2 - pyautogui.click(cx, cy) - time.sleep(0.5) + # 激活后重新查找当前的主窗口句柄(快捷键/API 可能改变了可见窗口) + hwnd = find_dingtalk_window(include_hidden=True) or hwnd - if _is_dingtalk_foreground(): - logger.info("钉钉窗口已激活") + # 3. 搜索并打开会话(传入 chat_type) + if not search_and_open(hwnd, name, chat_type): + raise RuntimeError(f"打开{chat_type}会话失败") + + # 4. 定位并点击输入框 + focus_input_box(hwnd) + time.sleep(0.3) + + # 5. 粘贴并发送 + pyperclip.copy(text) + pyautogui.hotkey('ctrl', 'v') + time.sleep(0.2) + pyautogui.press('enter') + logger.info("发送成功:%s...", text[:30]) + return + + except RuntimeError as e: + logger.error(str(e)) + raise + except Exception as e: + logger.error("第%d次尝试失败:%s", attempt + 1, e) + time.sleep(2) + + raise RuntimeError(f"重试 {RETRY_TIMES} 次后失败") + + +def copy_files_to_clipboard(paths): + """ + 将文件列表复制到剪贴板(CF_HDROP 格式,与资源管理器复制文件一致), + 供钉钉输入框粘贴后生成待发送文件气泡。 + """ + if isinstance(paths, (str, os.PathLike)): + paths = [os.path.abspath(str(paths))] else: - raise RuntimeError("无法激活钉钉窗口,请确认钉钉桌面端已启动并登录") - - -# ==================== 剪贴板 ==================== -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 - + paths = [os.path.abspath(str(p)) for p in paths] win32clipboard.OpenClipboard() try: win32clipboard.EmptyClipboard() - win32clipboard.SetClipboardData(win32clipboard.CF_HDROP, data) + # DROPFILES 结构:pFiles(4) + pt(8) + fNC(4) + fWide(4) = 20 字节,fWide=1 表示 Unicode + dropfiles = struct.pack(' max_depth or len(result) > 20: - return - try: - ct = control.ControlType - if ct in (ua.ControlType.EditControl, ua.ControlType.DocumentControl): - result.append(control) - except Exception: - pass - try: - for child in control.GetChildren(): - _find_editable_controls(child, result, depth + 1, max_depth) - except Exception: - pass - - -def _rect_area(rect): - """计算矩形面积,无效矩形返回 0。""" - try: - return max(0, rect.right - rect.left) * max(0, rect.bottom - rect.top) - except Exception: - return 0 - - -def _focus_message_input(): - """聚焦消息输入框(分辨率无关)。 - - 优先使用 UI Automation 遍历钉钉控件树,定位底部区域面积最大的可编辑控件 - (即消息输入框)并点击;若 uiautomation 不可用或未找到控件,回退到 - Escape 键关闭搜索面板,依赖钉钉将焦点自动移至消息输入框。 +def send_file_to(chat_type, name, file_path): """ - if ua is not None: + 向指定联系人或群组发送文件(视觉方案底层能力) + 参数: + chat_type: "联系人" 或 "群组" + name: 联系人或群组名称 + file_path: 要发送的文件路径 + 流程:查找窗口 → 多策略激活 → 搜索并打开会话 → 复制文件到剪贴板 → 粘贴 → 回车发送 + """ + if chat_type not in ["联系人", "群组"]: + raise ValueError("chat_type 必须为 '联系人' 或 '群组'") + file_path = os.path.abspath(file_path) + if not os.path.isfile(file_path): + raise FileNotFoundError(f"文件不存在: {file_path}") + + for attempt in range(RETRY_TIMES): try: - hwnd = _find_dingtalk_hwnd() - window = ua.ControlFromHandle(hwnd) - if window is not None: - edits = [] - _find_editable_controls(window, edits) - valid = [e for e in edits if e.BoundingRectangle and _rect_area(e.BoundingRectangle) > 0] - if valid: - wleft, wtop, wright, wbottom = win32gui.GetWindowRect(hwnd) - wh = wbottom - wtop - # 优先选择窗口底部 40% 区域的可编辑控件 - bottom_edits = [ - e for e in valid - if e.BoundingRectangle.bottom > wtop + wh * 0.6 - ] - candidates = bottom_edits if bottom_edits else valid - # 取面积最大的(消息输入框通常是最大的可编辑区域) - target = max(candidates, key=lambda e: _rect_area(e.BoundingRectangle)) - rect = target.BoundingRectangle - cx = (rect.left + rect.right) // 2 - cy = (rect.top + rect.bottom) // 2 - pyautogui.click(cx, cy) - time.sleep(0.3) - logger.debug("UI Automation 定位到消息输入框: (%d, %d)", cx, cy) - return + # 1. 查找钉钉窗口(含隐藏) + hwnd = _find_hwnd_or_raise() + + # 2. 激活窗口(验证主界面出现) + ensure_activate_dingtalk(hwnd, target_name=None, timeout=10) + + # 激活后重新查找当前的主窗口句柄(快捷键/API 可能改变了可见窗口) + hwnd = find_dingtalk_window(include_hidden=True) or hwnd + + # 3. 搜索并打开会话(传入 chat_type) + if not search_and_open(hwnd, name, chat_type): + raise RuntimeError(f"打开{chat_type}会话失败") + + # 4. 定位并点击输入框 + focus_input_box(hwnd) + time.sleep(0.3) + + # 5. 复制文件到剪贴板并粘贴,回车发送 + copy_files_to_clipboard([file_path]) + pyautogui.hotkey('ctrl', 'v') + time.sleep(0.8) # 等待生成待发送文件气泡 + pyautogui.press('enter') + logger.info("发送文件成功:%s", file_path) + return + + except RuntimeError as e: + logger.error(str(e)) + raise except Exception as e: - logger.debug("UI Automation 聚焦失败: %s", e) + logger.error("第%d次尝试失败:%s", attempt + 1, e) + time.sleep(2) - # 回退:钉钉可能失焦,重新确认前台并点击窗口底部消息输入框区域 - if not _is_dingtalk_foreground(): - _activate() - try: - hwnd = _find_dingtalk_hwnd() - rect = win32gui.GetWindowRect(hwnd) - cx = (rect[0] + rect[2]) // 2 - cy = rect[1] + int((rect[3] - rect[1]) * 0.85) # 窗口底部 15%,消息输入框区域 - pyautogui.click(cx, cy) - time.sleep(0.3) - logger.debug("回退方案:点击窗口底部聚焦消息输入框: (%d, %d)", cx, cy) - except Exception: - pyautogui.press("escape") - time.sleep(0.3) - logger.debug("最终回退:通过 Escape 键尝试聚焦") + raise RuntimeError(f"重试 {RETRY_TIMES} 次后失败") -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) # 会话加载完成 - _focus_message_input() # 聚焦消息输入框 - 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 ==================== +# ==================== 兼容旧版公共 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, + activate_method="auto", + wait_search=2.5, + wait_send=1.0, + wait_file_preview=1.5, ): - _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): """ 向指定目标发送消息。 @@ -390,12 +642,12 @@ class DingTalkSender: target: 群名或联系人姓名(用于搜索) text: 要发送的文本,空字符串表示不发送文本 file_path: 要发送的文件绝对/相对路径,空字符串表示不发送文件 - is_group: True=群消息,False=个人消息(仅日志区分,搜索流程一致) + is_group: True=群消息,False=个人消息 Raises: ValueError: target 为空,或 text 和 file_path 都为空 FileNotFoundError: file_path 指向的文件不存在 - RuntimeError: 激活/搜索失败(自动重试 2 次后仍失败) + RuntimeError: 激活/搜索/发送失败(内部自动重试后仍失败) """ if not target: raise ValueError("target 不能为空") @@ -403,33 +655,19 @@ class DingTalkSender: 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) + chat_type = "群组" if is_group else "联系人" + logger.info("开始发送 [%s] 目标=%s, 文本=%s, 文件=%s", + kind, target, bool(text), file_path or "无") if text: - _send_text(text, self.wait_send) - + send_text_to(chat_type, target, text) if file_path: - _send_file(file_path, self.wait_file_preview) + send_file_to(chat_type, target, file_path) 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, -): +def send_dingtalk_message(target, text="", file_path="", is_group=False, **kwargs): """ 一次性发送钉钉消息的便捷函数(内部创建 DingTalkSender)。 @@ -438,19 +676,9 @@ def send_dingtalk_message( text: 文本内容 file_path: 文件路径 is_group: 是否群消息 - activate_method: auto | hotkey | win32 - wait_search: 搜索等待秒数 - wait_send: 文本发送等待秒数 - wait_file_preview: 文件预览框等待秒数 + **kwargs: 兼容旧版参数(activate_method / 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) + DingTalkSender(**kwargs).send(target, text=text, file_path=file_path, is_group=is_group) def send_to_group(group_name, text="", file_path="", **kwargs): @@ -467,15 +695,11 @@ def send_to_person(name, text="", file_path="", **kwargs): def main(): import argparse - parser = argparse.ArgumentParser(description="钉钉消息推送工具") + 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( @@ -483,7 +707,6 @@ def main(): text=args.text, file_path=args.file, is_group=args.group, - activate_method=args.activate_method, ) diff --git a/tests/dingtalk_demo.py b/tests/dingtalk_demo.py new file mode 100644 index 0000000..1e8dd2d --- /dev/null +++ b/tests/dingtalk_demo.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +""" +钉钉自动化(纯 OCR + 键盘)演示入口 +视觉方案实现已迁移至 app/utils/dingtalk_sender.py,本文件仅作为手动测试入口。 +功能: +- 发送文本到联系人或群组 +- 发送文件到联系人或群组 +""" + +import os +import sys + +# 以脚本方式直接运行时,将项目根目录加入 sys.path 以导入 app 包 +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from app.utils.dingtalk_sender import send_file_to, send_text_to # noqa: E402 + +if __name__ == "__main__": + # 示例:向联系人发送消息 + send_text_to("联系人", "夏一平", "测试消息") + # 示例:向群组发送消息 + # send_text_to("群组", "小布丁", "测试消息") + # 示例:发送文件 + # send_file_to("联系人", "夏一平", r"D:\path\to\file.txt") diff --git a/tests/test.py b/tests/test.py deleted file mode 100644 index 719ac5b..0000000 --- a/tests/test.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -"""端到端测试:向夏一平(个人)和群聊小布丁分别发送测试文本 + 文件。""" -import os -import sys -import time - -# tests/ 在项目根下一级,需往上一级到项目根才能 import app -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -from app.utils.dingtalk_sender import send_to_person, send_to_group - -TEST_TEXT = "【自动化测试】这是一条测试消息,请忽略" -TEST_FILE = r"C:\Users\11156\Desktop\测试.txt" - - -def main(): - print("=" * 50) - print("即将发送,运行期间请勿移动鼠标/键盘") - print("=" * 50) - time.sleep(3) # 留 3 秒切换到钉钉、把手离开鼠标 - - # 1. 个人:夏一平 —— 先文本后文件 - print("\n[1/2] 发送给个人「夏一平」: 文本 + 文件") - send_to_person("夏一平", text=TEST_TEXT, file_path=TEST_FILE) - - time.sleep(2) - - # 2. 群聊:小布丁 —— 先文本后文件 - print("\n[2/2] 发送给群聊「小布丁」: 文本 + 文件") - send_to_group("小布丁", text=TEST_TEXT, file_path=TEST_FILE) - - print("\n" + "=" * 50) - print("全部发送完成,请到钉钉核对") - print("=" * 50) - - -if __name__ == "__main__": - main()