This commit is contained in:
eric
2026-04-07 00:31:43 -05:00
parent a34217b182
commit e12420cc48
2 changed files with 91 additions and 6 deletions

View File

@@ -0,0 +1,70 @@
"""
微信开放平台「小程序卡片」客服消息 msg 结构(与发送客服消息文档一致)。
字段title, appid, pagepath, thumb_media_id, thumb_url。
"""
from __future__ import annotations
import os
from typing import Any, Mapping, Optional
from urllib.parse import quote
# 默认值可通过环境变量覆盖,便于不同部署环境配置素材与小程序信息
_DEFAULT_TITLE = (os.getenv("CHATBOT_MINIPROGRAM_TITLE") or "openai对话插件").strip()
_DEFAULT_APPID = (os.getenv("CHATBOT_MINIPROGRAM_APPID") or "wx8c631f7e9f2465e1").strip()
_DEFAULT_PAGEPATH = (os.getenv("CHATBOT_MINIPROGRAM_PAGEPATH") or "pages/index/index").strip()
_DEFAULT_THUMB_MEDIA_ID = (
os.getenv("CHATBOT_MINIPROGRAM_THUMB_MEDIA_ID") or "KegpipQG9t-klMo25My4e8zpBjhjg3JMrMSpgjikB4U"
).strip()
_DEFAULT_THUMB_URL = (
os.getenv("CHATBOT_MINIPROGRAM_THUMB_URL")
or "http://mmbiz.qpic.cn/mmbiz_png/W3gQtpV3j8BYhWgfHT5Hfg6auN94c2ec4BBhDOMtPQrx6vEMc1rR4iaDKxDLOfZ1jBUqIEEY4YpvEj6ktSyXT7g/0?wx_fmt=png"
).strip()
def normalize_miniprogrampage_msg(msg: Mapping[str, Any]) -> dict:
"""仅保留文档约定的 miniprogrampage 五字段,避免多余键导致客户端不渲染。"""
raw = msg.get("miniprogrampage") if isinstance(msg, dict) else None
inner = raw if isinstance(raw, dict) else {}
return {
"miniprogrampage": {
"title": str(inner.get("title", "")),
"appid": str(inner.get("appid", "")),
"pagepath": str(inner.get("pagepath", "")),
"thumb_media_id": str(inner.get("thumb_media_id", "")),
"thumb_url": str(inner.get("thumb_url", "")),
}
}
def build_miniprogram_card_msg(
*,
user_id: str = "",
title: Optional[str] = None,
appid: Optional[str] = None,
pagepath: Optional[str] = None,
thumb_media_id: Optional[str] = None,
thumb_url: Optional[str] = None,
append_userid_to_pagepath: bool = True,
) -> dict:
"""
返回完整客服 msg{\"miniprogrampage\": {...}}。
若 append_userid_to_pagepath 且 user_id 非空,在 pagepath 上追加 ?userid=(已有查询串则用 &)。
"""
uid = (user_id or "").strip()
base_path = (pagepath if pagepath is not None else _DEFAULT_PAGEPATH).strip()
if append_userid_to_pagepath and uid:
sep = "&" if "?" in base_path else "?"
base_path = f"{base_path}{sep}userid={quote(uid, safe='')}"
return {
"miniprogrampage": {
"title": str(title if title is not None else _DEFAULT_TITLE),
"appid": str(appid if appid is not None else _DEFAULT_APPID),
"pagepath": base_path,
"thumb_media_id": str(thumb_media_id if thumb_media_id is not None else _DEFAULT_THUMB_MEDIA_ID),
"thumb_url": str(thumb_url if thumb_url is not None else _DEFAULT_THUMB_URL),
}
}