Files
37duAutomation/yingdao/share/dingtalk_sender.py
T
puddy 9e61206be2 feat: 启用考勤异常直接推送,重构钉钉推送适配逻辑
1.  启用app版考勤异常推送:移除push_abnormal中的注释,直接调用钉钉推送接口,不再仅打印日志
2.  更新钉钉推送文档与适配逻辑:
    - 重构dingtalk_sender参数为search_keyword/verify_keyword替代target/display_name
    - 更新考勤异常推送分组与参数格式,适配新的OCR推送逻辑
3.  移除影刀审批脚本的单聊推送支持,统一使用群机器人推送
4.  优化缺勤分析缓存逻辑,移除历史月缓存限制,改用懒加载缓存
5.  为影刀考勤异常脚本新增联调测试模式,避免联调期间打扰真实员工
2026-08-23 12:50:29 +08:00

589 lines
22 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 -*-
"""
@FileName: dingtalk_sender.py
@Description: 钉钉联系人推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
作为「37du钉钉推送」影刀自定义指令的模块源码,
供所有需要钉钉单人推送的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
避免每个脚本各自内联 OCR 视觉发送逻辑。
仅推送「联系人」(单聊);群消息已改用钉钉群机器人(webhook)推送,
见同目录 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
如何在影刀中创建指令:
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_sender,添加 Python 模块;
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
3. 增加流程参数 params(字典类型,dict),或分别增加 search_keyword/verify_keyword/text 三个参数;
4. 保存并「发版」;在需要钉钉推送的应用中「获取指令」并安装;
5. 在流程中拖入该指令,把业务脚本输出的参数传入(两种方式任选):
方式A(推荐):流程中先拼一个字典变量(如 {"search_keyword": "10086", "verify_keyword": "张三", "text": "..."}),
作为 params 整体传入;
方式B:分别传 search_keyword、verify_keyword、text 变量,指令内部自动拼成字典;
指令返回 JSON:{"success": bool, "message": str},可在后续流程中判断是否重试。
推送原理(OCR 视觉方案,与 app/utils/dingtalk_sender.py 一致):
查找钉钉窗口 → 多策略激活到前台 → Ctrl+Shift+F 搜索联系人 → OCR 定位输入框
→ 粘贴文本 → 回车发送。
依赖(影刀「Python包管理」安装;启动校验不懒加载):
pip install pyautogui pywin32 pyperclip psutil
pip install Pillow numpy rapidocr-onnxruntime
入口:
main(args) 影刀自定义指令调用入口
args = {
"search_keyword": "联系人搜索关键字(支持工号,避免同名误选)",
"verify_keyword": "会话校验关键字(钉钉标题显示姓名,用工号搜索时传姓名校验)",
"text": "要发送的消息内容",
}
通过流程参数传入(支持整字典 params 或分别传 search_keyword/verify_keyword/text)
messages 批量模式下,消息含 search_keyword 走 OCR 单聊;不含则视为群消息,
自动改由钉钉群机器人(dingtalk_robot)webhook 推送。
返回 JSON 安全 dict:{"success": bool, "message": str}
python dingtalk_sender.py 搜索关键词 消息内容 独立运行(等价于 main({"search_keyword": ..., "text": ...}))
"""
import sys
import time
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
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_onnxruntime 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()
# ==================== 钉钉 OCR 视觉推送(单一真源,与 app/utils/dingtalk_sender.py 一致) ====================
_DT_TIMEOUT = 8
_DT_SEARCH_RETRY = 3
_DT_RETRY_TIMES = 3
_DT_TOP_HEIGHT_RATIO = 0.18
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
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):
"""强制激活窗口(最小化、隐藏、托盘均可恢复)。"""
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 _dt_get_window_rect(hwnd):
return win32gui.GetWindowRect(hwnd)
def _dt_is_dingtalk_main_visible():
hwnd = _dt_find_dingtalk_window(include_hidden=True)
return bool(hwnd) and win32gui.IsWindowVisible(hwnd)
def _dt_is_dingtalk_foreground():
fg = win32gui.GetForegroundWindow()
if not fg:
return False
title = win32gui.GetWindowText(fg) or ""
return '钉钉' in title or 'DingTalk' in title
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:
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)))
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_wait_for_tab(hwnd, expected_tab, timeout=_DT_TIMEOUT):
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))
start = time.time()
while time.time() - start < timeout:
img = _dt_capture_region(left, top, width, top_height)
ocr_data = _dt_ocr_image(img)
if _dt_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 _dt_is_chat_opened(hwnd, target_name):
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)
ocr_data = _dt_ocr_image(img)
for text, _ in ocr_data:
if target_name in text:
logger.debug("标题识别到: '%s'", text)
return True
return False
def _dt_search_and_open(hwnd, search_keyword, verify_keyword=None):
"""搜索并打开指定联系人的会话(仅单聊;群消息改用钉钉群机器人 webhook 推送)。
search_keyword 为搜索关键字(支持工号,避免同名人员误选,如搜索 10086);
verify_keyword 为打开会话后校验标题用的关键字(钉钉会话标题显示的是联系人姓名
而非工号,故同名人场景需传姓名用于校验;不传则回退为 search_keyword)。
"""
_dt_activate_window(hwnd)
for attempt in range(_DT_SEARCH_RETRY):
pyautogui.hotkey('ctrl', 'shift', 'f')
time.sleep(0.8)
pyautogui.hotkey('ctrl', 'a')
pyautogui.press('delete')
pyperclip.copy(search_keyword)
pyautogui.hotkey('ctrl', 'v')
time.sleep(0.5)
pyautogui.press('enter')
logger.info("搜索 '%s' (尝试 %d)", search_keyword, attempt + 1)
time.sleep(0.8)
if _dt_wait_for_tab(hwnd, "联系人", timeout=3):
break
else:
pyautogui.press('esc')
time.sleep(0.5)
else:
logger.error("搜索框未正常打开")
return False
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)
ocr_data = _dt_ocr_image(img)
pos = _dt_find_text_center(ocr_data, "联系人")
if pos:
cx, cy = pos
pyautogui.click(left + cx, top + cy)
logger.info("点击'联系人'标签")
else:
logger.warning("未识别'联系人'标签")
time.sleep(0.5)
pyautogui.press('enter')
logger.info("打开第一个匹配项")
time.sleep(1.5)
start = time.time()
while time.time() - start < _DT_TIMEOUT:
if _dt_is_chat_opened(hwnd, verify_keyword or search_keyword):
logger.info("成功进入会话 '%s'", verify_keyword or search_keyword)
return True
_dt_activate_window(hwnd)
time.sleep(0.5)
logger.warning("未检测到会话名 '%s'", verify_keyword or search_keyword)
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):
input_pos = _dt_find_input_box_by_ocr(hwnd)
if input_pos:
pyautogui.click(input_pos[0], input_pos[1])
return True
left, top, right, bottom = _dt_get_window_rect(hwnd)
width = right - left
height = bottom - top
pyautogui.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_is_dingtalk_activated(hwnd, target_name=None):
try:
left, top, right, bottom = _dt_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 = _dt_capture_region(left, top, width, top_height)
if img is None:
return False
ocr_data = _dt_ocr_image(img)
if target_name:
for text, _ in ocr_data:
if target_name in text:
return True
main_keywords = ["搜索或提问", "消息", "未读", "搜索", "提问"]
for kw in main_keywords:
for text, _ in ocr_data:
if kw in text:
return True
return False
except Exception as e:
logger.warning("激活检测异常: %s", e)
return False
def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
"""多策略确保钉钉窗口激活到前台(快捷键→Win32 API→组合)。"""
def wait_for_valid_rect(hwnd, max_wait=1.5):
end = time.time() + max_wait
while time.time() < end:
left, top, right, bottom = _dt_get_window_rect(hwnd)
if (right - left) > 0 and (bottom - top) > 0:
return True
time.sleep(0.2)
return False
def find_current():
return _dt_find_dingtalk_window(include_hidden=True) or hwnd
def verify(hwnd):
start = time.time()
while time.time() - start < timeout:
if _dt_is_dingtalk_activated(hwnd, target_name=None):
return True
time.sleep(0.5)
return False
if _dt_is_dingtalk_foreground():
logger.info("钉钉已在最前,跳过激活")
return True
if not _dt_is_dingtalk_main_visible():
_dt_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("窗口已可见,跳过切换快捷键(避免将其隐藏)")
logger.info("尝试 Win32 API 激活")
cur = find_current()
if cur:
_dt_activate_window(cur)
if wait_for_valid_rect(cur) and verify(cur):
logger.info("API激活成功")
return True
logger.warning("API后窗口尺寸无效")
logger.info("组合激活")
if not _dt_is_dingtalk_main_visible():
_dt_send_hotkey_to_activate()
time.sleep(0.5)
cur = find_current()
if cur:
_dt_activate_window(cur)
time.sleep(1)
if wait_for_valid_rect(cur) and verify(cur):
logger.info("组合激活成功")
return True
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_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 不能为空")
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 _send_one(msg):
"""发送单条消息,返回 {success: bool, message: str}。msg 为 {search_keyword?, verify_keyword?, text} 字典。
- 含 search_keyword:钉钉联系人 OCR 推送(单聊);
- 不含 search_keyword:视为群消息,改用钉钉群机器人(webhook)推送。
"""
search_keyword = str((msg or {}).get("search_keyword", "") or "").strip()
text = str((msg or {}).get("text", "") or "")
verify_keyword = str((msg or {}).get("verify_keyword", "") or "").strip() or None
if not text.strip():
return {"success": False, "message": "参数 text 不能为空"}
if not search_keyword:
# 群消息:交由钉钉群机器人(webhook)推送
try:
import dingtalk_robot
except ImportError:
return {"success": False, "message": "未加载群机器人模块(dingtalk_robot.py),无法推送群消息"}
try:
return dingtalk_robot.main(text)
except Exception as e:
return {"success": False, "message": f"群机器人推送失败:{e}"}
try:
send_dingtalk_text(search_keyword, text, verify_keyword)
return {"success": True, "message": f"已向 {search_keyword} 发送成功"}
except Exception as e:
return {"success": False, "message": str(e)}
def main(args):
"""
影刀自定义指令「37du钉钉推送」调用入口。
args: dict,通过流程变量传入(影刀变量支持传字典/列表):
方式A(批量,推荐):args = {"messages": [{search_keyword?, verify_keyword?, text}, ...]}
messages 为「字典列表」,逐条发送并返回汇总结果;
含 search_keyword 走 OCR 单聊;不含则视为群消息,改用钉钉群机器人推送;
方式B(单条):args = {"params": {search_keyword, verify_keyword, text}} 或
{"search_keyword":..., "verify_keyword":..., "text":...};
返回: dict
单条: {success: bool, message: str}
批量: {success: bool, message: str, sent: int, failed: int, results: [...]}
"""
if not args:
args = {}
# 兼容「整个字典作为 params 传入」的用法
if isinstance(args.get("params"), dict):
merged = dict(args)
merged.update(args["params"])
args = merged
# 批量:messages 为字典列表,逐条发送
if isinstance(args.get("messages"), list):
results = [_send_one(m) for m in args["messages"]]
ok = sum(1 for r in results if r.get("success"))
return {
"success": ok == len(results),
"message": f"共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}",
"sent": ok,
"failed": len(results) - ok,
"results": results,
}
# 单条发送
return _send_one(args)
if __name__ == "__main__":
args = sys.argv
if len(args) >= 3:
print(_send_one({"search_keyword": args[1], "text": args[2]}))
else:
_messages = [
{"search_keyword": "夏一平", "verify_keyword": "夏一平", "text": "【37du钉钉推送·测试1】你好,这是一条连通性测试消息。"},
{"search_keyword": "夏一平", "verify_keyword": "夏一平", "text": "【37du钉钉推送·测试2】你好,这是第二条测试消息。"},
{"text": "【37du钉钉推送·群消息测试】你好,这是一条群机器人测试消息。"},
]
print(main({"messages": _messages}))