# -*- coding: utf-8 -*- """XQ0005 插件 - 钉钉群机器人推送(仅标准库,符合插件自包含约束)。 推送原理(HTTP Webhook):按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名, 向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次(项目级重试约定)。 限制说明:群机器人只能发文本/Markdown,不能发文件附件——结果工作簿留在本机输出目录, 消息里给出绝对路径,由人工自取(与影刀版「发 xlsx 到群」的差异点)。 """ import base64 import hashlib import hmac import json import time import urllib.parse import urllib.request from ..config import logger DEFAULT_TIMEOUT = 10 DEFAULT_RETRY_TIMES = 3 def _build_sign(secret, timestamp_ms): """按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。""" string_to_sign = f"{timestamp_ms}\n{secret}" hmac_code = hmac.new(secret.encode("utf-8"), string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest() return urllib.parse.quote_plus(base64.b64encode(hmac_code)) def _build_url(webhook, secret=""): """拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。""" if not secret: return webhook ts = int(round(time.time() * 1000)) separator = "&" if "?" in webhook else "?" return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}" def send_markdown(webhook, secret, title, text): """向群机器人推送 Markdown 消息,返回 {success, message};webhook 为空时跳过。""" webhook = (webhook or "").strip() if not webhook: return {"success": False, "message": "未配置 Webhook,跳过推送"} payload = { "msgtype": "markdown", "markdown": {"title": title or "通知", "text": text or ""}, } body = json.dumps(payload, ensure_ascii=False).encode("utf-8") url = _build_url(webhook, (secret or "").strip()) last_err = "" for attempt in range(1, DEFAULT_RETRY_TIMES + 1): try: req = urllib.request.Request( url, data=body, method="POST", headers={"Content-Type": "application/json; charset=utf-8"}) with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT) as resp: raw = resp.read().decode("utf-8", errors="replace") data = json.loads(raw) if raw else {} if data.get("errcode") == 0: logger.info("钉钉群消息推送成功") return {"success": True, "message": "ok"} last_err = f"errcode={data.get('errcode')} errmsg={data.get('errmsg')}" except Exception as e: last_err = str(e) logger.warning("钉钉推送第 %d/%d 次失败:%s", attempt, DEFAULT_RETRY_TIMES, last_err) if attempt < DEFAULT_RETRY_TIMES: time.sleep(1.0 * attempt) return {"success": False, "message": last_err}