- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
319 lines
14 KiB
Python
319 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""钉钉群机器人(自定义机器人 Webhook)推送。
|
||
|
||
能力(与原 ``workflows/share/dingtalk_robot.py`` 及各插件内副本一致):
|
||
- 加签(HMAC-SHA256 + Base64 + URL 编码)与不加签两种模式;
|
||
- Markdown 消息:标题按状态着色 + 正文 + 页脚署名/时间;
|
||
- 超长内容按行分批(``max_chars``);块格式按条数分批(``batch_size``);
|
||
- 多环境(prod/dev)webhook 选择,失败自动重试(默认 3 次)。
|
||
|
||
两种调用风格:
|
||
- ``Robot(...).send(...)``:失败抛异常(``NetworkError`` / ``ApiError``);
|
||
- ``push(...)``:失败返回 ``{"success": False, "message": ...}``,与旧脚本 ``main()`` 完全兼容。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import hmac
|
||
import json
|
||
import time
|
||
import urllib.parse
|
||
import urllib.request
|
||
from datetime import datetime
|
||
from typing import Callable, List, Optional, Sequence, Union
|
||
|
||
from .config import RobotAccount, get_settings
|
||
from .http import mask
|
||
|
||
#: 通知状态 → 标题颜色
|
||
STATUS_COLORS = {
|
||
"info": "#0077ff", # 蓝色
|
||
"success": "#00b300", # 绿色
|
||
"warning": "#ff9900", # 橙色
|
||
"error": "#ff0000", # 红色
|
||
}
|
||
|
||
DEFAULT_TITLE = "消息通知"
|
||
DEFAULT_MAX_CHARS = 15000 # 钉钉 Markdown 上限约 20000
|
||
DEFAULT_BATCH_SIZE = 10
|
||
|
||
|
||
# ==================== 加签 / URL ====================
|
||
|
||
def build_sign(secret: str, timestamp_ms: Union[int, str]) -> str:
|
||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||
digest = hmac.new(secret.encode("utf-8"), string_to_sign.encode("utf-8"),
|
||
digestmod=hashlib.sha256).digest()
|
||
return urllib.parse.quote_plus(base64.b64encode(digest))
|
||
|
||
|
||
def build_url(webhook: str, secret: str = "") -> str:
|
||
"""拼接最终推送地址:配置 secret 时追加 ``timestamp`` + ``sign``。"""
|
||
webhook = (webhook or "").strip()
|
||
if not secret:
|
||
return webhook
|
||
ts = int(round(time.time() * 1000))
|
||
sep = "&" if "?" in webhook else "?"
|
||
return f"{webhook}{sep}timestamp={ts}&sign={build_sign(secret, ts)}"
|
||
|
||
|
||
# ==================== 消息体构造 ====================
|
||
|
||
def render_markdown(title: str, content: str, status: str = "info",
|
||
server_name: str = "") -> str:
|
||
"""渲染统一格式的 Markdown 正文(彩色标题 + 正文 + 页脚)。"""
|
||
color = STATUS_COLORS.get((status or "").strip().lower(), STATUS_COLORS["info"])
|
||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
footer = f"\n\n---\n\n###### {(server_name or '').strip()} | {now}"
|
||
return f"**<font color='{color}'>{title}</font>**\n\n{str(content).strip()}\n{footer}"
|
||
|
||
|
||
def compose_batch_messages(blocks: Sequence[str], title_prefix: str,
|
||
batch_size: int = DEFAULT_BATCH_SIZE) -> List[str]:
|
||
"""把 block 列表按 ``batch_size`` 条一批,生成带批次标题的待推送文本列表。
|
||
|
||
Args:
|
||
blocks: 每条记录格式化后的 block 字符串列表(业务字段由调用方负责)
|
||
title_prefix: 批次标题前缀,如 ``【请假审批】通过``
|
||
batch_size: 每批最大条数(默认 10)
|
||
|
||
Returns:
|
||
字符串列表,每项可直接传给 :func:`push`(``batch=True``)或 ``Robot.send``。
|
||
"""
|
||
if not blocks:
|
||
return []
|
||
size = max(1, int(batch_size or DEFAULT_BATCH_SIZE))
|
||
total = (len(blocks) + size - 1) // size
|
||
out = []
|
||
for idx in range(total):
|
||
batch = list(blocks[idx * size:(idx + 1) * size])
|
||
header = f"###### {title_prefix}(第{idx + 1}/{total}批)\n\n"
|
||
# 钉钉中引用块尾行后需空行(双换行)再进入新标题,否则会紧贴渲染
|
||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||
out.append(header + "\n\n".join(batch) + footer)
|
||
return out
|
||
|
||
|
||
def split_by_chars(content: str, max_chars: int = DEFAULT_MAX_CHARS) -> List[str]:
|
||
"""按行切分超长文本(不切断单行内部),返回多段文本。"""
|
||
text = str(content or "").strip()
|
||
if not text:
|
||
return []
|
||
limit = max(1, int(max_chars or DEFAULT_MAX_CHARS))
|
||
batches, current, current_len = [], [], 0
|
||
for line in text.split("\n"):
|
||
line_len = len(line) + 1
|
||
if current_len + line_len > limit and current:
|
||
batches.append("\n".join(current))
|
||
current, current_len = [line], line_len
|
||
else:
|
||
current.append(line)
|
||
current_len += line_len
|
||
if current:
|
||
batches.append("\n".join(current))
|
||
return batches
|
||
|
||
|
||
# ==================== 推送器 ====================
|
||
|
||
class Robot:
|
||
"""群机器人推送器。
|
||
|
||
Args:
|
||
webhook: 机器人地址;缺省按 ``env`` 取配置
|
||
secret: 加签密钥;缺省按 ``env`` 取配置
|
||
server_name: 页脚署名;缺省按 ``env`` 取配置
|
||
env: ``prod`` / ``dev``
|
||
timeout: HTTP 超时秒
|
||
retries: 重试次数(含首次,默认 3)
|
||
log: 日志回调(默认不输出)
|
||
"""
|
||
|
||
def __init__(self, webhook: str = "", secret: str = "", server_name: str = "",
|
||
env: str = "prod", timeout: Optional[float] = None,
|
||
retries: Optional[int] = None,
|
||
log: Optional[Callable[[str], None]] = None) -> None:
|
||
cfg = get_settings()
|
||
acc: RobotAccount = cfg.robot(env)
|
||
self.webhook = (webhook or acc.webhook).strip()
|
||
self.secret = (secret or acc.secret).strip()
|
||
self.server_name = (server_name or acc.server_name).strip()
|
||
self.timeout = float(timeout if timeout is not None else 10.0)
|
||
self.retries = max(1, int(retries if retries is not None else cfg.retries))
|
||
self.log = log or (lambda msg: None)
|
||
if not self.webhook:
|
||
raise ValueError("webhook 不能为空")
|
||
|
||
# ---- 底层 ----
|
||
def post_payload(self, payload: dict) -> None:
|
||
"""推送任意 msgtype 的 payload;errcode != 0 视为失败,失败重试。"""
|
||
last_err: Optional[BaseException] = None
|
||
for attempt in range(self.retries):
|
||
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", errors="replace")
|
||
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 exc: # noqa: BLE001 - 统一重试
|
||
last_err = exc
|
||
self.log(f"[WARN] 推送失败(第 {attempt + 1}/{self.retries} 次):{mask(exc)}")
|
||
time.sleep(1)
|
||
raise RuntimeError(f"推送失败,重试 {self.retries} 次后仍出错:{mask(last_err)}")
|
||
|
||
# ---- 对外 ----
|
||
def send(self, title: str, content: str, status: str = "info",
|
||
server_name: str = "") -> None:
|
||
"""发送统一格式 Markdown(彩色标题 + 正文 + 页脚)。失败抛异常。"""
|
||
text = render_markdown(title, content, status, server_name or self.server_name)
|
||
payload = {"msgtype": "markdown", "markdown": {"title": title, "text": text}}
|
||
self.log(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||
self.post_payload(payload)
|
||
|
||
def send_markdown(self, title: str, text: str) -> None:
|
||
"""发送原始 Markdown(不再加彩色标题/页脚;标题只用于会话列表展示)。"""
|
||
payload = {"msgtype": "markdown", "markdown": {"title": title, "text": str(text)}}
|
||
self.log(f"[INFO] 钉钉机器人推送 Markdown: {title}")
|
||
self.post_payload(payload)
|
||
|
||
def send_text(self, text: str, at_all: bool = False,
|
||
at_open_ids: Sequence[str] = ()) -> None:
|
||
"""发送纯文本;``at_all`` / ``at_open_ids`` 会追加对应 @。"""
|
||
payload: dict = {"msgtype": "text", "text": {"content": str(text)}}
|
||
at: dict = {}
|
||
if at_all:
|
||
at["isAtAll"] = True
|
||
mobiles = [str(x).strip() for x in at_open_ids if str(x).strip()]
|
||
if mobiles:
|
||
at["atMobiles"] = mobiles
|
||
if at:
|
||
payload["at"] = at
|
||
self.log("[INFO] 钉钉机器人推送文本")
|
||
self.post_payload(payload)
|
||
|
||
def send_in_batches(self, title: str, content: str, status: str = "info",
|
||
server_name: str = "", max_chars: int = DEFAULT_MAX_CHARS) -> int:
|
||
"""超长内容按行拆批发送,每批标题带「第 i/N 批」。返回实际发送批次数量。"""
|
||
batches = split_by_chars(content, max_chars)
|
||
total = len(batches)
|
||
for idx, batch in enumerate(batches, 1):
|
||
batch_title = f"{title}(第{idx}/{total}批)" if total > 1 else title
|
||
self.log(f"[INFO] 分批推送 {idx}/{total}: {batch_title}")
|
||
self.send(batch_title, batch, status=status, server_name=server_name)
|
||
return total
|
||
|
||
|
||
#: 旧名兼容(原脚本类名)
|
||
DingTalkRobot = Robot
|
||
|
||
|
||
# ==================== 兼容入口(旧 main 签名) ====================
|
||
|
||
def push(text, title: str = DEFAULT_TITLE, status: str = "info", webhook: str = "",
|
||
secret: str = "", server_name: str = "", env: str = "prod",
|
||
batch: bool = False, max_chars: int = DEFAULT_MAX_CHARS,
|
||
log: Optional[Callable[[str], None]] = None) -> dict:
|
||
"""推送入口(与旧 ``dingtalk_robot.main`` 签名/返回完全一致)。
|
||
|
||
``text`` 支持三种形态:
|
||
- 字符串:单条推送;
|
||
- 列表:逐条推送,元素可为字符串或 ``{text, title?, status?, batch?, max_chars?}``;
|
||
- ``{title, blocks, status?, batch_size?}`` 字典列表:块格式分组,自动按条数分批。
|
||
|
||
Returns:
|
||
``{"success": bool, "message": str}``
|
||
"""
|
||
try:
|
||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||
or (isinstance(text, (list, tuple)) and not text):
|
||
return {"success": False, "message": "通知文本不能为空"}
|
||
|
||
env_key = (env or "prod").strip().lower()
|
||
cfg = get_settings()
|
||
if env_key not in cfg.robots:
|
||
return {"success": False,
|
||
"message": f"未知环境 [{env_key}],可选:{' / '.join(cfg.robots)}"}
|
||
acc = cfg.robot(env_key)
|
||
webhook = webhook or acc.webhook
|
||
secret = secret or acc.secret
|
||
server_name = server_name or acc.server_name
|
||
if not webhook:
|
||
return {"success": False,
|
||
"message": f"环境 [{env_key}] 的 webhook 未配置,请设置 "
|
||
f"DINGTALK_ROBOT_{env_key.upper()}_WEBHOOK"}
|
||
robot = Robot(webhook=webhook, secret=secret, server_name=server_name, log=log)
|
||
|
||
items = text if isinstance(text, (list, tuple)) else [text]
|
||
sent = 0
|
||
last_title, last_status = title, status
|
||
for item in items:
|
||
if isinstance(item, dict) and item.get("blocks") is not None:
|
||
# 块格式分组:调用方只给格式化好的 block 列表 + 标题,
|
||
# 分批、批次标题、逐条推送全部由 SDK 负责
|
||
ti = item.get("title", title)
|
||
st = item.get("status", status)
|
||
bs = int(item.get("batch_size", DEFAULT_BATCH_SIZE) or DEFAULT_BATCH_SIZE)
|
||
for batch_content in compose_batch_messages(item["blocks"], ti, bs):
|
||
robot.send(str(ti), batch_content, status=st, server_name=server_name)
|
||
sent += 1
|
||
last_title, last_status = ti, st
|
||
continue
|
||
if isinstance(item, dict):
|
||
t = item.get("text")
|
||
ti = item.get("title", title)
|
||
st = item.get("status", status)
|
||
bc = item.get("batch", batch)
|
||
mc = item.get("max_chars", max_chars)
|
||
else:
|
||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||
if t is None or not str(t).strip():
|
||
continue
|
||
if bc:
|
||
robot.send_in_batches(str(ti), str(t), status=st,
|
||
server_name=server_name, max_chars=mc)
|
||
else:
|
||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||
sent += 1
|
||
last_title, last_status = ti, st
|
||
|
||
if sent == 0:
|
||
return {"success": False, "message": "通知文本为空"}
|
||
if len(items) == 1:
|
||
return {"success": True,
|
||
"message": f"已推送通知 [{env_key}/{last_status}]:{last_title}"}
|
||
return {"success": True, "message": f"已推送 {sent} 条通知 [{env_key}]"}
|
||
except Exception as exc: # noqa: BLE001 - 兼容旧返回约定
|
||
return {"success": False, "message": mask(exc)}
|
||
|
||
|
||
#: 旧入口名兼容
|
||
main = push
|
||
|
||
|
||
__all__ = [
|
||
"DEFAULT_BATCH_SIZE",
|
||
"DEFAULT_MAX_CHARS",
|
||
"DEFAULT_TITLE",
|
||
"DingTalkRobot",
|
||
"Robot",
|
||
"STATUS_COLORS",
|
||
"build_sign",
|
||
"build_url",
|
||
"compose_batch_messages",
|
||
"main",
|
||
"push",
|
||
"render_markdown",
|
||
"split_by_chars",
|
||
]
|