219 lines
7.2 KiB
Python
219 lines
7.2 KiB
Python
#!/usr/bin/env python3
|
||
"""Send a sanitized CMB mail task failure notice to a DingTalk group robot."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import re
|
||
import sys
|
||
import urllib.error
|
||
import urllib.request
|
||
from datetime import date, datetime, timedelta
|
||
from pathlib import Path
|
||
from urllib.parse import parse_qs, urlparse
|
||
from zoneinfo import ZoneInfo
|
||
|
||
|
||
class NotificationError(RuntimeError):
|
||
"""A safe, user-facing notification error."""
|
||
|
||
|
||
def shanghai_yesterday() -> date:
|
||
return datetime.now(ZoneInfo("Asia/Shanghai")).date() - timedelta(days=1)
|
||
|
||
|
||
def normalized_date(value: str | None) -> str:
|
||
if not value:
|
||
return shanghai_yesterday().isoformat()
|
||
try:
|
||
parsed = date.fromisoformat(value)
|
||
except ValueError as exception:
|
||
raise NotificationError("--date 必须使用 YYYY-MM-DD 格式。") from exception
|
||
if parsed.isoformat() != value:
|
||
raise NotificationError("--date 必须使用 YYYY-MM-DD 格式。")
|
||
return value
|
||
|
||
|
||
def safe_reason(value: str) -> str:
|
||
value = re.sub(r"[\r\n\t]+", " ", value)
|
||
value = re.sub(r"https?://\S+", "[地址已隐藏]", value, flags=re.IGNORECASE)
|
||
value = re.sub(
|
||
r"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}",
|
||
"[邮箱已隐藏]",
|
||
value,
|
||
flags=re.IGNORECASE,
|
||
)
|
||
return value[:200] or "服务器日志已记录具体错误。"
|
||
|
||
|
||
def notification_message(
|
||
target_date: str,
|
||
failure_type: str,
|
||
reason: str,
|
||
*,
|
||
test: bool,
|
||
) -> tuple[str, str]:
|
||
if test:
|
||
return (
|
||
"招商银行邮件任务失败:通知通道测试",
|
||
"\n".join(
|
||
[
|
||
"### 招商银行邮件任务失败:通知通道测试",
|
||
"- 接收方式:生产服务器直接发送至钉钉群机器人",
|
||
"- 用途:仅发送招商银行邮件任务异常提醒",
|
||
"- 结果:通道已接通",
|
||
]
|
||
),
|
||
)
|
||
|
||
labels = {
|
||
"auth": "邮箱授权失效或登录失败",
|
||
"config": "任务配置缺失",
|
||
"not_found": "未找到当天招商银行账单邮件",
|
||
"download": "账单下载失败",
|
||
"archive": "账单解压或安全校验失败",
|
||
"import": "银行账单导入失败",
|
||
"unknown": "任务执行失败",
|
||
}
|
||
return (
|
||
"招商银行邮件任务失败",
|
||
"\n".join(
|
||
[
|
||
"### 招商银行邮件任务失败",
|
||
f"- 账单日期:{target_date}",
|
||
f"- 失败类型:{labels.get(failure_type, labels['unknown'])}",
|
||
"- 执行结果:07:00、07:10 两次均失败",
|
||
f"- 原因:{reason}",
|
||
"请检查服务器任务日志及 163 邮箱授权状态。",
|
||
]
|
||
),
|
||
)
|
||
|
||
|
||
def load_webhook(path: Path) -> str:
|
||
try:
|
||
webhook = path.read_text(encoding="utf-8").strip()
|
||
except FileNotFoundError as exception:
|
||
raise NotificationError("未配置钉钉群机器人地址。") from exception
|
||
except OSError as exception:
|
||
raise NotificationError("无法读取钉钉群机器人配置。") from exception
|
||
|
||
parsed = urlparse(webhook)
|
||
token = parse_qs(parsed.query).get("access_token", [""])
|
||
if (
|
||
parsed.scheme != "https"
|
||
or parsed.hostname != "oapi.dingtalk.com"
|
||
or parsed.path != "/robot/send"
|
||
or not token
|
||
or not token[0].strip()
|
||
):
|
||
raise NotificationError("钉钉群机器人地址无效。")
|
||
|
||
return webhook
|
||
|
||
|
||
def response_body(response: object) -> bytes:
|
||
read = getattr(response, "read", None)
|
||
return read() if callable(read) else b""
|
||
|
||
|
||
def api_error(body: bytes, status: int | None = None) -> str:
|
||
code = ""
|
||
message = ""
|
||
try:
|
||
payload = json.loads(body.decode("utf-8"))
|
||
if isinstance(payload, dict):
|
||
code = str(payload.get("errcode") or "").strip()
|
||
message = str(payload.get("errmsg") or "").strip()
|
||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||
pass
|
||
|
||
message = re.sub(r"https?://\S+", "[地址已隐藏]", message, flags=re.IGNORECASE)
|
||
message = message[:160]
|
||
parts = ["钉钉群机器人发送失败"]
|
||
if status is not None:
|
||
parts.append(f"HTTP {status}")
|
||
if code:
|
||
parts.append(f"errcode {code}")
|
||
if message:
|
||
parts.append(message)
|
||
return ":".join([parts[0], " ".join(parts[1:])]) if len(parts) > 1 else parts[0]
|
||
|
||
|
||
def send_message(
|
||
webhook: str,
|
||
title: str,
|
||
text: str,
|
||
*,
|
||
timeout: int = 15,
|
||
) -> None:
|
||
payload = json.dumps(
|
||
{
|
||
"msgtype": "markdown",
|
||
"markdown": {
|
||
"title": title,
|
||
"text": text,
|
||
},
|
||
},
|
||
ensure_ascii=False,
|
||
).encode("utf-8")
|
||
request = urllib.request.Request(
|
||
webhook,
|
||
data=payload,
|
||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||
method="POST",
|
||
)
|
||
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||
status = int(getattr(response, "status", response.getcode()))
|
||
body = response_body(response)
|
||
except urllib.error.HTTPError as exception:
|
||
raise NotificationError(api_error(exception.read(), exception.code)) from exception
|
||
except urllib.error.URLError as exception:
|
||
reason = re.sub(r"https?://\S+", "[地址已隐藏]", str(exception.reason), flags=re.IGNORECASE)
|
||
raise NotificationError(f"无法连接钉钉群机器人:{reason[:160]}") from exception
|
||
|
||
if status < 200 or status >= 300:
|
||
raise NotificationError(api_error(body, status))
|
||
try:
|
||
result = json.loads(body.decode("utf-8"))
|
||
except (UnicodeDecodeError, json.JSONDecodeError) as exception:
|
||
raise NotificationError("钉钉群机器人返回了无法识别的结果。") from exception
|
||
if not isinstance(result, dict) or int(result.get("errcode", -1)) != 0:
|
||
raise NotificationError(api_error(body, status))
|
||
|
||
|
||
def parser() -> argparse.ArgumentParser:
|
||
root = argparse.ArgumentParser(description="招商银行邮件任务钉钉群机器人提醒")
|
||
root.add_argument("--webhook-file", required=True, help="仅包含群机器人 Webhook 的本地文件")
|
||
root.add_argument("--date", help="账单日期 YYYY-MM-DD;默认前一天")
|
||
root.add_argument("--type", default="unknown", help="失败类型")
|
||
root.add_argument("--reason", default="", help="已脱敏的简短失败原因")
|
||
root.add_argument("--test", action="store_true", help="发送通道测试消息")
|
||
return root
|
||
|
||
|
||
def main() -> int:
|
||
args = parser().parse_args()
|
||
try:
|
||
target_date = normalized_date(args.date)
|
||
webhook = load_webhook(Path(args.webhook_file))
|
||
title, text = notification_message(
|
||
target_date,
|
||
args.type or "unknown",
|
||
safe_reason(args.reason),
|
||
test=args.test,
|
||
)
|
||
send_message(webhook, title, text)
|
||
print("钉钉群机器人通知通道测试已发送。" if args.test else "钉钉群机器人失败提醒已发送。")
|
||
return 0
|
||
except NotificationError as exception:
|
||
print(str(exception), file=sys.stderr)
|
||
return 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|