From 28ce06c92de9bf8b06226991ef11718aa4e6cc9a Mon Sep 17 00:00:00 2001 From: AoXuan Date: Sat, 27 Sep 2025 16:48:46 +0800 Subject: [PATCH] =?UTF-8?q?refactor(notification):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E8=A7=A3=E6=9E=90=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81JSON=E5=92=8C=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/notification.py | 45 +++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/app/services/notification.py b/app/services/notification.py index 9c1ddb0..aa31358 100644 --- a/app/services/notification.py +++ b/app/services/notification.py @@ -203,15 +203,48 @@ class Notification: "time": datetime.now().strftime("%H:%M:%S") } - # 替换模板中的变量 - formatted_template = template.format(**template_vars) + logger.debug(f"原始模板: {template}") + logger.debug(f"模板变量: {template_vars}") - # 尝试解析为JSON + # 先尝试作为JSON模板处理 try: - data = json.loads(formatted_template) + # 解析模板为JSON对象,然后替换其中的变量 + template_obj = json.loads(template) + + # 递归替换JSON对象中的变量 + def replace_variables(obj): + if isinstance(obj, dict): + return {k: replace_variables(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [replace_variables(item) for item in obj] + elif isinstance(obj, str): + result = obj + for key, value in template_vars.items(): + result = result.replace(f"{{{key}}}", str(value)) + return result + else: + return obj + + data = replace_variables(template_obj) + logger.debug(f"成功解析JSON模板: {data}") + except json.JSONDecodeError: - # 如果不是JSON格式,作为纯文本发送 - data = formatted_template + # 如果不是有效的JSON,作为字符串模板处理 + logger.debug("模板不是有效JSON,作为字符串模板处理") + formatted_template = template + for key, value in template_vars.items(): + # 转义特殊字符以避免JSON解析错误 + safe_value = str(value).replace('"', '\\"').replace('\n', '\\n').replace('\r', '\\r') + formatted_template = formatted_template.replace(f"{{{key}}}", safe_value) + + # 再次尝试解析为JSON + try: + data = json.loads(formatted_template) + logger.debug(f"字符串模板解析为JSON成功: {data}") + except json.JSONDecodeError: + # 最终作为纯文本发送 + data = formatted_template + logger.debug(f"作为纯文本发送: {data}") except Exception as e: logger.warning(f"模板解析失败,使用默认格式: {e}")