Files
37duAutomation/workflows/share/dingtalk_sender.py
T
puddy 2350ca671f feat: 新增多个业务需求脚本与共享模块
新增内容包括:
1. 7个业务需求占位文档目录与README
2. 共享OA登录、钉钉机器人推送工具模块
3. 雇主险变更清单导出脚本
4. 考勤月报封存检查两个检查脚本
5. 重庆社保停保导入名单生成脚本
2026-09-08 16:16:15 +08:00

775 lines
34 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 -*-
"""
【已废弃 / DEPRECATED】
钉钉联系人(单聊)文本推送已改由 yingdao/share/dingtalk_dws_push.py 替代
(DWS CLI 直连:免 OCR、免 pyautogui/rapidocr 等重型依赖,带 50 条/分钟限流与推送记录,
glv['messages'] 形状为 5 元组 (msg_type, name, user_id, content, file_path))。
本文件保留仅作参考 / 兼容旧流程,不推荐新流程使用;新需求请用 dingtalk_dws_push.py。
@FileName: dingtalk_sender.py
@Description: 钉钉联系人推送自定义指令(影刀编码版 Python 模块源码,单一真源,已废弃)。
作为「37du钉钉推送」影刀自定义指令的模块源码,
供所有需要钉钉单人推送的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
避免每个脚本各自内联 OCR 视觉发送逻辑。
仅推送「联系人」(单聊);群消息已改用钉钉群机器人(webhook)推送,
见同目录 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
如何在影刀中创建指令:
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_sender,添加 Python 模块;
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
3. 增加流程参数 messages(列表类型),每项为 (search_keyword, text, verify_keyword) 元组;
4. 保存并「发版」;在需要钉钉推送的应用中「获取指令」并安装;
5. 在流程中拖入该指令,把业务脚本输出的消息列表直接传给 messages 参数;
指令返回 JSON:{"success": bool, "message": str, "results": [...]},可在后续流程中判断是否重试。
推送原理(OCR 视觉方案,与 app/utils/dingtalk_sender.py 一致):
查找钉钉窗口 → 多策略激活到前台 → Ctrl+Shift+F 搜索联系人 → OCR 定位输入框
→ 粘贴文本 → 回车发送。
依赖(影刀「Python包管理」安装;启动校验不懒加载):
pip install pyautogui pywin32 pyperclip psutil
pip install Pillow numpy rapidocr onnxruntime
入口:
main(messages) 影刀自定义指令调用入口,直接传列表,每项为 (search_keyword, text, verify_keyword) 元组:
search_keyword 联系人搜索关键字(支持工号,避免同名误选)
text 要发送的消息内容
verify_keyword 会话校验关键字(钉钉标题显示姓名,用工号搜索时传姓名校验,可选)
仅推送联系人(单聊);群消息请改用同目录 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
返回 JSON 安全 dict:{"success": bool, "message": str, "results": [...]}
python dingtalk_sender.py 独立运行(默认发送 __main__ 中的测试消息列表)
推送记录(可选,best-effort,不影响发送):
1. 在 main 传入 record_dir(推送记录保存目录,空串=不记录)时,每次推送结果写入:
记录目录/YYYY-MM-DD/推送记录.csv,列 = 推送时间, 工号, 姓名, 结果, 消息摘要;
由调用方按场景传入,不写死(dingtalk_sender 供所有场景复用);
2. 推送结束后把推送记录文件路径写入影刀全局变量 push_record_path,
失败名单由流程自行读取记录文件处理(不在此生成名单文本)。
"""
import csv
import os
import time
import ctypes
from datetime import datetime
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
try:
import pyautogui
import win32gui
import win32con
import win32api
import win32process
import pyperclip
import psutil
from PIL import Image, ImageGrab
import numpy as np
from rapidocr import RapidOCR
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(钉钉推送指令要求所有库在启动前装齐,不懒加载)。\n"
"请先执行安装:\n"
" pip install pyautogui pywin32 pyperclip psutil\n"
" pip install Pillow numpy rapidocr onnxruntime\n"
f"缺失依赖详情: {_import_err}"
)
# ==================== 日志(print) ====================
class _PrintLogger:
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
@staticmethod
def debug(msg, *args):
if args:
msg = msg % args
print(f"[DEBUG] {msg}")
@staticmethod
def info(msg, *args):
if args:
msg = msg % args
print(f"[INFO] {msg}")
@staticmethod
def warning(msg, *args):
if args:
msg = msg % args
print(f"[WARN] {msg}")
@staticmethod
def error(msg, *args):
if args:
msg = msg % args
print(f"[ERROR] {msg}")
logger = _PrintLogger()
# ==================== 推送记录(main 传入 record_dir 时自动写入,best-effort) ====================
_DT_RECORD_COLUMNS = ["推送时间", "工号", "姓名", "结果", "消息摘要"]
_DT_SUMMARY_MAX_CHARS = 200
_DT_GLV_RECORD_PATH = "push_record_path" # 推送记录文件路径(影刀全局变量,供流程自行取用/发送失败名单)
def _dt_set_glv(name, value):
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
try:
glv[name] = value
except Exception:
pass
def _dt_record_csv_path(record_dir):
return os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d"), "推送记录.csv")
def _dt_record_push(keyword, name, result, text="", error="", record_dir=""):
"""尽力追加一条推送记录到 <record_dir>/YYYY-MM-DD/推送记录.csv。
record_dir 为空串时不记录(dingtalk_sender 供所有场景复用,由调用方传位置)。
best-effort,任何失败都不影响推送。返回记录文件路径(未记录返回空串)。
"""
if not record_dir:
return ""
try:
path = _dt_record_csv_path(record_dir)
os.makedirs(os.path.dirname(path), exist_ok=True)
new_file = not os.path.exists(path)
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
summary = str(text or "").replace("\r\n", "\n").replace("\r", "\n")
if len(summary) > _DT_SUMMARY_MAX_CHARS:
summary = summary[:_DT_SUMMARY_MAX_CHARS] + "..."
with open(path, "a", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=_DT_RECORD_COLUMNS)
if new_file:
writer.writeheader()
writer.writerow({
"推送时间": now,
"工号": keyword,
"姓名": name,
"结果": result,
"消息摘要": summary,
})
logger.info("推送记录已写入:%s(%s)", path, result)
return path
except Exception as e:
logger.warning("推送记录写入失败(不影响推送):%s", e)
return ""
def _dt_write_record_path_to_glv(record_dir):
"""把推送记录文件路径写入影刀全局变量 push_record_path。
未传 record_dir 或记录失败时写空串,由流程自行读取记录文件处理失败名单。
"""
path = _dt_record_csv_path(record_dir) if record_dir else ""
_dt_set_glv(_DT_GLV_RECORD_PATH, path)
if path:
logger.info("推送记录文件路径已写入全局变量 %s:%s", _DT_GLV_RECORD_PATH, path)
# ==================== 钉钉 OCR 视觉推送(单一真源,与 app/utils/dingtalk_sender.py 一致) ====================
_DT_SEARCH_RETRY = 4 # 搜索并打开会话的外层重试次数(标签/会话校验的 OCR 偶发抖动由它兜底)
_DT_RETRY_TIMES = 3
_DT_TOP_HEIGHT_RATIO = 0.18
_DT_CACHED_INPUT_POS = None # (rect, screen_x, screen_y) 输入框坐标缓存:同批次窗口未移动则复用,省去重复 OCR
def _dt_warmup_ocr(inst):
"""预热 OCR 模型:实例创建后跑一次空白图,提前加载 onnx 模型,
避免真正识别时因模型加载/首轮推理过慢导致漏检(搜索面板「联系人」标签未识别到)。
"""
try:
blank = Image.new("RGB", (64, 64), (255, 255, 255))
inst(np.array(blank))
logger.info("OCR 模型预热完成")
except Exception as e:
logger.warning("OCR 预热失败(不影响后续使用): %s", e)
def _dt_get_ocr():
"""获取 RapidOCR 实例(单例)。
实例挂在函数自身属性上,避免依赖模块级可变全局变量:影刀指令运行环境对
「模块级 global 变量」的作用域处理与标准 Python 不同(曾报
name '_dt_ocr' is not defined),函数属性存放在函数对象自身,任何环境都可靠。
"""
inst = getattr(_dt_get_ocr, "_instance", None)
if inst is None:
inst = RapidOCR()
_dt_get_ocr._instance = inst
_dt_warmup_ocr(inst)
return inst
def _dt_get_process_name_by_pid(pid):
try:
return psutil.Process(pid).name()
except Exception:
return None
def _dt_find_dingtalk_window(include_hidden=True):
"""查找钉钉主窗口句柄(排除 0 尺寸阴影/辅助窗口,只认 DingTalk 进程或主标题)。"""
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 = _dt_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
for h in valid:
if is_main_title(h) and win32gui.IsWindowVisible(h):
return h
for h in valid:
if is_main_title(h):
return h
for h in valid:
if win32gui.IsWindowVisible(h):
return h
return valid[0]
def _dt_activate_window(hwnd):
"""确保窗口在前台(最小化、隐藏、托盘均可恢复)。
已在前台直接返回,绝不无谓地抢焦点——否则批量推送时会反复把焦点从用户正在
操作的应用抢到钉钉(表现为「所有窗口失焦、点不动」)。
前台锁绕过:Windows 禁止后台进程直接 SetForegroundWindow(表现为窗口只在任务栏
「闪现」却上不了前台)。用两步让它真正前置并保持:
1. SPI_SETFOREGROUNDLOCKTIMEOUT=0:临时关闭系统「前台锁超时」,允许后台进程
抢占前台(随后立即恢复原值,副作用最小);
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 按下/抬起 + TOPMOST 强制置顶,
# 让 SetForegroundWindow 真正生效(见函数头注释)。
old_lock = None
try:
lock_val = ctypes.c_uint()
if ctypes.windll.user32.SystemParametersInfoW(0x2000, 0, ctypes.byref(lock_val), 0): # SPI_GETFOREGROUNDLOCKTIMEOUT
old_lock = lock_val.value
ctypes.windll.user32.SystemParametersInfoW(0x2001, 0, 0, 0x2) # SPI_SETFOREGROUNDLOCKTIMEOUT=0, SPIF_SENDCHANGE
time.sleep(0.05) # 等系统设置生效
except Exception:
old_lock = None
try:
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0) # Alt 按下
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) # Alt 抬起
win32gui.SetForegroundWindow(hwnd)
win32gui.BringWindowToTop(hwnd)
# TOPMOST 强制置顶再取消:后台进程也能把窗口顶到 Z 序最前,
# 是对「SetForegroundWindow 被前台锁拒绝 → 任务栏闪现」最可靠的兜底。
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, 0, 0, 0, 0,
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
finally:
if old_lock is not None:
try:
ctypes.windll.user32.SystemParametersInfoW(0x2001, old_lock, 0, 0x2) # 恢复原超时
except Exception:
pass
time.sleep(0.2)
def _dt_get_window_rect(hwnd):
return win32gui.GetWindowRect(hwnd)
def _dt_safe_click(x, y):
"""异常安全的鼠标左键点击:任何情况(异常/打断)都保证左键松开。
不用 pyautogui.click——它在 mouseDown 与 mouseUp 之间被打断时会留下卡死的左键
(症状:屏幕点不动、滚轮失效,必须重启才能恢复)。
实现:SetCursorPos 瞬移指针 + mouse_event 按下/抬起(finally 兜底松开)。
"""
ctypes.windll.user32.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 _dt_release_mouse():
"""安全兜底:补发左键松开,清掉历史遗留的卡死左键状态(幂等,无害)。"""
try:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
except Exception:
pass
def _dt_find_dingtalk_main_window():
"""只找钉钉主窗口(标题为「钉钉/DingTalk」且有效尺寸)。
优先返回可见的主窗口;找不到可见的再回退到任意有效尺寸的主标题窗口。
用于「可见性」判断,避免 _dt_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 _dt_is_dingtalk_foreground():
"""钉钉主窗口是否在前台:直接比对前台窗口句柄 == 钉钉主窗口句柄(毫秒级,比标题匹配更准)。"""
main_hwnd = _dt_find_dingtalk_main_window()
return bool(main_hwnd) and win32gui.GetForegroundWindow() == main_hwnd
def _dt_capture_region(x, y, w, h):
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 _dt_ocr_image(img):
if img is None:
return []
img_np = np.array(img)
result = _dt_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)))
return ocr_data
def _dt_find_text_center(ocr_data, target_text):
for text, (x1, y1, x2, y2) in ocr_data:
if target_text in text:
return (x1 + x2) // 2, (y1 + y2) // 2
return None
def _dt_analyze_top_region(hwnd):
"""截取窗口顶部区域并 OCR,返回 (text, (x1,y1,x2,y2)) 列表。
顶部区域「截屏+OCR」样板代码的唯一封装点(DRY),供 _dt_wait_for_tab /
_dt_is_chat_opened / _dt_focus_search_box / _dt_search_and_open 复用,
避免各处重复写 rect 计算 + 截图 + OCR 三件套。
"""
left, top, right, bottom = _dt_get_window_rect(hwnd)
width = right - left
height = bottom - top
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
img = _dt_capture_region(left, top, width, top_height)
return _dt_ocr_image(img)
def _dt_wait_for_tab(hwnd, expected_tab):
"""顶部区域 OCR 检测 expected_tab 标签(如「联系人」)。
快速失败(fail-fast):最多 OCR 2 次(即时 + 0.3s 重试),失败交由外层
_DT_SEARCH_RETRY 循环兜底重试,不再长时间轮询死磕 OCR(OCR 是重型计算,按次计费)。
"""
for i in range(2):
ocr_data = _dt_analyze_top_region(hwnd)
if _dt_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 _dt_is_chat_opened(hwnd, target_name):
"""顶部区域 OCR 校验会话标题是否包含 target_name。
快速失败(fail-fast):最多 OCR 2 次(即时 + 0.3s 重试),失败由
_dt_search_and_open 的外层 _DT_SEARCH_RETRY 循环兜底重试,不再原地死循环轮询。
"""
for i in range(2):
ocr_data = _dt_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 _dt_search_and_open(hwnd, search_keyword, verify_keyword=None):
"""搜索并打开指定联系人的会话(仅单聊;群消息改用钉钉群机器人 webhook 推送)。
search_keyword 为搜索关键字(支持工号,避免同名人员误选,如搜索 10086);
verify_keyword 为打开会话后校验标题用的关键字(钉钉会话标题显示的是联系人姓名
而非工号,故同名人场景需传姓名用于校验;不传则回退为 search_keyword)。
简化设计:不再用 Ctrl+Shift+F 快捷键 + OCR 兜底的双路径(快捷键会被前台锁/输入法
干扰且逻辑重复),一律 OCR 点击主界面搜索框(_dt_focus_search_box)→ 输入关键字 →
回车。每个 attempt 开头 esc 复位,避免上一个 attempt 残留的搜索面板遮住占位文本。
快速失败设计(fail-fast):标签检测(_dt_wait_for_tab)与会话校验(_dt_is_chat_opened)
都只做最多 2 次 OCR(即时 + 0.3s 重试),失败不再原地长时间轮询死磕 OCR,
而是 continue 回到外层 _DT_SEARCH_RETRY 循环重试(避免「会话校验偶发漏检 →
整条消息永久失败」的致命坑)。
"""
for attempt in range(_DT_SEARCH_RETRY):
_dt_activate_window(hwnd)
# 复位:关闭可能残留的搜索面板,让「搜索或提问」占位文本回到可见
pyautogui.press('esc')
time.sleep(0.3)
if not _dt_focus_search_box(hwnd):
logger.warning("未识别到搜索框(第%d次),外层重试", attempt + 1)
continue
# 输入关键字并搜索
pyautogui.hotkey('ctrl', 'a')
pyautogui.press('delete')
pyperclip.copy(search_keyword)
pyautogui.hotkey('ctrl', 'v')
time.sleep(0.2)
pyautogui.press('enter')
logger.info("搜索 '%s' (尝试 %d)", search_keyword, attempt + 1)
time.sleep(0.5)
if not _dt_wait_for_tab(hwnd, "联系人"):
logger.warning("未检测到'联系人'标签(第%d次),外层重试", attempt + 1)
continue
# 点击「联系人」标签 → 回车打开第一个匹配项
ocr_data = _dt_analyze_top_region(hwnd)
left, top, _, _ = _dt_get_window_rect(hwnd)
pos = _dt_find_text_center(ocr_data, "联系人")
if pos:
cx, cy = pos
_dt_safe_click(left + cx, top + cy)
logger.info("点击'联系人'标签")
else:
logger.warning("未识别'联系人'标签")
time.sleep(0.3)
pyautogui.press('enter')
logger.info("打开第一个匹配项")
time.sleep(1.0)
# 会话校验:最多 2 次 OCR,失败继续外层重试(不再原地死循环轮询)
if _dt_is_chat_opened(hwnd, verify_keyword or search_keyword):
logger.info("成功进入会话 '%s'", verify_keyword or search_keyword)
return True
logger.warning("未检测到会话名 '%s',外层重试", verify_keyword or search_keyword)
continue
logger.error("搜索并打开会话失败(重试 %d 次后仍失败)", _DT_SEARCH_RETRY)
return False
def _dt_find_input_box_by_ocr(hwnd):
left, top, right, bottom = _dt_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 = _dt_capture_region(left, bottom_region_top, width, bottom_region_height)
ocr_data = _dt_ocr_image(img)
keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"]
for keyword in keywords:
pos = _dt_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 _dt_focus_input_box(hwnd):
"""定位并点击输入框,使其获得焦点。
优化:批量推送时钉钉窗口位置/尺寸不变,输入框在窗口内的位置也固定,
因此首次 OCR 定位后按窗口 rect 缓存绝对坐标,后续会话直接复用缓存点击,
省去每人一次的输入框 OCR;窗口被拖动/缩放(rect 变化)时缓存自动失效重定位。
"""
global _DT_CACHED_INPUT_POS
rect = _dt_get_window_rect(hwnd)
cached = _DT_CACHED_INPUT_POS
if cached and cached[0] == rect:
_, cx, cy = cached
_dt_safe_click(cx, cy)
logger.info("使用缓存输入框坐标 (%s, %s)", cx, cy)
return True
if cached:
logger.info("窗口位置/尺寸变化,输入框缓存失效,重新 OCR 定位")
input_pos = _dt_find_input_box_by_ocr(hwnd)
if input_pos:
_DT_CACHED_INPUT_POS = (rect, input_pos[0], input_pos[1])
_dt_safe_click(input_pos[0], input_pos[1])
return True
left, top, right, bottom = rect
width = right - left
height = bottom - top
_dt_safe_click(left + width // 2, top + height - 60)
logger.warning("使用固定坐标点击输入框")
return False
def _dt_send_hotkey_to_activate():
logger.info("尝试快捷键 Ctrl+Alt+D 激活")
pyautogui.hotkey('ctrl', 'alt', 'd')
time.sleep(0.8)
def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
"""快捷键主力 + 窗口状态检测兜底(不再用 Win32 SetForegroundWindow 前置——
本机实测后台进程调它会被前台锁拒绝,表现为窗口只在任务栏「闪现」却上不了前台;
而 Ctrl+Alt+D 是钉钉注册的全局快捷键,钉钉自己响应用户级热键唤出,能真正前置)。
Ctrl+Alt+D 是「唤起/隐藏主面板」的【切换】键——窗口已显示时按下会把它隐藏到托盘
(原始 bug「发着发着钉钉窗口突然隐藏且再也唤不回来」即因此触发)。
因此严格依赖窗口状态检测,绝不盲目按键:
1. 已在前台 → 直接成功,绝不按键、绝不抢焦点(否则批量推送反复抢焦点
→ 「所有窗口失焦、点不动」);
2. 主窗口不可见(托盘/最小化)→ 按 Ctrl+Alt+D 唤出(唤出时钉钉自动前置),
每次按键后自校验是否变为可见;
3. 主窗口可见但不前台 → 先按一次切到托盘,确认隐藏后再按一次唤出,
借「唤出」时机把窗口带到前台(直接按键会把可见窗口切隐藏,绝不可行);
若按键后状态与预期不符(快捷键未生效)立即补按纠正,绝不让窗口停在隐藏态;
4. 快速失败:最多 3 轮「唤出 + 稳定校验」(激活后稍等再比对前台句柄,
避免「闪现」瞬间误判成功),尽快给出结论。
"""
def find_main():
return _dt_find_dingtalk_main_window()
def main_visible():
main = find_main()
return bool(main) and win32gui.IsWindowVisible(main)
def wait_state(want_visible, max_wait=1.5):
end = time.time() + max_wait
while time.time() < end:
if main_visible() == want_visible:
return True
time.sleep(0.2)
return False
def stable_foreground():
# 稳定校验:激活动作后稍等再比对前台句柄,避免「闪现」瞬间误判成功
time.sleep(0.35)
main = find_main()
return bool(main) and win32gui.GetForegroundWindow() == main
if _dt_is_dingtalk_foreground():
logger.info("钉钉已在最前,跳过激活")
return True
for _ in range(3): # 快速失败:最多 3 轮「唤出 + 稳定校验」
if main_visible():
# 可见但不前台:先切隐藏,确认后再唤出(借唤出时机前置)
_dt_send_hotkey_to_activate()
if not wait_state(False):
# 按键后仍可见(快捷键未生效/状态异常)→ 不盲目再按,重试一轮
logger.warning("切换隐藏未生效,重试")
time.sleep(0.3)
continue
_dt_send_hotkey_to_activate() # 从托盘唤出(此时钉钉自动前置)
if stable_foreground():
logger.info("激活成功(快捷键唤出)")
return True
time.sleep(0.2)
raise RuntimeError("所有激活策略失败")
def _dt_find_hwnd_or_raise():
hwnd = _dt_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 _dt_focus_search_box(hwnd):
"""OCR 定位主界面搜索框(占位文本「搜索或提问」)并点击一次,
让钉钉把焦点放到搜索框(比纯快捷键更稳,避免 Ctrl+Shift+F 失败),
同时该次识别本身就是一次真实 OCR 预热。
"""
ocr_data = _dt_analyze_top_region(hwnd)
if not ocr_data:
return False
left, top, _, _ = _dt_get_window_rect(hwnd)
for keyword in ("搜索或提问", "搜索", "提问"):
pos = _dt_find_text_center(ocr_data, keyword)
if pos:
cx, cy = pos
screen_x, screen_y = left + cx, top + cy
_dt_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 _dt_send_text_to_person(search_keyword, text, verify_keyword=None):
"""向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。
search_keyword 为搜索关键字(支持工号);verify_keyword 为会话标题校验关键字(钉钉标题显示姓名,
同名人时传姓名校验;不传则用 search_keyword 校验),二者分离避免同名误选。
"""
if not text or not text.strip():
raise ValueError("text 不能为空")
_dt_release_mouse() # 清掉可能的卡死左键,再开始本消息
for attempt in range(_DT_RETRY_TIMES):
try:
hwnd = _dt_find_hwnd_or_raise()
_dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10)
hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd
if not _dt_search_and_open(hwnd, search_keyword, verify_keyword):
raise RuntimeError("打开联系人会话失败")
_dt_focus_input_box(hwnd)
time.sleep(0.3)
pyperclip.copy(text)
pyautogui.hotkey('ctrl', 'v')
time.sleep(0.2)
pyautogui.press('enter')
logger.info("发送成功:%s...", text[:30])
return True
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("重试 %d 次后失败" % _DT_RETRY_TIMES)
def send_dingtalk_text(search_keyword, text, verify_keyword=None):
"""推送文本到钉钉联系人(OCR 视觉方案,仅单聊)。供业务脚本 import 调用。
search_keyword 为搜索关键字(支持工号);verify_keyword 为会话标题校验关键字(可选,同名人传姓名)。
群消息请改用 dingtalk_robot(钉钉群机器人 webhook)推送。
"""
return _dt_send_text_to_person(search_keyword, text, verify_keyword)
# ==================== 影刀自定义指令入口 ====================
def main(messages, record_dir=""):
"""
影刀自定义指令「37du钉钉推送」调用入口。
直接传列表,每项为 (search_keyword, text, verify_keyword) 元组,verify_keyword 可省略:
search_keyword 联系人搜索关键字(支持工号,避免同名误选)
text 要发送的消息内容
verify_keyword 会话校验关键字(可选;钉钉标题显示姓名,用工号搜索时传姓名校验)
record_dir(可选):推送记录保存目录,非空时每次推送结果写入
<record_dir>/YYYY-MM-DD/推送记录.csv(列=推送时间, 工号, 姓名, 结果, 消息摘要);
空串=不记录。由调用方按场景传入,不写死(本指令供所有场景复用)。
仅推送联系人(单聊);群消息请改用 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
每次推送自动写入推送记录(见模块头说明);推送记录文件路径写入全局变量 push_record_path,
由流程自行读取记录文件处理失败名单。
返回: {"success": bool, "message": str, "results": [...]}
"""
results = []
_total_start = time.time()
for item in messages:
search_keyword = str(item[0] or "").strip()
text = str(item[1] or "")
verify_keyword = str(item[2] or "").strip() or None if len(item) > 2 else None
name = verify_keyword or search_keyword
if not text.strip():
results.append({"success": False, "message": "参数 text 不能为空"})
_dt_record_push(search_keyword, name, "失败", text,
error="参数 text 不能为空", record_dir=record_dir)
continue
if not search_keyword:
results.append({"success": False, "message": "参数 search_keyword 不能为空"})
_dt_record_push(search_keyword, name, "失败", text,
error="参数 search_keyword 不能为空", record_dir=record_dir)
continue
_t_start = time.time()
try:
send_dingtalk_text(search_keyword, text, verify_keyword)
_t_cost = time.time() - _t_start
logger.info("本条推送耗时 %.1f 秒(%s)", _t_cost, search_keyword)
results.append({"success": True, "message": f"已向 {search_keyword} 发送成功",
"cost_sec": round(_t_cost, 1)})
_dt_record_push(search_keyword, name, "成功", text, record_dir=record_dir)
except Exception as e:
_t_cost = time.time() - _t_start
logger.error("本条推送失败,耗时 %.1f 秒(%s):%s", _t_cost, search_keyword, e)
results.append({"success": False, "message": str(e), "cost_sec": round(_t_cost, 1)})
_dt_record_push(search_keyword, name, "失败", text, error=str(e), record_dir=record_dir)
_total_cost = time.time() - _total_start
logger.info("全部推送完成,总耗时 %.1f 秒,共 %d 条", _total_cost, len(results))
ok = sum(1 for r in results if r.get("success"))
# 推送记录文件路径写入影刀全局变量,由流程自行读取记录文件处理失败名单
_dt_write_record_path_to_glv(record_dir)
return {
"success": ok == len(results),
"message": f"共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}",
"results": results,
}
if __name__ == "__main__":
messages = [("37036361", "【37du钉钉推送·测试1】你好,这是一条连通性测试消息。", "夏一平"),("37036361", "【37du钉钉推送·测试2】你好,这是第二条测试消息。", "夏一平")]
# 本地自测:传记录目录则写入推送记录;留空则不记录
print(main(messages, record_dir="D:\资料\人资\考勤异常\推送记录"))