feat: 新增OA工作沟通推送模块,优化考勤异常查询逻辑与钉钉推送能力
1. 新增OA工作沟通推送全流程模块: - 实现人员搜索、多附件上传、工作沟通提交完整链路 - 提供一键推送入口send_work_communication,支持多接收人、富文本与多类型沟通 - 补充配套配置常量与接口封装 - 添加抓包调试脚本与完整需求/开发文档 2. 考勤异常处理模块重构: - 将默认查询范围从「当月」改为「上周(周一~周日)」 - 统一app/影刀版的日期范围计算逻辑 - 新增班段合成、请假日期修复逻辑,优化导出报表字段 - 更新需求文档与开发文档,同步功能变更 3. 钉钉推送工具优化: - 修复窗口激活逻辑,避免批量推送时抢焦点导致窗口失焦 - 新增安全点击与鼠标状态兜底,防止左键卡死 - 优化搜索与会话打开流程,提升稳定性
|
Before Width: | Height: | Size: 135 KiB After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 155 KiB After Width: | Height: | Size: 108 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 107 KiB After Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 9.5 KiB After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 6.1 KiB After Width: | Height: | Size: 6.3 KiB |
@@ -182,6 +182,22 @@ def _to_minutes(value: Any) -> Optional[int]:
|
||||
return int(m.group(1)) * 60 + int(m.group(2))
|
||||
|
||||
|
||||
def _time_hhmm(value: Any) -> str:
|
||||
"""取日期时间串中的 "HH:MM";无时间部分返回空串。"""
|
||||
if value is None:
|
||||
return ""
|
||||
import re
|
||||
m = re.search(r"(\d{1,2}):(\d{2})", str(value))
|
||||
return f"{int(m.group(1)):02d}:{m.group(2)}" if m else ""
|
||||
|
||||
|
||||
def _shift_segment(rec: Dict[str, Any]) -> str:
|
||||
"""合成异常记录的班段 "HH:MM ~ HH:MM"(begin_time ~ end_time,区分同一日多班段异常)。"""
|
||||
b = _time_hhmm(_get(rec, "begin_time"))
|
||||
e = _time_hhmm(_get(rec, "end_time"))
|
||||
return f"{b} ~ {e}" if b or e else ""
|
||||
|
||||
|
||||
def _parse_shift_time(bc_time: str) -> Tuple[Optional[int], Optional[int]]:
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。"""
|
||||
if not bc_time:
|
||||
@@ -322,8 +338,10 @@ def _build_leave_set(leaves: List[Dict[str, Any]], need_full_day: bool = False)
|
||||
index: Dict[Tuple[str, str], Dict] = {}
|
||||
for rec in leaves:
|
||||
code = str(_get(rec, "base_code")).strip()
|
||||
start = _to_date_str(_get(rec, "start_time", "begin_date"))
|
||||
end = _to_date_str(_get(rec, "end_time", "end_date"))
|
||||
# 用 begin_date/end_date(考勤归属日期)而非 start_time/end_time:
|
||||
# 跨天夜班请假 end_time 会落到次日,导致请假范围多算一天
|
||||
start = _to_date_str(_get(rec, "begin_date", "start_time"))
|
||||
end = _to_date_str(_get(rec, "end_date", "end_time"))
|
||||
leave_days = _float(rec.get("leave_days"))
|
||||
if not code or not start or not end:
|
||||
continue
|
||||
@@ -367,8 +385,8 @@ def check_leave_after_confirm(abnormal_confirmed: List[Dict[str, Any]],
|
||||
"考勤日期": work_day,
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假起止": f"{_to_date_str(_get(leave_rec, 'start_time', 'begin_date'))} ~ "
|
||||
f"{_to_date_str(_get(leave_rec, 'end_time', 'end_date'))}",
|
||||
"请假起止": f"{_to_date_str(_get(leave_rec, 'begin_date', 'start_time'))} ~ "
|
||||
f"{_to_date_str(_get(leave_rec, 'end_date', 'end_time'))}",
|
||||
"问题说明": "该日期已确认考勤异常,但同时存在请假流程,可能为「提前确认后请假」仍为异常",
|
||||
})
|
||||
return rows
|
||||
@@ -467,6 +485,7 @@ def check_full_day_leave_abnormal(abnormal_confirmed: List[Dict[str, Any]],
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假天数": _get(leave_rec, "leave_days"),
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"班段": _shift_segment(ab),
|
||||
"异常状态": status,
|
||||
"提示": hint,
|
||||
})
|
||||
@@ -495,7 +514,8 @@ def export_report(results: Dict[str, List[Dict[str, Any]]], save_dir: str, month
|
||||
"员工姓名", "工号", "加班日期", "加班天数", "排班班次", "排班班段时间", "计划时段",
|
||||
"上班打卡", "下班打卡", "打卡次数", "判定"]),
|
||||
("检查3_整日请假有异常", "check3", [
|
||||
"员工姓名", "工号", "请假日期", "请假类型", "请假天数", "异常类型", "异常状态", "提示"]),
|
||||
"员工姓名", "工号", "请假日期", "请假类型", "请假天数", "异常类型", "班段",
|
||||
"异常状态", "提示"]),
|
||||
]
|
||||
|
||||
c1 = results.get("check1", [])
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-10
|
||||
@Description: 考勤异常查询与导出:通过员工基础信息接口(getCurUserInfo)校验 cookies 有效性,
|
||||
再调用考勤异常接口分页拉取【当月】全部考勤异常数据,导出为 Excel;
|
||||
再调用考勤异常接口分页拉取【上周(周一~周日)】全部考勤异常数据,导出为 Excel;
|
||||
并按规则(迟到/早退 >=30 分钟,或其他类型异常)向对应员工推送钉钉核实通知;
|
||||
仅推送 first_type_name 含「职能」的人员,且按「姓名-工号」合并为一人一条,减少推送次数。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@@ -14,12 +14,12 @@
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可查询当月考勤异常并导出 Excel。
|
||||
2. 直接运行本文件即可查询上周(周一~周日)考勤异常并导出 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
@@ -87,15 +87,18 @@ IS_ADJUSTED = "0"
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 当月查询范围(每次默认查询当月)
|
||||
# 1. 上周查询范围(每次默认查询上周一~上周日)
|
||||
# ----------------------------------------------
|
||||
def current_month_range(today: date = None) -> tuple:
|
||||
"""返回当月的查询日期范围,返回 (开始日期, 结束日期)。
|
||||
开始日期 = 当月 1 日,结束日期 = 今天。
|
||||
def last_week_range(today: date = None) -> tuple:
|
||||
"""返回上周(周一~周日)的查询日期范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
上周定义:本周一往前推 7 天为上周一,上周一 + 6 天为上周日。
|
||||
"""
|
||||
today = today or date.today()
|
||||
begin = today.replace(day=1)
|
||||
return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
this_monday = today - timedelta(days=today.weekday()) # 本周一
|
||||
last_monday = this_monday - timedelta(days=7)
|
||||
last_sunday = this_monday - timedelta(days=1)
|
||||
return last_monday.strftime("%Y-%m-%d"), last_sunday.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
@@ -250,14 +253,14 @@ def _fetch_abnormal_data(month: str = None) -> tuple:
|
||||
# 校验 cookies 有效性,并获取查询所需 user_id / treecode
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
|
||||
# 计算查询范围:默认当月
|
||||
# 计算查询范围:默认上周(周一~周日)
|
||||
if month:
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
month_str = month
|
||||
else:
|
||||
begin, end = current_month_range()
|
||||
month_str = date.today().strftime("%Y-%m")
|
||||
begin, end = last_week_range()
|
||||
month_str = end[:7] # 文件名月份标识取上周日所在月
|
||||
logger.info("===== 查询考勤异常日期范围:%s ~ %s,调整状态:%s =====",
|
||||
begin, end, IS_ADJUSTED or "所有")
|
||||
|
||||
@@ -335,13 +338,13 @@ def download_attendance_abnormal(save_dir: str = None, month: str = None) -> str
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM"(默认当月)。传该参数时查询整个月,
|
||||
不传则按「当月 1 日 至 今天」查询。
|
||||
month: 查询月份 "YYYY-MM"(默认上周)。传该参数时查询整个月,
|
||||
不传则按「上周一 至 上周日」查询。
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
data, month_str = _fetch_abnormal_data(month)
|
||||
if not data:
|
||||
logger.info("当月无考勤异常数据")
|
||||
logger.info("上周无考勤异常数据")
|
||||
return None
|
||||
return export_excel(data, save_dir, month_str)
|
||||
|
||||
@@ -354,7 +357,7 @@ def handle_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM"(默认当月)
|
||||
month: 查询月份 "YYYY-MM"(默认上周)
|
||||
|
||||
Returns:
|
||||
导出文件路径(无数据时返回 None)
|
||||
@@ -362,7 +365,7 @@ def handle_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
data, month_str = _fetch_abnormal_data(month)
|
||||
if not data:
|
||||
logger.info("当月无考勤异常数据,跳过导出与推送")
|
||||
logger.info("上周无考勤异常数据,跳过导出与推送")
|
||||
return None
|
||||
|
||||
path = export_excel(data, save_dir, month_str)
|
||||
@@ -377,7 +380,7 @@ def handle_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||||
if month:
|
||||
confirm_begin, confirm_end = f"{month}-01", f"{month}-31"
|
||||
else:
|
||||
confirm_begin, confirm_end = current_month_range()
|
||||
confirm_begin, confirm_end = last_week_range()
|
||||
mild_count = len([it for it in handled_list if it.get("abnormal_id")])
|
||||
if AUTO_CONFIRM_ENABLED:
|
||||
confirmed_count = auto_confirm_mild(handled_list, session=session)
|
||||
@@ -418,7 +421,7 @@ def main() -> None:
|
||||
if out:
|
||||
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
|
||||
else:
|
||||
logger.info("===== 考勤异常处理完成:当月无数据 =====")
|
||||
logger.info("===== 考勤异常处理完成:上周无数据 =====")
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
# 文件被 Excel 占用:只提醒关闭后重试,不抛堆栈
|
||||
|
||||
@@ -20,6 +20,42 @@ TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||
FD_TYPE = "13"
|
||||
|
||||
# ---------- 工作沟通推送接口(oa 域名) ----------
|
||||
# 人员搜索接口:按工号/姓名模糊搜索,返回人员 XML(<data id=.. name=..>)
|
||||
PERSON_SEARCH_URL = f"{BASE_URL}/sys/common/dataxml.jsp"
|
||||
# 附件上传接口:getuserkey / submit 两步共用
|
||||
ATT_UPLOAD_URL = f"{BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
|
||||
# 附件二进制上传接口
|
||||
ATT_UPLOADER_URL = f"{BASE_URL}/sys/attachment/uploaderServlet"
|
||||
# 工作沟通提交接口(新建保存走 method=save&s_seq=1,真实抓包确认;aa.md 中 user.jsp 为错误端点)
|
||||
WORK_COMMUNICATION_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 新建工作沟通页面:method=add 返回表单页,其中含新建草稿 fdId 与通知方式随机字段 __notify_type_<id>
|
||||
WORK_COMMUNICATION_ADD_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do?method=add"
|
||||
# 保存工作沟通:POST 表单字段(application/x-www-form-urlencoded),成功返回「操作成功」提示页
|
||||
KM_COLLABORATE_SAVE_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 沟通内容 fdContent 序列化前缀:真实格式为 固定前缀 + {base64(HTML)}(前缀为抓包确认的固定字节)
|
||||
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
|
||||
# 沟通类型(fdCategoryId 必填 validate=required),全部类型如下,调用方可任选,默认「工作安排」
|
||||
FD_CATEGORY_COMMUNICATION = "15e4c970dd59cd559f096644cecadbc7" # 工作交流
|
||||
FD_CATEGORY_INFO = "15e4c980ff72365007fc1a741ceb0c7d" # 信息传递
|
||||
FD_CATEGORY_WORK_ARRANGE = "17646e8283a07a43be3003d485492a4f" # 工作安排
|
||||
FD_CATEGORY_PROJECT = "1767a1195ec34b0de7d53764c84812f1" # 项目沟通
|
||||
FD_CATEGORY_REMINDER = "17efb81557d1e74c532aa78407a95189" # 温馨提示
|
||||
FD_CATEGORY_OTHER = "15e4c985cd9a92cc54cb20c413d9b29e" # 其他
|
||||
# 沟通类型映射:名称 -> ID(submit 时支持直接传中文名)
|
||||
FD_CATEGORY_MAP = {
|
||||
"工作交流": FD_CATEGORY_COMMUNICATION,
|
||||
"信息传递": FD_CATEGORY_INFO,
|
||||
"工作安排": FD_CATEGORY_WORK_ARRANGE,
|
||||
"项目沟通": FD_CATEGORY_PROJECT,
|
||||
"温馨提示": FD_CATEGORY_REMINDER,
|
||||
"其他": FD_CATEGORY_OTHER,
|
||||
}
|
||||
# 默认沟通类型:工作安排
|
||||
FD_CATEGORY_DEFAULT = FD_CATEGORY_WORK_ARRANGE
|
||||
# 工作沟通(协作)业务模型名:附件绑定与沟通提交共用
|
||||
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
|
||||
|
||||
# OA 流程接口(hr 域名)
|
||||
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
|
||||
@@ -35,6 +35,11 @@ from app.service.hrbp.oa.common.oa_api.punch import (
|
||||
fetch_punch_record_page,
|
||||
get_punch_records,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.work_communication import (
|
||||
search_person,
|
||||
upload_attachment,
|
||||
submit_work_communication,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"oa_request_json",
|
||||
@@ -52,4 +57,7 @@ __all__ = [
|
||||
"get_leave_records",
|
||||
"fetch_punch_record_page",
|
||||
"get_punch_records",
|
||||
"search_person",
|
||||
"upload_attachment",
|
||||
"submit_work_communication",
|
||||
]
|
||||
|
||||
@@ -45,6 +45,7 @@ def oa_request_json(
|
||||
params: dict,
|
||||
label: str,
|
||||
timeout: int = 20,
|
||||
headers: dict = None,
|
||||
):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验状态码/JSON → 返回解析后的 JSON。
|
||||
|
||||
@@ -55,6 +56,8 @@ def oa_request_json(
|
||||
params: 请求参数
|
||||
label: 接口中文名(用于报错信息)
|
||||
timeout: 请求超时秒数,默认 20
|
||||
headers: 附加请求头(显式传入可规避 DrissionPage 对 session 级
|
||||
Referer 头的 KeyError 问题),可空
|
||||
|
||||
Returns:
|
||||
解析后的 JSON 字典
|
||||
@@ -63,7 +66,7 @@ def oa_request_json(
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
if method.upper() == "GET":
|
||||
session.get(url, params=params, timeout=timeout)
|
||||
session.get(url, params=params, timeout=timeout, headers=headers)
|
||||
else:
|
||||
session.post(url, data=params, timeout=timeout)
|
||||
session.post(url, data=params, timeout=timeout, headers=headers)
|
||||
return _handle_response(session.response, label)
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: work_communication.py
|
||||
@Description: OA 工作沟通推送接口:搜索接收人 / 上传附件 / 提交工作沟通。
|
||||
对应需求文档 aa.md(OA工作沟通自动化发送)。
|
||||
附件上传采用「普通上传」流程(getuserkey → 二进制上传 → submit 绑定),
|
||||
暂不实现 MD5 秒传(文件已存在时也走完整上传,保证可用性,后续需要再优化)。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import base64
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
BASE_URL,
|
||||
PERSON_SEARCH_URL,
|
||||
ATT_UPLOAD_URL,
|
||||
ATT_UPLOADER_URL,
|
||||
WORK_COMMUNICATION_ADD_URL,
|
||||
KM_COLLABORATE_SAVE_URL,
|
||||
FD_CONTENT_PREFIX,
|
||||
FD_CATEGORY_MAP,
|
||||
FD_CATEGORY_DEFAULT,
|
||||
KM_COLLABORATE_MODEL,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json, OALoginExpiredError
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 附件二进制上传时的请求头(Referer 指向 OA 根地址,避免被服务端拦截)
|
||||
_DEFAULT_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Referer": f"{BASE_URL}/",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
|
||||
def _check_response(resp, label: str):
|
||||
"""校验响应:存在性 / 状态码 / 登录态。供返回 XML 或纯文本等非 JSON 的接口使用。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或状态码异常
|
||||
OALoginExpiredError: 会话失效(接口被重定向到登录页返回 HTML)
|
||||
"""
|
||||
if not resp:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
return resp
|
||||
|
||||
|
||||
def search_person(session: SessionPage, keyword: str, org_type: str = "15") -> Optional[tuple]:
|
||||
"""
|
||||
按工号或姓名搜索人员,返回 (person_id, person_name)。
|
||||
|
||||
- 精确匹配优先:姓名或 ID 与关键字完全一致时直接命中;
|
||||
- 模糊命中多个时默认取第一个,并记录警告。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
keyword: 工号或姓名(支持模糊)
|
||||
org_type: 组织类型,默认 "15"(与 aa.md 一致)
|
||||
|
||||
Returns:
|
||||
(person_id, person_name) 元组;未找到返回 None
|
||||
|
||||
Raises:
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
params = {
|
||||
"s_bean": "organizationDialogSearch",
|
||||
"orgType": org_type,
|
||||
"deptLimit": "",
|
||||
"isExternal": "",
|
||||
"key": keyword,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
session.get(PERSON_SEARCH_URL, params=params, timeout=20)
|
||||
resp = _check_response(session.response, "人员搜索")
|
||||
|
||||
try:
|
||||
root = ET.fromstring(resp.text)
|
||||
except ET.ParseError as e:
|
||||
logger.warning("人员搜索[%s]响应解析失败: %s", keyword, e)
|
||||
return None
|
||||
|
||||
matches = []
|
||||
for node in root.iter("data"):
|
||||
pid = node.get("id")
|
||||
pname = node.get("name")
|
||||
if pid and pname:
|
||||
matches.append((pid, pname))
|
||||
|
||||
if not matches:
|
||||
logger.warning("未搜索到人员: %s", keyword)
|
||||
return None
|
||||
|
||||
# 精确匹配优先(工号/姓名全等)
|
||||
for pid, pname in matches:
|
||||
if keyword in (pid, pname):
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
if len(matches) > 1:
|
||||
logger.warning("关键字[%s]模糊匹配到 %d 人,默认取第一个: %s", keyword, len(matches), matches[0])
|
||||
pid, pname = matches[0]
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
|
||||
def upload_attachment(session: SessionPage, file_path: str) -> str:
|
||||
"""
|
||||
上传单个附件,返回最终附件 ID(attid)。
|
||||
|
||||
普通上传流程(不实现 MD5 秒传,保证可用性):
|
||||
1. 获取 userkey(上传凭证)
|
||||
2. 上传二进制内容,得到 filekey
|
||||
3. submit 绑定附件,得到最终 attid
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
file_path: 附件文件路径(相对路径会自动转绝对路径)
|
||||
|
||||
Returns:
|
||||
最终附件 ID(attid)
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 附件文件不存在
|
||||
RuntimeError: 上传任一步骤失败
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
|
||||
file_name = os.path.basename(file_path)
|
||||
file_size = str(os.path.getsize(file_path))
|
||||
# 按扩展名推断 MIME 类型(aa.md 原实现硬编码 xlsx,这里通用化支持任意附件类型)
|
||||
file_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
||||
last_modified = time.strftime(
|
||||
"%a %b %d %Y %H:%M:%S GMT+0800",
|
||||
time.localtime(os.path.getmtime(file_path)),
|
||||
)
|
||||
# fdSign = Base64(文件名) 并去掉 + / = 字符(与 swf_attachment.js 的 createAttMainInfo 一致)
|
||||
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
|
||||
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
|
||||
|
||||
# 上传三步统一显式带上 UA/Referer 等请求头(不设 session 级 headers,
|
||||
# 避免触发 DrissionPage 4.1.1.4 对 session 级 Referer 头的 KeyError bug)
|
||||
|
||||
# ---- 步骤1:获取 userkey ----
|
||||
params1 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "getuserkey",
|
||||
"format": "json",
|
||||
"filesize": file_size,
|
||||
"md5": "",
|
||||
"fileName": file_name,
|
||||
"isSupportDirect": "false",
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp1 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params1, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
|
||||
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
|
||||
if not userkey:
|
||||
raise RuntimeError(f"获取 userkey 失败: {resp1}")
|
||||
logger.info(" 1. 获取 userkey 成功")
|
||||
|
||||
# ---- 步骤2:上传二进制(userkey 需随请求带上,否则报「附件上传密钥为空」) ----
|
||||
uploader_url = f"{ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
files = {"file": (file_name, open(file_path, "rb"), file_type)}
|
||||
data2 = {
|
||||
"id": "WU_FILE_0",
|
||||
"name": file_name,
|
||||
"type": file_type,
|
||||
"lastModifiedDate": last_modified,
|
||||
"size": file_size,
|
||||
}
|
||||
session.post(uploader_url, data=data2, files=files, timeout=60, headers=_DEFAULT_HEADERS)
|
||||
resp2 = _check_response(session.response, "附件上传-二进制")
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
filekey = None
|
||||
if not filekey:
|
||||
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
|
||||
logger.info(" 2. 二进制上传成功, filekey: %s...", filekey[:16])
|
||||
|
||||
# ---- 步骤3:submit 绑定附件,获取最终 attid ----
|
||||
params3 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "submit",
|
||||
"format": "json",
|
||||
"filekey": filekey,
|
||||
"filename": file_name,
|
||||
"fdKey": "attachment",
|
||||
"fdModelName": KM_COLLABORATE_MODEL,
|
||||
"fdAttType": "byte",
|
||||
"width": "null",
|
||||
"height": "null",
|
||||
"proportion": "true",
|
||||
"fdSign": fd_sign,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp3 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params3, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
|
||||
attid = resp3.get("attid")
|
||||
if str(resp3.get("status")) != "1" or not attid:
|
||||
raise RuntimeError(f"提交绑定附件失败: {resp3}")
|
||||
logger.info(" 3. 提交绑定成功, attid: %s", attid)
|
||||
return attid
|
||||
|
||||
|
||||
def _encode_fd_content(content: str) -> str:
|
||||
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。
|
||||
|
||||
真实抓包确认:CKEditor 保存时 fdContent 形如
|
||||
`䙉堠䵅䉁卅㘴{<base64(HTML)>}`,其中前缀为固定字节,花括号内是内容的 base64。
|
||||
"""
|
||||
return FD_CONTENT_PREFIX + "{" + base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
|
||||
|
||||
|
||||
def _get_add_page_fd_info(session: SessionPage) -> tuple:
|
||||
"""打开新建工作沟通页(method=add),解析出草稿 fdId 与通知方式随机字段名。
|
||||
|
||||
Returns:
|
||||
(fd_id, notify_field_name):fdId 隐藏域值;`__notify_type_<随机id>` 字段名
|
||||
|
||||
Raises:
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
RuntimeError: 页面解析失败
|
||||
"""
|
||||
session.get(WORK_COMMUNICATION_ADD_URL, timeout=20)
|
||||
resp = _check_response(session.response, "新建工作沟通-取页面")
|
||||
html = resp.text or ""
|
||||
m = re.search(r'name="fdId"\s+value="([^"]*)"', html)
|
||||
fd_id = m.group(1) if m else ""
|
||||
m2 = re.search(r'name="(__notify_type_[a-f0-9]+)"', html)
|
||||
notify_field = m2.group(1) if m2 else ""
|
||||
if not fd_id:
|
||||
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
|
||||
logger.info("获取新建草稿 fdId: %s, 通知方式字段: %s", fd_id, notify_field)
|
||||
return fd_id, notify_field
|
||||
|
||||
|
||||
def submit_work_communication(
|
||||
session: SessionPage,
|
||||
receiver_ids: Union[str, List[str]],
|
||||
receiver_names: Union[str, List[str]],
|
||||
subject: str,
|
||||
content: str,
|
||||
attachment_ids: Union[str, List[str]] = None,
|
||||
creator_id: str = None,
|
||||
category_id: str = FD_CATEGORY_DEFAULT,
|
||||
) -> str:
|
||||
"""
|
||||
提交工作沟通(新建),成功返回沟通文档 ID(fdId)。
|
||||
|
||||
真实提交端点:`kmCollaborateMain.do?method=save&s_seq=1`(aa.md 中的 user.jsp 为错误端点)。
|
||||
流程:先打开新建页取草稿 fdId 与通知方式随机字段,再以相同表单结构 POST 保存。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
receiver_ids: 接收人 ID,单个字符串或列表(多个以「;」分号分隔)
|
||||
receiver_names: 接收人姓名,单个字符串或列表(顺序与 ID 一致)
|
||||
subject: 标题
|
||||
content: 内容(支持 HTML 富文本)
|
||||
attachment_ids: 附件 ID(attid),单个字符串或列表(多个以「;」分号分隔),可空
|
||||
creator_id: 创建人(当前操作人)ID,必填
|
||||
category_id: 沟通类型,可传中文名(如「工作安排」)或类型 ID,
|
||||
默认「工作安排」(config.FD_CATEGORY_DEFAULT)
|
||||
|
||||
Returns:
|
||||
沟通文档 ID(fdId,字符串)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺少必填参数
|
||||
RuntimeError: 提交失败
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
if not creator_id:
|
||||
raise ValueError("docCreatorId(creator_id) 必填,请传入当前操作人的用户 ID")
|
||||
|
||||
# 沟通类型:支持中文名 -> ID 映射,空值回退默认「工作安排」(fdCategoryId 必填)
|
||||
if category_id in FD_CATEGORY_MAP:
|
||||
category_id = FD_CATEGORY_MAP[category_id]
|
||||
elif not category_id:
|
||||
category_id = FD_CATEGORY_DEFAULT
|
||||
|
||||
# 真实抓包确认:多人参与人 / 多附件 ID 在表单体里以「;」分号分隔(不是逗号)
|
||||
receiver_ids_str = ";".join(receiver_ids) if isinstance(receiver_ids, list) else receiver_ids
|
||||
receiver_names_str = ";".join(receiver_names) if isinstance(receiver_names, list) else receiver_names
|
||||
if isinstance(attachment_ids, list):
|
||||
attachment_ids_str = ";".join(attachment_ids)
|
||||
else:
|
||||
attachment_ids_str = attachment_ids or ""
|
||||
|
||||
# 1) 打开新建页,取草稿 fdId 与通知方式随机字段
|
||||
fd_id, notify_field = _get_add_page_fd_info(session)
|
||||
|
||||
# 2) 组装保存请求(结构对齐真实抓包的 method=save&s_seq=1 表单体)
|
||||
data = {
|
||||
"fdId": fd_id,
|
||||
"fdNumber": "",
|
||||
"participantIds": receiver_ids_str,
|
||||
"participantNames": receiver_names_str,
|
||||
"docSubject": subject,
|
||||
"fdIsPriority": "",
|
||||
"fdCategoryId": category_id,
|
||||
"fdContent": _encode_fd_content(content),
|
||||
"attachmentForms.attachment.fdModelId": "",
|
||||
"attachmentForms.attachment.extParam": "",
|
||||
"attachmentForms.attachment.fdModelName": KM_COLLABORATE_MODEL,
|
||||
"attachmentForms.attachment.fdKey": "attachment",
|
||||
"attachmentForms.attachment.fdAttType": "",
|
||||
"attachmentForms.attachment.fdMulti": "",
|
||||
"attachmentForms.attachment.deletedAttachmentIds": "",
|
||||
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
|
||||
"__landray_fileattachment": "",
|
||||
"fdNotifyType": "todo",
|
||||
"__notify_type_placeholder": "todo", # 占位,下方替换为真实随机字段名
|
||||
"_fdPartnerOperating": "true",
|
||||
"fdPartnerOperating": "true",
|
||||
"fdIsOnlyView": "false",
|
||||
"fdIsReminders": "false",
|
||||
"fdRemindersDay_hidden": "",
|
||||
"fdRemindersDay": "2",
|
||||
"docCreatorId": creator_id,
|
||||
}
|
||||
if notify_field:
|
||||
data[notify_field] = data.pop("__notify_type_placeholder")
|
||||
else:
|
||||
data.pop("__notify_type_placeholder", None)
|
||||
|
||||
# 3) POST 保存
|
||||
session.post(KM_COLLABORATE_SAVE_URL, params={"method": "save", "s_seq": "1"}, data=data, timeout=30)
|
||||
resp = _check_response(session.response, "工作沟通提交")
|
||||
text = resp.text or ""
|
||||
|
||||
# 成功标志:返回「您的操作已成功!」提示页(自动关闭),而非数字 ID
|
||||
if "您的操作已成功" in text:
|
||||
logger.info("工作沟通发送成功, 文档ID: %s", fd_id)
|
||||
return fd_id
|
||||
|
||||
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
|
||||
@@ -0,0 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.work_communication
|
||||
@FileName: work_communication.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-25
|
||||
@Description: OA 工作沟通推送模块(app 版公共模块)。
|
||||
对外提供 send_work_communication 一键推送入口:
|
||||
搜索接收人 -> 上传附件 -> 提交沟通,三个步骤全部成功才算推送成功;
|
||||
任一接收人解析失败或任一附件上传失败即整体失败,不发送部分数据。
|
||||
底层接口见 oa_api/work_communication.py(search_person / upload_attachment / submit_work_communication),
|
||||
可单独调用。需求文档见 aa.md。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用示例:
|
||||
from app.service.hrbp.oa.common.session_manager import load_saved_session
|
||||
from app.service.hrbp.oa.common.work_communication import send_work_communication
|
||||
|
||||
session = load_saved_session() # 复用「37duOA登录」写入的共享 cookies
|
||||
doc_id = send_work_communication(
|
||||
session=session,
|
||||
receiver_keywords=["37036801", "夏一平"], # 工号或姓名,单个或列表
|
||||
subject="【通知】...",
|
||||
content="<p>正文支持 HTML</p>",
|
||||
attachment_paths=[r"D:\\资料\\附件1.xlsx"], # 可选
|
||||
creator_id="1342173e36cf416088266b17d7d084a4", # 当前操作人 ID(必填)
|
||||
category="工作安排", # 沟通类型(可选):工作交流/信息传递/工作安排/项目沟通/温馨提示/其他
|
||||
)
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.oa_api.work_communication import (
|
||||
search_person,
|
||||
upload_attachment,
|
||||
submit_work_communication,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def _to_list(value: Union[str, List[str], None]) -> List[str]:
|
||||
"""把单个字符串或列表统一成列表(空值返回空列表)。"""
|
||||
if not value:
|
||||
return []
|
||||
return [value] if isinstance(value, str) else list(value)
|
||||
|
||||
|
||||
def send_work_communication(
|
||||
session: SessionPage,
|
||||
receiver_keywords: Union[str, List[str]],
|
||||
subject: str,
|
||||
content: str,
|
||||
attachment_paths: Union[str, List[str]] = None,
|
||||
creator_id: str = None,
|
||||
category: str = None,
|
||||
) -> str:
|
||||
"""
|
||||
发送工作沟通(一键推送入口)。
|
||||
|
||||
完整流程:解析接收人(工号/姓名 -> ID)-> 上传附件 -> 提交沟通。
|
||||
- 接收人支持多个,用工号或姓名(姓名同名时建议用工号保证准确);
|
||||
- 附件支持多个,任一上传失败即整体失败(不发送部分数据);
|
||||
- 所有步骤成功才返回沟通文档 ID(fdId)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(复用共享 cookies)
|
||||
receiver_keywords: 接收人工号或姓名,单个字符串或列表
|
||||
subject: 沟通标题
|
||||
content: 沟通内容(支持 HTML 富文本)
|
||||
attachment_paths: 附件文件路径,单个字符串或列表,可空
|
||||
creator_id: 创建人(当前操作人)用户 ID,必填
|
||||
category: 沟通类型,可传中文名(如「工作安排」「信息传递」)或类型 ID,
|
||||
默认「工作安排」(config.FD_CATEGORY_DEFAULT)
|
||||
|
||||
Returns:
|
||||
沟通文档 ID(fdId,字符串)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺少必填参数
|
||||
RuntimeError: 接收人解析失败 / 附件上传失败 / 提交失败(含具体原因)
|
||||
"""
|
||||
if not subject or not subject.strip():
|
||||
raise ValueError("subject(标题) 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content(内容) 不能为空")
|
||||
if not creator_id:
|
||||
raise ValueError("creator_id(创建人ID) 必填,请传入当前操作人的用户 ID")
|
||||
|
||||
# ---- 1. 解析接收人 ----
|
||||
receiver_ids, receiver_names = [], []
|
||||
unresolved = []
|
||||
for kw in _to_list(receiver_keywords):
|
||||
kw = str(kw).strip()
|
||||
if not kw:
|
||||
continue
|
||||
result = search_person(session, kw)
|
||||
if result:
|
||||
pid, pname = result
|
||||
receiver_ids.append(pid)
|
||||
receiver_names.append(pname)
|
||||
logger.info("接收人[%s] -> %s (ID: %s)", kw, pname, pid)
|
||||
else:
|
||||
unresolved.append(kw)
|
||||
|
||||
if not receiver_ids:
|
||||
raise RuntimeError("未解析到任何接收人,请检查传入的工号/姓名")
|
||||
if unresolved:
|
||||
raise RuntimeError(f"以下接收人解析失败,已中止发送: {', '.join(unresolved)}")
|
||||
|
||||
# ---- 2. 上传附件(任一失败即整体失败) ----
|
||||
attachment_ids = []
|
||||
for path in _to_list(attachment_paths):
|
||||
attid = upload_attachment(session, path)
|
||||
attachment_ids.append(attid)
|
||||
logger.info("附件[%s] -> attid: %s", path, attid)
|
||||
|
||||
# ---- 3. 提交沟通 ----
|
||||
return submit_work_communication(
|
||||
session=session,
|
||||
receiver_ids=receiver_ids,
|
||||
receiver_names=receiver_names,
|
||||
subject=subject,
|
||||
content=content,
|
||||
attachment_ids=attachment_ids or None,
|
||||
creator_id=creator_id,
|
||||
category_id=category,
|
||||
)
|
||||
@@ -149,16 +149,48 @@ def find_dingtalk_window(include_hidden=True):
|
||||
|
||||
|
||||
def activate_window(hwnd):
|
||||
"""强制激活窗口(最小化、隐藏、托盘均可恢复)"""
|
||||
"""确保窗口在前台(最小化、隐藏、托盘均可恢复)。
|
||||
|
||||
已在前台直接返回,绝不无谓地抢焦点——否则批量推送时会反复把焦点从用户正在
|
||||
操作的应用抢到钉钉(表现为「所有窗口失焦、点不动」)。
|
||||
|
||||
前台锁绕过:Windows 禁止后台进程直接 SetForegroundWindow(表现为窗口只在任务栏
|
||||
「闪现」却上不了前台)。这里用两步让它真正前置:
|
||||
1. AttachThreadInput:把本线程输入队列挂到前台线程,冒充「前台进程」;
|
||||
2. Alt 完整按下+抬起(down+up 对,不是孤立的 KEYUP):告诉系统「用户刚按了
|
||||
键」,进一步放宽前台锁;完整按键对不会遗留粘滞状态。
|
||||
"""
|
||||
if win32gui.GetForegroundWindow() == hwnd:
|
||||
return
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
time.sleep(0.1)
|
||||
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)
|
||||
time.sleep(0.1)
|
||||
|
||||
# 前台锁绕过:挂到前台线程 + Alt 按下/抬起,让 SetForegroundWindow 真正生效
|
||||
fg_hwnd = win32gui.GetForegroundWindow()
|
||||
cur_thread = win32api.GetCurrentThreadId()
|
||||
fg_thread = win32process.GetWindowThreadProcessId(fg_hwnd)[0] if fg_hwnd else 0
|
||||
attached = False
|
||||
if fg_thread and fg_thread != cur_thread:
|
||||
try:
|
||||
win32process.AttachThreadInput(fg_thread, cur_thread, True)
|
||||
attached = True
|
||||
except Exception:
|
||||
attached = False
|
||||
try:
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, 0, 0) # Alt 按下
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) # Alt 抬起
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
finally:
|
||||
if attached:
|
||||
try:
|
||||
win32process.AttachThreadInput(fg_thread, cur_thread, False)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def get_window_rect(hwnd):
|
||||
@@ -166,6 +198,30 @@ def get_window_rect(hwnd):
|
||||
return win32gui.GetWindowRect(hwnd)
|
||||
|
||||
|
||||
def safe_click(x, y):
|
||||
"""异常安全的鼠标左键点击:任何情况(异常/打断)都保证左键松开。
|
||||
不用 pyautogui.click——它在 mouseDown 与 mouseUp 之间被打断时会留下卡死的左键
|
||||
(症状:屏幕点不动、滚轮失效,必须重启才能恢复)。
|
||||
实现:SetCursorPos 瞬移指针 + mouse_event 按下/抬起(finally 兜底松开)。
|
||||
"""
|
||||
win32api.SetCursorPos(int(x), int(y))
|
||||
time.sleep(0.05)
|
||||
try:
|
||||
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
|
||||
time.sleep(0.05)
|
||||
finally:
|
||||
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def release_mouse():
|
||||
"""安全兜底:补发左键松开,清掉历史遗留的卡死左键状态(幂等,无害)。"""
|
||||
try:
|
||||
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def find_dingtalk_main_window():
|
||||
"""只找钉钉主窗口(标题为「钉钉/DingTalk」且有效尺寸)。
|
||||
优先返回可见的主窗口;找不到可见的再回退到任意有效尺寸的主标题窗口。
|
||||
@@ -280,33 +336,58 @@ def wait_for_tab(hwnd, expected_tab):
|
||||
|
||||
|
||||
# ---------- 核心功能 ----------
|
||||
def focus_search_box(hwnd):
|
||||
"""OCR 定位主界面搜索框(占位文本“搜索或提问”)并点击一次,
|
||||
让钉钉把焦点放到搜索框(比纯快捷键更稳,避免 Ctrl+Shift+F 失败)。
|
||||
"""
|
||||
ocr_data = analyze_top_region(hwnd)
|
||||
if not ocr_data:
|
||||
return False
|
||||
left, top, _, _ = get_window_rect(hwnd)
|
||||
for keyword in ("搜索或提问", "搜索", "提问"):
|
||||
pos = find_text_center(ocr_data, keyword)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
screen_x, screen_y = left + cx, top + cy
|
||||
safe_click(screen_x, screen_y)
|
||||
logger.info("已点击搜索框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
logger.warning("未识别到搜索框占位文本(搜索或提问/搜索/提问)")
|
||||
return False
|
||||
|
||||
|
||||
def search_and_open(hwnd, target_name, chat_type="联系人"):
|
||||
"""搜索并打开指定的联系人或群组会话。
|
||||
chat_type: "联系人" 或 "群组"
|
||||
简化设计:不再用 Ctrl+Shift+F 快捷键(会被前台锁/输入法干扰且逻辑重复),
|
||||
一律 OCR 点击主界面搜索框(focus_search_box)→ 输入关键字 → 回车。
|
||||
每个 attempt 开头 esc 复位,避免残留搜索面板遮住占位文本。
|
||||
快速失败设计(fail-fast):标签检测(wait_for_tab)与会话校验(is_chat_opened)
|
||||
都只做最多 2 次 OCR(即时 + 0.3s 重试),失败不再原地长时间轮询死磕 OCR,
|
||||
而是 continue 回到外层 SEARCH_RETRY 循环重试:既把 OCR 次数压到最少,
|
||||
又避免「会话校验偶发漏检 → 整条消息永久失败」的致命坑
|
||||
(旧逻辑 return False 会让 send_text_to 抛 RuntimeError 直接跳过整条重试)。
|
||||
都只做最多 2 次 OCR(即时 + 0.3s 重试),失败 continue 回到外层 SEARCH_RETRY
|
||||
循环重试(避免「会话校验偶发漏检 → 整条消息永久失败」的致命坑)。
|
||||
"""
|
||||
activate_window(hwnd)
|
||||
for attempt in range(SEARCH_RETRY):
|
||||
# 1. 打开搜索框并输入关键字
|
||||
pyautogui.hotkey('ctrl', 'shift', 'f')
|
||||
time.sleep(0.8)
|
||||
activate_window(hwnd)
|
||||
# 复位:关闭可能残留的搜索面板,让占位文本回到可见
|
||||
pyautogui.press('esc')
|
||||
time.sleep(0.3)
|
||||
if not focus_search_box(hwnd):
|
||||
logger.warning("未识别到搜索框(第%d次),外层重试", attempt + 1)
|
||||
continue
|
||||
|
||||
# 1. 输入关键字并搜索
|
||||
pyautogui.hotkey('ctrl', 'a')
|
||||
pyautogui.press('delete')
|
||||
pyperclip.copy(target_name)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.5)
|
||||
time.sleep(0.2)
|
||||
pyautogui.press('enter')
|
||||
logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1)
|
||||
time.sleep(0.8)
|
||||
# 检测对应的标签(联系人/群组)出现,表示搜索已就绪
|
||||
time.sleep(0.5)
|
||||
if not wait_for_tab(hwnd, chat_type):
|
||||
pyautogui.press('esc')
|
||||
time.sleep(0.5)
|
||||
continue # 标签没出现 → 外层重试
|
||||
logger.warning("未检测到'%s'标签(第%d次),外层重试", chat_type, attempt + 1)
|
||||
continue
|
||||
|
||||
# 2. 点击对应标签(联系人/群组)
|
||||
ocr_data = analyze_top_region(hwnd)
|
||||
@@ -314,16 +395,16 @@ def search_and_open(hwnd, target_name, chat_type="联系人"):
|
||||
pos = find_text_center(ocr_data, chat_type)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
pyautogui.click(left + cx, top + cy)
|
||||
safe_click(left + cx, top + cy)
|
||||
logger.info("点击'%s'标签", chat_type)
|
||||
else:
|
||||
logger.warning("未识别'%s'标签", chat_type)
|
||||
time.sleep(0.5)
|
||||
time.sleep(0.3)
|
||||
|
||||
# 3. 选中第一个结果并打开
|
||||
pyautogui.press('enter')
|
||||
logger.info("打开第一个匹配项")
|
||||
time.sleep(1.5)
|
||||
time.sleep(1.0)
|
||||
|
||||
# 4. 验证会话是否成功打开(最多 2 次 OCR,失败继续外层重试)
|
||||
if is_chat_opened(hwnd, target_name):
|
||||
@@ -384,7 +465,7 @@ def focus_input_box(hwnd):
|
||||
cached = CACHED_INPUT_POS
|
||||
if cached and cached[0] == rect:
|
||||
_, cx, cy = cached
|
||||
pyautogui.click(cx, cy)
|
||||
safe_click(cx, cy)
|
||||
logger.info("使用缓存输入框坐标 (%s, %s)", cx, cy)
|
||||
return True
|
||||
if cached:
|
||||
@@ -393,13 +474,13 @@ def focus_input_box(hwnd):
|
||||
input_pos = find_input_box_by_ocr(hwnd)
|
||||
if input_pos:
|
||||
CACHED_INPUT_POS = (rect, input_pos[0], input_pos[1])
|
||||
pyautogui.click(input_pos[0], input_pos[1])
|
||||
safe_click(input_pos[0], input_pos[1])
|
||||
return True
|
||||
# 降级:点击窗口底部中央
|
||||
left, top, right, bottom = rect
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
pyautogui.click(left + width // 2, top + height - 60)
|
||||
safe_click(left + width // 2, top + height - 60)
|
||||
logger.warning("使用固定坐标点击输入框")
|
||||
return False
|
||||
|
||||
@@ -413,18 +494,17 @@ def send_hotkey_to_activate():
|
||||
|
||||
|
||||
def ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
"""
|
||||
采用多种策略确保钉钉窗口激活到前台(主界面可见),并等待验证。
|
||||
策略:快捷键 → Win32 API → 组合
|
||||
注意:Ctrl+Alt+D 是“切换”快捷键——窗口已显示时按下会将其隐藏到托盘
|
||||
(批量推送时「发着发着钉钉窗口突然隐藏且再也唤不回来」即因此触发),
|
||||
"""多策略确保钉钉窗口激活到前台(Win32 API 优先 → 快捷键兜底 → 组合)。
|
||||
|
||||
注意:Ctrl+Alt+D 是钉钉「唤起/隐藏主面板」的【切换】快捷键——窗口已显示时按下会把它
|
||||
隐藏到托盘(用户反馈的「发着发着钉钉窗口突然隐藏且再也唤不回来」即因此触发)。
|
||||
因此本函数:
|
||||
1. 切换键只在确认主窗口不可见时才允许按;
|
||||
2. 每次按键后用 Win32 校验是否【变为可见】,若反而不可见(说明原本可见被误判切走),
|
||||
立即再按一次切回,绝不让窗口停留在隐藏状态;
|
||||
3. Win32 API 激活(ShowWindow + SetForegroundWindow)只显示/前置,永远不会隐藏窗口,
|
||||
作为主力路径优先使用。
|
||||
每次按键/API 后都会重新查找窗口句柄再验证,避免句柄指向 0 尺寸的辅助窗口。
|
||||
1. Win32 API 激活(ShowWindow + SetForegroundWindow)只显示/前置,永远不会隐藏窗口,
|
||||
作为主力路径优先使用,不依赖切换键;
|
||||
2. 切换键只在 API 失效且确认主窗口不可见时才按,且每次按键后自校验是否变为可见,
|
||||
若反而不可见(误切隐藏)立即补按切回,绝不让窗口停留在隐藏状态;
|
||||
3. verify 采用快速失败(最多 3 轮「尝试前置 + 检查」,约 1.5s 内给出结论),
|
||||
不再长时间等待。
|
||||
"""
|
||||
def wait_for_valid_rect(hwnd, max_wait=1.5):
|
||||
end = time.time() + max_wait
|
||||
@@ -441,10 +521,9 @@ def ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
|
||||
def verify(hwnd):
|
||||
"""Win32 校验激活成功:主窗口可见且位于前台(不做 OCR,毫秒级)。
|
||||
前台判定同时保证后续按键不会落到别的程序;未在前台时循环内再尝试前置。
|
||||
快速失败:最多 3 轮「尝试前置 + 检查」,约 1.5s 内给出结论,不再长时间等待。
|
||||
"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
for _ in range(3):
|
||||
main = find_dingtalk_main_window()
|
||||
if main and win32gui.IsWindowVisible(main) and win32gui.GetForegroundWindow() == main:
|
||||
return True
|
||||
@@ -463,26 +542,12 @@ def ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
cur = find_current()
|
||||
return bool(cur) and is_dingtalk_main_visible()
|
||||
|
||||
# 策略0:已在前台则直接返回(循环调用时避免重复激活/切换键误关窗口)
|
||||
# 已在前台则直接返回(循环调用时避免重复激活/切换键误关窗口)
|
||||
if is_dingtalk_foreground():
|
||||
logger.info("钉钉已在最前,跳过激活")
|
||||
return True
|
||||
|
||||
# 策略1:快捷键(仅在主窗口不可见时使用,toggle_show 自带防切隐藏校验)
|
||||
if not is_dingtalk_main_visible():
|
||||
if toggle_show():
|
||||
cur = find_current()
|
||||
if cur and wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("快捷键激活成功")
|
||||
win32gui.SetForegroundWindow(cur)
|
||||
return True
|
||||
logger.warning("快捷键已显示窗口但主界面未确认,继续 API 兜底")
|
||||
else:
|
||||
logger.warning("快捷键后窗口仍未显示")
|
||||
else:
|
||||
logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)")
|
||||
|
||||
# 策略2:API(只显示/前置,绝不会隐藏窗口)
|
||||
# 策略1(主力):Win32 API——只显示/前置,绝不会隐藏窗口,几乎总能成功
|
||||
logger.info("尝试 Win32 API 激活")
|
||||
cur = find_current()
|
||||
if cur:
|
||||
@@ -490,16 +555,29 @@ def ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("API激活成功")
|
||||
return True
|
||||
logger.warning("API后窗口尺寸无效")
|
||||
logger.warning("API后窗口仍未在前台")
|
||||
|
||||
# 策略3:组合(同样只在主窗口不可见时按切换键,避免切隐藏)
|
||||
# 策略2(兜底):仅在主窗口不可见时按切换快捷键(toggle_show 自带防切隐藏校验)
|
||||
if not is_dingtalk_main_visible():
|
||||
if toggle_show():
|
||||
cur = find_current()
|
||||
if cur and wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("快捷键激活成功")
|
||||
win32gui.SetForegroundWindow(cur)
|
||||
return True
|
||||
logger.warning("快捷键已显示窗口但主界面未确认,继续组合兜底")
|
||||
else:
|
||||
logger.warning("快捷键后窗口仍未显示")
|
||||
else:
|
||||
logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)")
|
||||
|
||||
# 策略3(最后手段):组合(同样只在主窗口不可见时按切换键,避免切隐藏)
|
||||
logger.info("组合激活")
|
||||
if not is_dingtalk_main_visible():
|
||||
if toggle_show():
|
||||
cur = find_current()
|
||||
if cur:
|
||||
activate_window(cur)
|
||||
time.sleep(1)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("组合激活成功")
|
||||
return True
|
||||
@@ -511,7 +589,6 @@ def ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
cur = find_current()
|
||||
if cur:
|
||||
activate_window(cur)
|
||||
time.sleep(1)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("组合激活成功(API)")
|
||||
return True
|
||||
@@ -546,6 +623,7 @@ def send_text_to(chat_type, name, text):
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
release_mouse() # 清掉可能的卡死左键,再开始本消息
|
||||
for attempt in range(RETRY_TIMES):
|
||||
try:
|
||||
# 1. 查找钉钉窗口(含隐藏)
|
||||
@@ -618,6 +696,7 @@ def send_file_to(chat_type, name, file_path):
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"文件不存在: {file_path}")
|
||||
|
||||
release_mouse() # 清掉可能的卡死左键,再开始本消息
|
||||
for attempt in range(RETRY_TIMES):
|
||||
try:
|
||||
# 1. 查找钉钉窗口(含隐藏)
|
||||
|
||||