# -*- coding: utf-8 -*- """ @Module: utils.dingtalk_sender @FileName: dingtalk_sender.py @Author: 小布丁 @CreateTime: 2026-08-06 @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 依赖(项目虚拟环境已安装): pyautogui pywin32 pyperclip psutil pillow numpy rapidocr_onnxruntime 使用前提: 1. Windows 系统 2. 钉钉桌面客户端已启动并登录 3. 钉钉已配置 Ctrl+Alt+D 全局热键(唤起主面板) 使用示例: 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") # 视觉方案底层能力(指定 联系人/群组 类型) 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 logger = get_logger(__name__) # ==================== 第三方依赖 ==================== 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 # ==================== 默认参数 ==================== TIMEOUT = 8 # 会话打开/搜索框验证超时(秒) SEARCH_RETRY = 3 # 搜索重试次数 RETRY_TIMES = 3 # 发送整体重试次数 TOP_HEIGHT_RATIO = 0.18 # 顶部区域占窗口高度的比例(用于OCR截取) # ---------- OCR 初始化 ---------- ocr = None def get_ocr(): """获取 RapidOCR 实例(单例)""" global ocr if ocr is None: ocr = RapidOCR() return ocr # ---------- 窗口操作 ---------- def get_process_name_by_pid(pid): """根据进程 ID 获取进程名称,失败返回 None""" try: return psutil.Process(pid).name() except Exception: return None 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 == '钉钉' 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) 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 send_text_to(chat_type, name, text): """ 向指定联系人或群组发送文本消息(视觉方案底层能力) 参数: chat_type: "联系人" 或 "群组" name: 联系人或群组名称 text: 要发送的消息内容 流程:查找窗口 → 多策略激活 → 搜索并打开会话 → 定位输入框 → 粘贴发送 """ if chat_type not in ["联系人", "群组"]: raise ValueError("chat_type 必须为 '联系人' 或 '群组'") if not text or not text.strip(): raise ValueError("text 不能为空") for attempt in range(RETRY_TIMES): try: # 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. 粘贴并发送 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: paths = [os.path.abspath(str(p)) for p in paths] win32clipboard.OpenClipboard() try: win32clipboard.EmptyClipboard() # DROPFILES 结构:pFiles(4) + pt(8) + fNC(4) + fWide(4) = 20 字节,fWide=1 表示 Unicode dropfiles = struct.pack('