Files
37duAutomation/app/utils/dingtalk_sender.py
T
puddy 947e1d24e6 refactor: 重构审批流程与依赖,新增社保异动模块
1. 新增社保增减名单模块,支持参保/停保名单导出
2. 重构钉钉推送逻辑,先推摘要再按需推送完整报告
3. 优化假期/加班校验的天数比对逻辑,适配半天请假场景
4. 重写排班HTML解析器,兼容新的页面结构并提取班次全称
5. 重构审批报告生成逻辑,新增全量明细展示
6. 重构影刀脚本的日志与依赖管理,新增UI自动化聚焦输入框
7. 更新依赖包,新增uiautomation库支持
2026-08-07 19:40:02 +08:00

492 lines
18 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: 钉钉桌面客户端消息推送工具
通过模拟键盘快捷键 + 剪贴板,向指定群/联系人发送文本和文件
操作链路:Ctrl+D 激活钉钉 → Ctrl+Shift+F 搜索 → 回车确认 → 粘贴文本/文件 → 回车发送
@Version: 1.0.0
依赖安装:
pip install pyautogui pywin32 pyperclip uiautomation
使用前提:
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
try:
import uiautomation as ua
except ImportError:
ua = 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):
"""激活钉钉窗口:先找窗口,托盘中则 Ctrl+D 唤起,win32 置前,点击确保焦点。
若钉钉已在前台则直接返回--Ctrl+D 是 toggle 热键,窗口已显示时再按会把它隐藏,
导致后续发送失败。连续发送时第二次起会命中此分支。
"""
if _is_dingtalk_foreground():
logger.info("钉钉窗口已在前台,跳过激活")
return
# 先尝试找到已打开的钉钉窗口
hwnd = None
try:
hwnd = _find_dingtalk_hwnd()
except RuntimeError:
pass
if hwnd is None:
# 钉钉在系统托盘,用 Ctrl+D 全局热键唤起
pyautogui.hotkey("ctrl", "d")
time.sleep(1.5)
try:
hwnd = _find_dingtalk_hwnd()
except RuntimeError:
raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键")
# 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)
# 点击窗口中心确保键盘焦点落在钉钉上(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)
if _is_dingtalk_foreground():
logger.info("钉钉窗口已激活")
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
win32clipboard.OpenClipboard()
try:
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_HDROP, data)
finally:
win32clipboard.CloseClipboard()
logger.debug("文件已放入剪贴板: %s", abspath)
# ==================== 搜索 & 发送 ====================
def _find_editable_controls(control, result, depth=0, max_depth=15):
"""递归遍历控件树,收集所有可编辑控件(Edit/Document)。"""
if depth > 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 键关闭搜索面板,依赖钉钉将焦点自动移至消息输入框。
"""
if ua is not None:
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
except Exception as e:
logger.debug("UI Automation 聚焦失败: %s", e)
# 回退:钉钉可能失焦,重新确认前台并点击窗口底部消息输入框区域
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 键尝试聚焦")
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 ====================
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()