fix(cmcc): webhook 400 根因 — 模板替换破坏 JSON 合法性

真机 2026-11-09 08:40 首次推送 webhook 得 HTTP 400。复现确认:
WEBHOOK_BODY 模板 '{"title":"$title","content":"$content"}' 做字符串替换后,
content 里的换行是裸 LF → JSON 非法(Invalid control character at col 64)→ 400。

修复对齐 common.js 的既有做法:JSON 类 Content-Type 下替换后先 json.loads 校验,
不合法就用 json.dumps 重建;非 JSON 类型走表单编码。
回归验证:旧逻辑产出非法 JSON,新逻辑 json.loads 通过。
This commit is contained in:
2026-11-09 13:20:57 +08:00
parent d6abdc59a3
commit 36cb329864

View File

@@ -157,12 +157,22 @@ def send_notify(title, content):
sent = False
if hook:
try:
body = os.environ.get("WEBHOOK_BODY", "").strip()
if body:
body = body.replace("$title", title).replace("$content", content)
else:
ct = os.environ.get("WEBHOOK_CONTENT_TYPE", "application/json").strip()
tpl = os.environ.get("WEBHOOK_BODY", "").strip()
if tpl:
body = tpl.replace("$title", title).replace("$content", content)
# ★ 模板替换会打破 JSON:content 里有换行/引号时合法 JSON 变非法 → 服务端 400。
# common.js 的做法是 try JSON.parse 失败就重建,这里对齐(2026-11-09 真机 400 即此)。
if "json" in ct.lower():
try:
json.loads(body)
except Exception:
body = json.dumps({"title": title, "content": content}, ensure_ascii=False)
hdrs = {"Content-Type": os.environ.get("WEBHOOK_CONTENT_TYPE", "application/json")}
elif "json" in ct.lower():
body = json.dumps({"title": title, "content": content}, ensure_ascii=False)
else:
body = "title=%s&content=%s" % (title, content)
hdrs = {"Content-Type": ct}
for ln in os.environ.get("WEBHOOK_HEADERS", "").splitlines():
if ":" in ln:
k, v = ln.split(":", 1)