Files
37duAutomation/app/utils/dingtalk_sender.py
T
puddy eabadf5a37 refactor: 升级OCR依赖与适配rapidocr v3+,补充业务字段展示
主要变更:
1. 统一替换rapidocr-onnxruntime为rapidocr+onnxruntime依赖包
2. 适配rapidocr v3+ API变更:调整OCR结果解析逻辑
3. 补充展示员工岗位信息到OA审批通知
4. 优化OA详情链接格式为Markdown可点击样式
5. 修复OCR图片EXIF旋转问题与文件名解码
6. 新增RPA开发提成评分规则文档
7. 重构OA登录入口参数,简化调用逻辑
8. 删除临时测试脚本
2026-08-27 13:32:48 +08:00

864 lines
35 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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 import RapidOCR
# ==================== 默认参数 ====================
SEARCH_RETRY = 3 # 搜索并打开会话的外层重试次数(标签/会话校验的 OCR 偶发抖动由它兜底)
RETRY_TIMES = 3 # 发送整体重试次数
TOP_HEIGHT_RATIO = 0.18 # 顶部区域占窗口高度的比例(用于OCR截取)
CACHED_INPUT_POS = None # (rect, x, y) 输入框坐标缓存:同批次窗口未移动则复用,省去重复 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):
"""确保窗口在前台(最小化、隐藏、托盘均可恢复)。
已在前台直接返回,绝不无谓地抢焦点——否则批量推送时会反复把焦点从用户正在
操作的应用抢到钉钉(表现为「所有窗口失焦、点不动」)。
前台锁绕过:Windows 禁止后台进程直接 SetForegroundWindow(表现为窗口只在任务栏
「闪现」却上不了前台)。这里用两步让它真正前置:
1. AttachThreadInput:把本线程输入队列挂到前台线程,冒充「前台进程」;
2. Alt 完整按下+抬起(down+up 对,不是孤立的 KEYUP):告诉系统「用户刚按了
键」,进一步放宽前台锁;完整按键对不会遗留粘滞状态。
"""
if win32gui.GetForegroundWindow() == hwnd:
return
if win32gui.IsIconic(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
time.sleep(0.1)
if not win32gui.IsWindowVisible(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
time.sleep(0.1)
# 前台锁绕过:挂到前台线程 + Alt 按下/抬起,让 SetForegroundWindow 真正生效
fg_hwnd = win32gui.GetForegroundWindow()
cur_thread = win32api.GetCurrentThreadId()
fg_thread = win32process.GetWindowThreadProcessId(fg_hwnd)[0] if fg_hwnd else 0
attached = False
if fg_thread and fg_thread != cur_thread:
try:
win32process.AttachThreadInput(fg_thread, cur_thread, True)
attached = True
except Exception:
attached = False
try:
win32api.keybd_event(win32con.VK_MENU, 0, 0, 0) # Alt 按下
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) # Alt 抬起
win32gui.SetForegroundWindow(hwnd)
finally:
if attached:
try:
win32process.AttachThreadInput(fg_thread, cur_thread, False)
except Exception:
pass
time.sleep(0.2)
def get_window_rect(hwnd):
"""获取窗口矩形 (left, top, right, bottom)"""
return win32gui.GetWindowRect(hwnd)
def safe_click(x, y):
"""异常安全的鼠标左键点击:任何情况(异常/打断)都保证左键松开。
不用 pyautogui.click——它在 mouseDown 与 mouseUp 之间被打断时会留下卡死的左键
(症状:屏幕点不动、滚轮失效,必须重启才能恢复)。
实现:SetCursorPos 瞬移指针 + mouse_event 按下/抬起(finally 兜底松开)。
"""
win32api.SetCursorPos(int(x), int(y))
time.sleep(0.05)
try:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
time.sleep(0.05)
finally:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
time.sleep(0.05)
def release_mouse():
"""安全兜底:补发左键松开,清掉历史遗留的卡死左键状态(幂等,无害)。"""
try:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
except Exception:
pass
def find_dingtalk_main_window():
"""只找钉钉主窗口(标题为「钉钉/DingTalk」且有效尺寸)。
优先返回可见的主窗口;找不到可见的再回退到任意有效尺寸的主标题窗口。
用于「可见性」判断,避免 find_dingtalk_window 偶发选中搜索/辅助/阴影窗口,
导致把已显示的钉钉误判为隐藏,从而误按 Ctrl+Alt+D 切换键把它切到托盘。
"""
visible_main = None
any_main = None
def enum_callback(hwnd, _):
nonlocal visible_main, any_main
if win32gui.GetWindowText(hwnd) not in ('钉钉', 'DingTalk'):
return True
try:
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
if (right - left) <= 0 or (bottom - top) <= 0:
return True
if any_main is None:
any_main = hwnd
if win32gui.IsWindowVisible(hwnd) and visible_main is None:
visible_main = hwnd
except Exception:
pass
return True
win32gui.EnumWindows(enum_callback, None)
return visible_main or any_main
def is_dingtalk_main_visible():
"""钉钉主窗口当前是否可见(能找到标题为“钉钉/DingTalk”的可见窗口)"""
hwnd = find_dingtalk_main_window()
return bool(hwnd) and win32gui.IsWindowVisible(hwnd)
def is_dingtalk_foreground():
"""钉钉主窗口是否已处于最前(循环调用时第一步检测,已激活则跳过,避免切换键把窗口关闭/切走)。
直接比对前台窗口句柄 == 钉钉主窗口句柄(毫秒级,比标题匹配更准)。"""
main_hwnd = find_dingtalk_main_window()
return bool(main_hwnd) and win32gui.GetForegroundWindow() == main_hwnd
# ---------- 截图与 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 and result.boxes is not None:
for box, text, score in zip(result.boxes, result.txts, result.scores):
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
# ---------- 顶部区域 OCR(DRY 封装) ----------
def analyze_top_region(hwnd):
"""截取窗口顶部区域并 OCR,返回 (text, (x1,y1,x2,y2)) 列表。
顶部区域「截屏+OCR」样板代码的唯一封装点(DRY),供 wait_for_tab /
is_chat_opened / search_and_open 复用,避免各处重复写 rect 计算 + 截图 + 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)
return ocr_image(img)
# ---------- 搜索框验证 ----------
def wait_for_tab(hwnd, expected_tab):
"""顶部区域 OCR 检测 expected_tab 标签(如“联系人”或“群组”)。
快速失败(fail-fast):最多 OCR 2 次(即时 + 0.3s 重试),失败交由外层
SEARCH_RETRY 循环兜底重试,不再长时间轮询死磕 OCR(OCR 是重型计算,按次计费)。
"""
for i in range(2):
ocr_data = analyze_top_region(hwnd)
if find_text_center(ocr_data, expected_tab):
logger.info("检测到'%s'标签", expected_tab)
return True
if i == 0:
time.sleep(0.3) # 给 UI 渲染一个短暂重试机会
logger.warning("未检测到'%s'标签", expected_tab)
return False
# ---------- 核心功能 ----------
def focus_search_box(hwnd):
"""OCR 定位主界面搜索框(占位文本“搜索或提问”)并点击一次,
让钉钉把焦点放到搜索框(比纯快捷键更稳,避免 Ctrl+Shift+F 失败)。
"""
ocr_data = analyze_top_region(hwnd)
if not ocr_data:
return False
left, top, _, _ = get_window_rect(hwnd)
for keyword in ("搜索或提问", "搜索", "提问"):
pos = find_text_center(ocr_data, keyword)
if pos:
cx, cy = pos
screen_x, screen_y = left + cx, top + cy
safe_click(screen_x, screen_y)
logger.info("已点击搜索框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
time.sleep(0.3)
return True
logger.warning("未识别到搜索框占位文本(搜索或提问/搜索/提问)")
return False
def search_and_open(hwnd, target_name, chat_type="联系人"):
"""搜索并打开指定的联系人或群组会话。
chat_type: "联系人" 或 "群组"
简化设计:不再用 Ctrl+Shift+F 快捷键(会被前台锁/输入法干扰且逻辑重复),
一律 OCR 点击主界面搜索框(focus_search_box)→ 输入关键字 → 回车。
每个 attempt 开头 esc 复位,避免残留搜索面板遮住占位文本。
快速失败设计(fail-fast):标签检测(wait_for_tab)与会话校验(is_chat_opened)
都只做最多 2 次 OCR(即时 + 0.3s 重试),失败 continue 回到外层 SEARCH_RETRY
循环重试(避免「会话校验偶发漏检 → 整条消息永久失败」的致命坑)。
"""
for attempt in range(SEARCH_RETRY):
activate_window(hwnd)
# 复位:关闭可能残留的搜索面板,让占位文本回到可见
pyautogui.press('esc')
time.sleep(0.3)
if not focus_search_box(hwnd):
logger.warning("未识别到搜索框(第%d次),外层重试", attempt + 1)
continue
# 1. 输入关键字并搜索
pyautogui.hotkey('ctrl', 'a')
pyautogui.press('delete')
pyperclip.copy(target_name)
pyautogui.hotkey('ctrl', 'v')
time.sleep(0.2)
pyautogui.press('enter')
logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1)
time.sleep(0.5)
if not wait_for_tab(hwnd, chat_type):
logger.warning("未检测到'%s'标签(第%d次),外层重试", chat_type, attempt + 1)
continue
# 2. 点击对应标签(联系人/群组)
ocr_data = analyze_top_region(hwnd)
left, top, _, _ = get_window_rect(hwnd)
pos = find_text_center(ocr_data, chat_type)
if pos:
cx, cy = pos
safe_click(left + cx, top + cy)
logger.info("点击'%s'标签", chat_type)
else:
logger.warning("未识别'%s'标签", chat_type)
time.sleep(0.3)
# 3. 选中第一个结果并打开
pyautogui.press('enter')
logger.info("打开第一个匹配项")
time.sleep(1.0)
# 4. 验证会话是否成功打开(最多 2 次 OCR,失败继续外层重试)
if is_chat_opened(hwnd, target_name):
logger.info("成功进入会话 '%s'", target_name)
return True
logger.warning("未检测到会话名 '%s',外层重试", target_name)
continue
logger.error("搜索并打开会话失败(重试 %d 次后仍失败)", SEARCH_RETRY)
return False
def is_chat_opened(hwnd, target_name):
"""顶部区域 OCR 校验会话标题是否包含 target_name。
快速失败(fail-fast):最多 OCR 2 次(即时 + 0.3s 重试),失败由 search_and_open
的外层 SEARCH_RETRY 循环兜底重试,不再原地死循环轮询。
"""
for i in range(2):
ocr_data = analyze_top_region(hwnd)
for text, _ in ocr_data:
if target_name in text:
logger.debug("标题识别到: '%s'", text)
return True
if i == 0:
time.sleep(0.3)
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):
"""定位并点击输入框,使其获得焦点。
优化:批量推送时钉钉窗口位置/尺寸不变,输入框在窗口内的位置也固定,
因此首次 OCR 定位后按窗口 rect 缓存绝对坐标,后续会话直接复用缓存点击,
省去每人一次的输入框 OCR;窗口被拖动/缩放(rect 变化)时缓存自动失效重定位。
"""
global CACHED_INPUT_POS
rect = get_window_rect(hwnd)
cached = CACHED_INPUT_POS
if cached and cached[0] == rect:
_, cx, cy = cached
safe_click(cx, cy)
logger.info("使用缓存输入框坐标 (%s, %s)", cx, cy)
return True
if cached:
logger.info("窗口位置/尺寸变化,输入框缓存失效,重新 OCR 定位")
input_pos = find_input_box_by_ocr(hwnd)
if input_pos:
CACHED_INPUT_POS = (rect, input_pos[0], input_pos[1])
safe_click(input_pos[0], input_pos[1])
return True
# 降级:点击窗口底部中央
left, top, right, bottom = rect
width = right - left
height = bottom - top
safe_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 ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
"""多策略确保钉钉窗口激活到前台(Win32 API 优先 → 快捷键兜底 → 组合)。
注意:Ctrl+Alt+D 是钉钉「唤起/隐藏主面板」的【切换】快捷键——窗口已显示时按下会把它
隐藏到托盘(用户反馈的「发着发着钉钉窗口突然隐藏且再也唤不回来」即因此触发)。
因此本函数:
1. Win32 API 激活(ShowWindow + SetForegroundWindow)只显示/前置,永远不会隐藏窗口,
作为主力路径优先使用,不依赖切换键;
2. 切换键只在 API 失效且确认主窗口不可见时才按,且每次按键后自校验是否变为可见,
若反而不可见(误切隐藏)立即补按切回,绝不让窗口停留在隐藏状态;
3. verify 采用快速失败(最多 3 轮「尝试前置 + 检查」,约 1.5s 内给出结论),
不再长时间等待。
"""
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):
"""Win32 校验激活成功:主窗口可见且位于前台(不做 OCR,毫秒级)。
快速失败:最多 3 轮「尝试前置 + 检查」,约 1.5s 内给出结论,不再长时间等待。
"""
for _ in range(3):
main = find_dingtalk_main_window()
if main and win32gui.IsWindowVisible(main) and win32gui.GetForegroundWindow() == main:
return True
# 可见但未在前台 → 再尝试前置(含 Alt 释放前台锁)
activate_window(main or hwnd)
time.sleep(0.2)
return False
def toggle_show():
"""按切换键显示主面板并自校验:按后可见则成功;若反而不可见(误切隐藏)再按一次切回。"""
send_hotkey_to_activate()
cur = find_current()
if cur and wait_for_valid_rect(cur) and is_dingtalk_main_visible():
return True
send_hotkey_to_activate() # 把已显示的窗口切隐藏了 → 补按切回
cur = find_current()
return bool(cur) and is_dingtalk_main_visible()
# 已在前台则直接返回(循环调用时避免重复激活/切换键误关窗口)
if is_dingtalk_foreground():
logger.info("钉钉已在最前,跳过激活")
return True
# 策略1(主力):Win32 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后窗口仍未在前台")
# 策略2(兜底):仅在主窗口不可见时按切换快捷键(toggle_show 自带防切隐藏校验)
if not is_dingtalk_main_visible():
if toggle_show():
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.warning("快捷键后窗口仍未显示")
else:
logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)")
# 策略3(最后手段):组合(同样只在主窗口不可见时按切换键,避免切隐藏)
logger.info("组合激活")
if not is_dingtalk_main_visible():
if toggle_show():
cur = find_current()
if cur:
activate_window(cur)
if wait_for_valid_rect(cur) and verify(cur):
logger.info("组合激活成功")
return True
logger.warning("组合切换后主界面未确认")
else:
logger.warning("组合切换后窗口仍未显示")
else:
# 窗口已可见:直接 API 激活兜底,绝不按切换键
cur = find_current()
if cur:
activate_window(cur)
if wait_for_valid_rect(cur) and verify(cur):
logger.info("组合激活成功(API)")
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 不能为空")
release_mouse() # 清掉可能的卡死左键,再开始本消息
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('<Iiiii', 20, 0, 0, 0, 1)
file_list = '\x00'.join(paths) + '\x00\x00'
win32clipboard.SetClipboardData(win32con.CF_HDROP, dropfiles + file_list.encode('utf-16le'))
finally:
win32clipboard.CloseClipboard()
def send_file_to(chat_type, name, file_path):
"""
向指定联系人或群组发送文件(视觉方案底层能力)
参数:
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}")
release_mouse() # 清掉可能的卡死左键,再开始本消息
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. 复制文件到剪贴板并粘贴,回车发送
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.error("第%d次尝试失败:%s", attempt + 1, e)
time.sleep(2)
raise RuntimeError(f"重试 {RETRY_TIMES} 次后失败")
# ==================== 兼容旧版公共 API ====================
class DingTalkSender:
"""
钉钉消息推送器(视觉方案)。多次发送复用同一实例。
构造参数仅为兼容旧版调用方,视觉方案无需调参,均被忽略。
"""
def __init__(
self,
activate_method="auto",
wait_search=2.5,
wait_send=1.0,
wait_file_preview=1.5,
):
self.activate_method = activate_method
self.wait_search = wait_search
self.wait_send = wait_send
self.wait_file_preview = wait_file_preview
def send(self, target, text="", file_path="", is_group=False, keyword="", record_dir=""):
"""
向指定目标发送消息。
Args:
target: 群名或联系人姓名(用于搜索)
text: 要发送的文本,空字符串表示不发送文本
file_path: 要发送的文件绝对/相对路径,空字符串表示不发送文件
is_group: True=群消息,False=个人消息
keyword: 联系人推送记录用的工号(可选,默认取 target),
仅个人推送时写入推送记录(见 app/utils/push_record.py)
record_dir: 推送记录保存目录(按场景传入,不写死;空串=不记录)
Raises:
ValueError: target 为空,或 text 和 file_path 都为空
FileNotFoundError: file_path 指向的文件不存在
RuntimeError: 激活/搜索/发送失败(内部自动重试后仍失败)
"""
if not target:
raise ValueError("target 不能为空")
if not text and not file_path:
raise ValueError("text 和 file_path 至少需要传一个")
kind = "群" if is_group else "个人"
chat_type = "群组" if is_group else "联系人"
logger.info("开始发送 [%s] 目标=%s, 文本=%s, 文件=%s",
kind, target, bool(text), file_path or "无")
try:
if text:
send_text_to(chat_type, target, text)
if file_path:
send_file_to(chat_type, target, file_path)
except Exception as e:
# 记录推送失败(仅个人推送;群消息由群机器人 dingtalk_robot 另行留痕)
if not is_group:
_record_app_push(keyword or target, target, "失败", text,
error=str(e), record_dir=record_dir)
logger.info("发送失败 [%s]: %s -> %s", kind, target, e)
raise
else:
# 记录推送成功(仅个人推送)
if not is_group:
_record_app_push(keyword or target, target, "成功", text, record_dir=record_dir)
logger.info("发送完成 [%s]: %s", kind, target)
def _record_app_push(keyword, name, result, text="", error="", record_dir=""):
"""尽力记录一条钉钉联系人推送(best-effort,不影响发送主流程)。"""
try:
from app.utils.push_record import record_push
record_push(keyword=keyword, name=name, result=result, text=text,
error=error, record_dir=record_dir or None)
except Exception as e:
logger.debug("推送记录失败(忽略):%s", e)
def send_dingtalk_message(target, text="", file_path="", is_group=False,
keyword="", record_dir="", **kwargs):
"""
一次性发送钉钉消息的便捷函数(内部创建 DingTalkSender)。
Args:
target: 群名或联系人姓名
text: 文本内容
file_path: 文件路径
is_group: 是否群消息
keyword: 联系人推送记录用的工号(可选,仅个人推送时写入推送记录)
record_dir: 推送记录保存目录(按场景传入,不写死;空串=不记录)
**kwargs: 兼容旧版参数(activate_method / wait_search / wait_send / wait_file_preview),忽略
"""
DingTalkSender(**kwargs).send(target, text=text, file_path=file_path,
is_group=is_group, keyword=keyword, record_dir=record_dir)
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="", keyword="", record_dir="", **kwargs):
"""快捷封装:向指定联系人发送消息。额外参数透传给 send_dingtalk_message。"""
send_dingtalk_message(name, text=text, file_path=file_path, is_group=False,
keyword=keyword, record_dir=record_dir, **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="发送到群")
args = parser.parse_args()
send_dingtalk_message(
args.target,
text=args.text,
file_path=args.file,
is_group=args.group,
)
if __name__ == "__main__":
main()