1. 新增TODO_COUNT_URL轻量接口用于快速校验会话有效性 2. 定义OALoginExpiredError统一标识登录态失效异常 3. 重构会话校验逻辑,使用轻量接口替代拉取待办页校验 4. 为重试装饰器添加不重试异常配置,登录失效直接上抛 5. 全流程增加登录态失效自动重登机制,最多重试2次 6. 新增通用钉钉机器人推送工具类
457 lines
17 KiB
Python
457 lines
17 KiB
Python
# -*- 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()
|