feat: 新增轻量会话校验能力,优化登录态失效处理流程
1. 新增TODO_COUNT_URL轻量接口用于快速校验会话有效性 2. 定义OALoginExpiredError统一标识登录态失效异常 3. 重构会话校验逻辑,使用轻量接口替代拉取待办页校验 4. 为重试装饰器添加不重试异常配置,登录失效直接上抛 5. 全流程增加登录态失效自动重登机制,最多重试2次 6. 新增通用钉钉机器人推送工具类
This commit is contained in:
@@ -24,8 +24,10 @@ from app.service.hrbp.oa.common.session_manager import (
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
is_session_valid,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
OALoginExpiredError,
|
||||
get_documents,
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
@@ -141,13 +143,13 @@ def _get_browser_and_session(subject: str):
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次)"""
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析单据详情:SSO 取 taskId/businessKey -> WfActivity 取 formId -> WorkformEngine 取表单数据。
|
||||
@@ -208,49 +210,68 @@ def run_flow(
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
result["creator"], result["title"], result["decision"],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
result["creator"], result["title"], result["decision"],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -15,6 +15,8 @@ from app.service.hrbp.common.config import HR_BASE_URL # noqa: E402
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||
FD_TYPE = "13"
|
||||
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json, _handle_response
|
||||
from app.service.hrbp.oa.common.oa_api.base import (
|
||||
oa_request_json,
|
||||
_handle_response,
|
||||
OALoginExpiredError,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.todo import (
|
||||
fetch_todo_page,
|
||||
parse_todo_list,
|
||||
@@ -32,6 +36,7 @@ from app.service.hrbp.oa.common.oa_api.leave import (
|
||||
__all__ = [
|
||||
"oa_request_json",
|
||||
"_handle_response",
|
||||
"OALoginExpiredError",
|
||||
"fetch_todo_page",
|
||||
"parse_todo_list",
|
||||
"get_documents",
|
||||
|
||||
@@ -18,17 +18,24 @@ except ImportError:
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _handle_response(resp, label):
|
||||
"""统一校验响应:存在性 / 状态码 / JSON 可解析性,返回解析后的 JSON。"""
|
||||
if not resp:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
|
||||
|
||||
|
||||
def oa_request_json(
|
||||
|
||||
@@ -128,11 +128,19 @@ def create_browser_with_saved_cookies(path: str = COOKIE_FILE) -> ChromiumPage:
|
||||
|
||||
|
||||
def is_session_valid(session: SessionPage, subject: str = "加班") -> bool:
|
||||
"""通过拉取待办第一页判断会话是否有效(无效则需重新登录)。"""
|
||||
from app.service.hrbp.oa.common.oa_api import fetch_todo_page
|
||||
"""通过轻量接口 sumTodoCount 判断会话是否有效(无效则需重新登录)。
|
||||
|
||||
会话有效时接口返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});
|
||||
会话失效会被重定向到登录页返回 HTML,据此判定失效。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.config import TODO_COUNT_URL
|
||||
try:
|
||||
fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
||||
return True
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
@@ -217,7 +217,8 @@ def _get_cookies_with_domain(session: SessionPage) -> list:
|
||||
|
||||
|
||||
def get_fd_id_by_listening(session: SessionPage, browser: Optional[ChromiumPage] = None) -> str:
|
||||
# 优先复用外部传入的浏览器;仅在没有可用浏览器时才自行创建(如复用已保存会话的场景)
|
||||
# 优先复用外部传入的浏览器;仅在没有可用浏览器时才自行创建(如复用已保存会话的场景)。
|
||||
# 复用场景下 get_session 已用轻量接口 is_session_valid 校验过会话,无需在此重复校验
|
||||
own_browser = browser is None
|
||||
if own_browser:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
@@ -236,6 +237,10 @@ def get_fd_id_by_listening(session: SessionPage, browser: Optional[ChromiumPage]
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
|
||||
# 兜底:轻量接口校验通过后,若新浏览器 cookies 提取不全仍可能停在登录页,快速失败避免空等
|
||||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||||
|
||||
deadline = time.time() + 10
|
||||
target_request = None
|
||||
while time.time() < deadline:
|
||||
@@ -620,73 +625,77 @@ def export_employee_change_list(
|
||||
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **filter_params}
|
||||
|
||||
browser, session = get_session()
|
||||
# 登录态失效时自动删除 cookie、重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session = get_session()
|
||||
|
||||
try:
|
||||
# 1. 动态获取 fdId(复用登录浏览器,避免重复创建导致浏览器被提前关闭)
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
|
||||
# 2. 从菜单获取 searchId
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
|
||||
# 3. 生成一个固定的时间戳(毫秒)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
logger.info("使用时间戳: %s", timestamp)
|
||||
|
||||
# 4. 查询获取总条数
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
# 5. 导出数据
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
file_content = export_all_data(session, base_params, total, columns,
|
||||
search_id, timestamp)
|
||||
|
||||
output_filename = f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"
|
||||
output_path = os.path.abspath(os.path.join(output_dir, output_filename))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(file_content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
# 6. 读取原始表并内存清洗(去『废弃』+按工号去重),不落中间表
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
|
||||
# 7. 调用 HR 参保记录接口核对,追加『社保记录查询结果』列(一次性完成)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
|
||||
# 8. 清理中间原始导出文件,只保留最终标注表
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
# 1. 动态获取 fdId(复用登录浏览器,避免重复创建导致浏览器被提前关闭)
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
|
||||
if browser is not None:
|
||||
save_browser_cookies(browser)
|
||||
return final_path
|
||||
# 2. 从菜单获取 searchId
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e, exc_info=True)
|
||||
if "登录" in str(e) or "cookie" in str(e).lower():
|
||||
# 3. 生成一个固定的时间戳(毫秒)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
logger.info("使用时间戳: %s", timestamp)
|
||||
|
||||
# 4. 查询获取总条数
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
# 5. 导出数据
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
file_content = export_all_data(session, base_params, total, columns,
|
||||
search_id, timestamp)
|
||||
|
||||
output_filename = f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"
|
||||
output_path = os.path.abspath(os.path.join(output_dir, output_filename))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(file_content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
# 6. 读取原始表并内存清洗(去『废弃』+按工号去重),不落中间表
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
|
||||
# 7. 调用 HR 参保记录接口核对,追加『社保记录查询结果』列(一次性完成)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
|
||||
# 8. 清理中间原始导出文件,只保留最终标注表
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效的 cookie 文件")
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if browser is not None:
|
||||
save_browser_cookies(browser)
|
||||
return final_path
|
||||
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e, exc_info=True)
|
||||
is_login_fail = "登录" in str(e) or "cookie" in str(e).lower()
|
||||
if is_login_fail and login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("检测到登录态失效,已删除 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def export_participation(
|
||||
filter_params: Optional[Dict] = None,
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: utils.dingtalk_robot
|
||||
@FileName: dingtalk_robot.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-14
|
||||
@Description: 钉钉群机器人消息推送模块(自定义机器人 Webhook 方式)——项目级通用推送能力,
|
||||
供请假/加班/考勤/雇主险等所有业务模块复用,不绑定任何具体业务。
|
||||
提供统一通知方法 send_notification(标题按状态着色 + 内容引用块 + 页脚署名带时间),
|
||||
样式参照小芒任务调度平台的 DingTalkBot.send_notification。
|
||||
与 dingtalk_sender(桌面客户端模拟)不同,本模块走 HTTP 推送,无需登录钉钉桌面端。
|
||||
推送地址、加签密钥、页脚平台署名可通过环境变量配置:
|
||||
DINGTALK_ROBOT_WEBHOOK = https://oapi.dingtalk.com/robot/send?access_token=xxx
|
||||
DINGTALK_ROBOT_SECRET = 加签密钥(未配置则不加签)
|
||||
DINGTALK_ROBOT_NAME = 页脚平台署名,默认 "小芒 任务调度平台"
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受。
|
||||
失败自动重试 3 次,成功/失败均有日志;响应细节仅 DEBUG 级别输出,避免大 JSON 刷屏。
|
||||
@Version: 2.0.0
|
||||
|
||||
使用示例:
|
||||
from app.utils.dingtalk_robot import DingTalkRobot, send_robot_notification
|
||||
|
||||
# 统一通知(推荐):标题按 status 着色,内容多行自动转引用块,自动追加页脚署名+时间
|
||||
robot = DingTalkRobot()
|
||||
robot.send_notification(
|
||||
"任务执行失败",
|
||||
"订单同步失败\n错误原因:接口超时",
|
||||
status="error",
|
||||
)
|
||||
|
||||
# 底部带按钮的 ActionCard(如报表下载)
|
||||
robot.send_action_card(
|
||||
"报表已生成",
|
||||
"7 月考勤报表已生成,点击下方按钮下载",
|
||||
single_title="点击下载报表",
|
||||
single_url="https://xxx/download",
|
||||
)
|
||||
|
||||
# 纯文本
|
||||
robot.send_text("测试消息")
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from app.utils.intelligent_retry import retry
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ==================== 环境变量加载 ====================
|
||||
def _load_env_file():
|
||||
"""
|
||||
从项目根目录的 .env 加载环境变量(不覆盖已存在的环境变量)。
|
||||
|
||||
优先使用 python-dotenv;缺失时手动解析 key=value 行,保证模块零第三方依赖可用。
|
||||
"""
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
return
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# 项目根目录:app/utils/dingtalk_robot.py 向上三级
|
||||
env_path = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||
".env",
|
||||
)
|
||||
if not os.path.exists(env_path):
|
||||
return
|
||||
with open(env_path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
key = key.strip()
|
||||
value = value.strip().strip("\"'")
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
_load_env_file()
|
||||
|
||||
# ==================== 默认参数 ====================
|
||||
DEFAULT_WEBHOOK = os.getenv("DINGTALK_ROBOT_WEBHOOK", "").strip()
|
||||
DEFAULT_SECRET = os.getenv("DINGTALK_ROBOT_SECRET", "").strip()
|
||||
DEFAULT_SERVER_NAME = os.getenv("DINGTALK_ROBOT_NAME", "").strip() or "小芒 任务调度平台"
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
DINGTALK_ROBOT_ENDPOINT = "https://oapi.dingtalk.com/robot/send"
|
||||
|
||||
# 通知状态 → 标题颜色(与 aa.md 中 DingTalkBot.send_notification 色板一致)
|
||||
_STATUS_COLORS = {
|
||||
"info": "#0077ff", # 蓝色
|
||||
"success": "#00b300", # 绿色
|
||||
"warning": "#ff9900", # 橙色
|
||||
"error": "#ff0000", # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret: str, timestamp_ms: int) -> str:
|
||||
"""按钉钉加签规则计算签名(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: str, secret: str = "") -> str:
|
||||
"""拼接最终推送地址:配置了 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)}"
|
||||
|
||||
|
||||
def _at_payload(
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> dict:
|
||||
"""构造 @ 参数。三种 @ 方式可组合,都不指定时返回空 dict。"""
|
||||
at = {}
|
||||
if at_mobiles:
|
||||
at["atMobiles"] = list(at_mobiles)
|
||||
if at_user_ids:
|
||||
at["atUserIds"] = list(at_user_ids)
|
||||
if is_at_all:
|
||||
at["isAtAll"] = True
|
||||
return at
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""
|
||||
钉钉群机器人推送器。
|
||||
|
||||
Args:
|
||||
webhook: 机器人 webhook 地址;缺省时读取环境变量 DINGTALK_ROBOT_WEBHOOK
|
||||
secret: 加签密钥;缺省时读取环境变量 DINGTALK_ROBOT_SECRET
|
||||
server_name: 页脚平台署名;缺省时读取环境变量 DINGTALK_ROBOT_NAME,
|
||||
默认 "小芒 任务调度平台"(含关键词"小芒",可满足机器人自定义关键词校验)
|
||||
timeout: HTTP 请求超时秒数
|
||||
|
||||
Raises:
|
||||
ValueError: webhook 为空
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
webhook: str = "",
|
||||
secret: str = "",
|
||||
server_name: str = "",
|
||||
timeout: int = 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 不能为空,请通过参数传入或配置环境变量 DINGTALK_ROBOT_WEBHOOK"
|
||||
)
|
||||
|
||||
@retry(max_attempts=DEFAULT_RETRY_TIMES)
|
||||
def _post(self, payload: dict):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败(重试由装饰器负责)。"""
|
||||
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")
|
||||
data = json.loads(body)
|
||||
if data.get("errcode") != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={data.get('errcode')}, "
|
||||
f"errmsg={data.get('errmsg')}"
|
||||
)
|
||||
logger.debug("钉钉机器人推送成功,响应: %s", data)
|
||||
|
||||
def _build_footer(self, server_name: str = "") -> str:
|
||||
"""构建页脚:###### {署名} | {当前时间}。署名缺省取实例的 server_name。"""
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
return f"###### {display_name} | {current_time}"
|
||||
|
||||
def send_text(
|
||||
self,
|
||||
content: str,
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
发送文本消息。
|
||||
|
||||
Args:
|
||||
content: 文本内容
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: content 为空
|
||||
"""
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content 不能为空")
|
||||
|
||||
payload = {"msgtype": "text", "text": {"content": content}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送文本: %s", content[:50] + ("..." if len(content) > 50 else ""))
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_markdown(
|
||||
self,
|
||||
title: str,
|
||||
text: str,
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
发送 Markdown 消息(底层通用方法,内容完全由调用方控制)。
|
||||
|
||||
Args:
|
||||
title: 消息标题(显示在会话中)
|
||||
text: Markdown 正文
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title 或 text 为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError("title 不能为空")
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
payload = {"msgtype": "markdown", "markdown": {"title": title, "text": text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送 Markdown: %s", title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_notification(
|
||||
self,
|
||||
title: str,
|
||||
content: str,
|
||||
status: str = "info",
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
server_name: str = "",
|
||||
append_footer: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
统一通知方法(推荐业务方使用),样式与 aa.md 中 DingTalkBot.send_notification 一致:
|
||||
|
||||
**<font color='#ff0000'>任务执行失败</font>** ← 标题按 status 着色
|
||||
|
||||
内容详情:
|
||||
> 订单同步失败 ← 内容多行自动转引用块
|
||||
> 错误原因:接口超时
|
||||
|
||||
---
|
||||
|
||||
###### 小芒 任务调度平台 | 2026-08-14 14:30:00 ← 页脚:署名 + 当前时间
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息主体内容,支持多行(自动按行转引用块)
|
||||
status: 状态类型,决定标题颜色: info(蓝) | success(绿) | warning(橙) | error(红)
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
server_name: 页脚署名,缺省用实例的 server_name
|
||||
append_footer: 是否自动追加页脚(署名 + 时间),默认 True
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title 或 content 为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError("title 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content 不能为空")
|
||||
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += "内容详情:\n"
|
||||
for line in content.strip().splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
# 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示
|
||||
text += f"> {line} \n"
|
||||
if append_footer:
|
||||
text += f"\n\n---\n\n{self._build_footer(server_name)}"
|
||||
|
||||
payload = {"msgtype": "markdown", "markdown": {"title": title, "text": text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_action_card(
|
||||
self,
|
||||
title: str,
|
||||
content: str,
|
||||
single_title: str,
|
||||
single_url: str,
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
server_name: str = "",
|
||||
) -> bool:
|
||||
"""
|
||||
发送 ActionCard 消息(底部带按钮,如"点击下载报表")。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 卡片正文(支持多行)
|
||||
single_title: 按钮文字
|
||||
single_url: 按钮跳转链接
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
server_name: 页脚署名,缺省用实例的 server_name
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title / content / single_title / single_url 任一为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError("title 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content 不能为空")
|
||||
if not single_title or not single_title.strip():
|
||||
raise ValueError("single_title 不能为空")
|
||||
if not single_url or not single_url.strip():
|
||||
raise ValueError("single_url 不能为空")
|
||||
|
||||
text = f"**{title}**\n\n{content}\n\n---\n\n{self._build_footer(server_name)}"
|
||||
payload = {
|
||||
"msgtype": "actionCard",
|
||||
"actionCard": {
|
||||
"title": title,
|
||||
"text": text,
|
||||
"singleTitle": single_title,
|
||||
"singleURL": single_url,
|
||||
},
|
||||
}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送 ActionCard: %s -> %s", title, single_url)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 一次性便捷函数 ====================
|
||||
def send_robot_text(
|
||||
content: str,
|
||||
webhook: str = "",
|
||||
secret: str = "",
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> bool:
|
||||
"""一键发送文本到群机器人(webhook 缺省取环境变量 DINGTALK_ROBOT_WEBHOOK)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_text(content, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all)
|
||||
|
||||
|
||||
def send_robot_notification(
|
||||
title: str,
|
||||
content: str,
|
||||
status: str = "info",
|
||||
webhook: str = "",
|
||||
secret: str = "",
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
server_name: str = "",
|
||||
) -> bool:
|
||||
"""一键发送统一通知(样式与 send_notification 一致)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_notification(
|
||||
title, content, status=status,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
|
||||
|
||||
# ==================== 命令行入口(便于手动测试) ====================
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="钉钉群机器人消息推送工具")
|
||||
parser.add_argument("content", help="消息内容(多行可用换行分隔)")
|
||||
parser.add_argument("-t", "--title", default="消息通知", help="消息标题")
|
||||
parser.add_argument("--status", default="info",
|
||||
choices=["info", "success", "warning", "error"], help="通知状态(决定标题颜色)")
|
||||
parser.add_argument("-w", "--webhook", default="", help="机器人 webhook,缺省取环境变量")
|
||||
parser.add_argument("-s", "--secret", default="", help="加签密钥,缺省取环境变量")
|
||||
parser.add_argument("--name", default="", help="页脚平台署名,缺省取环境变量")
|
||||
parser.add_argument("--all", action="store_true", help="@所有人")
|
||||
args = parser.parse_args()
|
||||
|
||||
send_robot_notification(
|
||||
args.title, args.content, status=args.status,
|
||||
webhook=args.webhook, secret=args.secret,
|
||||
server_name=args.name, is_at_all=args.all,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user