refactor: 重构雇主险业务,适配多类别拆分与影刀脚本整合
1. 重构ehr/common/config.py与employer_insurance/config.py,新增多类别配置与工具函数 2. 重写employer_insurance.py,支持按类别调度处理 3. 新增影刀共享模块与业务脚本,统一RPA开发规范 4. 移除旧版冗余的影刀脚本文件
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_robot.py
|
||||
@Description: 钉钉群机器人推送(影刀自定义指令模块源码,单一真源)。
|
||||
使用方式:main("需要推送的通知文本") 即可,标题/颜色等均可选。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_robot,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加一个流程参数(文本类型,如 text),并勾选「参数可见」;
|
||||
4. 保存并「发版」;在需要钉钉群推送的应用中「获取指令」并安装;
|
||||
5. 流程中拖入该指令,把业务脚本输出的文本直接传给 text 参数即可。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 影刀运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
|
||||
「默认配置」区(单一真源),改推送目标时改常量即可;
|
||||
- 页脚署名默认 "小芒 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受。
|
||||
|
||||
入口:
|
||||
main(text, title='消息通知', status='info', webhook='', secret='', server_name='')
|
||||
第一个参数传通知文本即可,其余可选。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 默认配置(改推送目标改这里) ====================
|
||||
DEFAULT_WEBHOOK = (
|
||||
'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
)
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '小芒 任务调度平台'
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
|
||||
# 通知状态 → 标题颜色
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,多行内容转引用块,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n内容详情:\n"
|
||||
for line in content.strip().splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
# 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示
|
||||
text += f"> {line} \n"
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
text += f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name=''):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉群机器人推送」调用入口。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
webhook: 机器人 webhook(缺省用内联默认值)
|
||||
secret: 加签密钥(缺省用内联默认值)
|
||||
server_name: 页脚署名(缺省用内联默认值)
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if not text or not str(text).strip():
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
robot.send(str(title), str(text), status=status, server_name=server_name)
|
||||
return {'success': True, 'message': f'已推送通知 [{status}]:{title}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
text = '测试消息:钉钉机器人连接正常。'
|
||||
print(main(text))
|
||||
@@ -0,0 +1,588 @@
|
||||
# -*- 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),或分别增加 target/text 两个参数;
|
||||
4. 保存并「发版」;在需要钉钉推送的应用中「获取指令」并安装;
|
||||
5. 在流程中拖入该指令,把业务脚本输出的参数传入(两种方式任选):
|
||||
方式A(推荐):流程中先拼一个字典变量(如 {"target": "张三", "text": "..."}),
|
||||
作为 params 整体传入;
|
||||
方式B:分别传 target、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 = {
|
||||
"target": "联系人搜索关键字(支持工号,避免同名误选)",
|
||||
"text": "要发送的文本内容",
|
||||
"display_name": "会话标题校验名(可选;钉钉标题显示姓名,target 用工号时传姓名校验)",
|
||||
}
|
||||
通过流程参数传入(支持整字典 params 或分别传 target/text)
|
||||
messages 批量模式下,消息含 target 走 OCR 单聊;不含 target 视为群消息,
|
||||
自动改由钉钉群机器人(dingtalk_robot)webhook 推送。
|
||||
返回 JSON 安全 dict:{"success": bool, "message": str}
|
||||
|
||||
python dingtalk_sender.py 目标 文本 独立运行(等价于 main({"target": ..., "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, target_name, verify_name=None):
|
||||
"""搜索并打开指定联系人的会话(仅单聊;群消息改用钉钉群机器人 webhook 推送)。
|
||||
|
||||
target_name 为搜索关键字(支持工号,避免同名人员误选,如搜索 10086);
|
||||
verify_name 为打开会话后校验标题用的名称(钉钉会话标题显示的是联系人姓名
|
||||
而非工号,故同名人场景需传姓名用于校验;不传则回退为 target_name)。
|
||||
"""
|
||||
_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(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 _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_name or target_name):
|
||||
logger.info("成功进入会话 '%s'", verify_name or target_name)
|
||||
return True
|
||||
_dt_activate_window(hwnd)
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到会话名 '%s'", verify_name or target_name)
|
||||
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(name, text, display_name=None):
|
||||
"""向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。
|
||||
name 为搜索关键字(支持工号);display_name 为会话标题校验名(钉钉标题显示姓名,
|
||||
同名人时传姓名用于校验;不传则用 name 校验),二者分离避免同名误选。
|
||||
"""
|
||||
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, name, display_name):
|
||||
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(target, text, display_name=None):
|
||||
"""推送文本到钉钉联系人(OCR 视觉方案,仅单聊)。供业务脚本 import 调用。
|
||||
target 为搜索关键字(支持工号);display_name 为会话标题校验名(可选,同名人传姓名)。
|
||||
群消息请改用 dingtalk_robot(钉钉群机器人 webhook)推送。
|
||||
"""
|
||||
return _dt_send_text_to_person(target, text, display_name)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def _send_one(msg):
|
||||
"""发送单条消息,返回 {success: bool, message: str}。msg 为 {target?, text, display_name?} 字典。
|
||||
|
||||
- 含 target:钉钉联系人 OCR 推送(单聊);
|
||||
- 不含 target:视为群消息,改用钉钉群机器人(webhook)推送(替换原 OCR 群聊)。
|
||||
"""
|
||||
target = str((msg or {}).get("target", "") or "").strip()
|
||||
text = str((msg or {}).get("text", "") or "")
|
||||
display_name = str((msg or {}).get("display_name", "") or "").strip() or None
|
||||
if not text.strip():
|
||||
return {"success": False, "message": "参数 text 不能为空"}
|
||||
if not target:
|
||||
# 群消息:交由钉钉群机器人(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(target, text, display_name)
|
||||
return {"success": True, "message": f"已向 {target} 发送成功"}
|
||||
except Exception as e:
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉推送」调用入口。
|
||||
args: dict,通过流程变量传入(影刀变量支持传字典/列表):
|
||||
方式A(批量,推荐):args = {"messages": [{target?, text, display_name?}, ...]}
|
||||
messages 为「字典列表」,逐条发送并返回汇总结果;
|
||||
含 target 走 OCR 单聊;不含 target 视为群消息,改用钉钉群机器人推送;
|
||||
方式B(单条):args = {"params": {target, text}} 或
|
||||
{"target":..., "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__":
|
||||
# 仅本地自测连通性。影刀中会直接调用 main(args) 并通过流程变量传参,不会走这里。
|
||||
# 批量测试:流程变量 messages = 字典列表,含 target 走 OCR 单聊;
|
||||
# 不含 target 视为群消息,交由钉钉群机器人(webhook)推送。
|
||||
_messages = [
|
||||
{"target": "夏一平", "text": "【37du钉钉推送·测试1】你好,这是一条连通性测试消息。"},
|
||||
{"target": "夏一平", "text": "【37du钉钉推送·测试2】你好,这是第二条测试消息。"},
|
||||
{"text": "【37du钉钉推送·群消息测试】你好,这是一条群机器人测试消息。"},
|
||||
]
|
||||
result = main({"messages": _messages})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,448 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
环境变量(.env 或系统变量):
|
||||
hr_login_url=HR 登录页 URL
|
||||
hr_target_url_keyword=HR 登录成功后 URL 关键字
|
||||
hr_login_username=用户名
|
||||
hr_login_password=密码
|
||||
hr_validate_url=(可选)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 注意:必须在读取环境变量前先加载 .env,否则 import 时这些值会被捕获为 None
|
||||
_load_shared_env()
|
||||
LOGIN_URL = os.getenv('hr_login_url')
|
||||
SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword')
|
||||
USERNAME = os.getenv('hr_login_username')
|
||||
PASSWORD = os.getenv('hr_login_password')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
if bg_img is None or slider_color is None:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
# ================== 轨迹生成与滑动 ==================
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry + 1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
continue
|
||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 hr_login_url / hr_target_url_keyword 环境变量", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 hr_login_username / hr_login_password 环境变量", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,243 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login.py
|
||||
@Description: OA 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duOA登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 OA 系统影刀脚本(请假/加班/社保增减等)复用。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 oa_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 SessionPage / requests.Session。
|
||||
|
||||
环境变量(.env 或系统变量):
|
||||
oa_login_url=OA 登录页 URL
|
||||
oa_target_url_keyword=OA 登录成功后 URL 关键字
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
oa_validate_url=(可选)轻量会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 注意:必须在读取环境变量前先加载 .env,否则 import 时这些值会被捕获为 None
|
||||
_load_shared_env()
|
||||
LOGIN_URL = os.getenv('oa_login_url')
|
||||
SUCCESS_KEYWORD = os.getenv('oa_target_url_keyword')
|
||||
USERNAME = os.getenv('oa_login_username')
|
||||
PASSWORD = os.getenv('oa_login_password')
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
|
||||
TIMEOUT = 10
|
||||
WAIT_AFTER_LOAD = 2
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化 ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
|
||||
与业务脚本(overtime_approval/leave_approval/social_change 等)使用同一套接口与校验逻辑:
|
||||
requests.Session + Chrome UA + 仅注入 37du.co 域 cookies,GET method=sumTodoCount。
|
||||
"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 cookies。"""
|
||||
page = ChromiumPage()
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele(USERNAME_INPUT)
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(USERNAME)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele(PASSWORD_INPUT)
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(PASSWORD)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele(LOGIN_BTN)
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
page.wait(0.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
print(f"登录失败,提示: {error_elem.text}")
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 oa_login_url / oa_target_url_keyword 环境变量", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 oa_login_username / oa_login_password 环境变量", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": True})
|
||||
print("最终结果:", result)
|
||||
Reference in New Issue
Block a user