Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c0dab1e63 | ||
|
|
80a4b2d0f9 | ||
|
|
d16f188845 | ||
|
|
c98bd91fb9 | ||
|
|
d695f87e33 | ||
|
|
256ba2c52b |
223
README.md
223
README.md
@@ -1,92 +1,199 @@
|
||||
# chatbot
|
||||
# chatbot(微信对话回调服务)
|
||||
|
||||
本项目是一个基于 FastAPI 的微信对话开放平台回调服务,核心目标是:
|
||||
|
||||
- 接收并解密公众号私信回调(接口 A)
|
||||
- 根据关键词回复用户(支持 H5 卡片)
|
||||
- 后台触发抓包接口 B 获取会话列表
|
||||
- 将用户资料同步到 PocketBase
|
||||
|
||||
## Getting started
|
||||
---
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
## 一、当前实现状态
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
### 1) 回调入口(接口 A)
|
||||
|
||||
## Add your files
|
||||
- 支持 `POST /`
|
||||
- 支持 `POST /wechat/thirdapi`
|
||||
- 支持加密请求体解析
|
||||
- 支持解密后明文为 JSON / XML 两种格式
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
### 2) 关键词回复
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin http://gitlab.yidooplanet.com/gitlab-instance-0a899031/chatbot.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
内置规则:
|
||||
|
||||
- 包含 `电子书`:返回“数字游民”H5 内容
|
||||
- 包含 `群`:返回“异度星球”H5 内容
|
||||
- 其他内容:返回默认引导文案
|
||||
|
||||
### 3) 接口 B(抓包)
|
||||
|
||||
用于拉取会话列表(数据同步用途):
|
||||
|
||||
- `https://chatbot.weixin.qq.com/miniopenai/manualservice/getaccessstautuslist`
|
||||
|
||||
### 4) PocketBase 同步
|
||||
|
||||
将用户资料写入 `wechat_private_users`,字段包含:
|
||||
|
||||
- `userid`
|
||||
- `channel_id`
|
||||
- `nick`
|
||||
- `avatar`
|
||||
- `source_query`
|
||||
- `source_message_id`
|
||||
- `source_message_time`
|
||||
- `matched_last_msg`
|
||||
- `matched_last_msg_id`
|
||||
- `matched_last_msg_time`
|
||||
- `raw_contact`
|
||||
|
||||
---
|
||||
|
||||
## 二、项目结构
|
||||
|
||||
```text
|
||||
chatbot/
|
||||
├── main.py # 回调主流程、关键词逻辑、B同步、PB写库、调试接口
|
||||
├── crypto_utils.py # AES加解密、签名
|
||||
├── config.py # 应用配置(A/B/PB)
|
||||
├── run.py # 启动入口(8001)
|
||||
├── requirements.txt # 依赖
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
---
|
||||
|
||||
- [ ] [Set up project integrations](http://gitlab.yidooplanet.com/gitlab-instance-0a899031/chatbot/-/settings/integrations)
|
||||
## 三、快速启动
|
||||
|
||||
## Collaborate with your team
|
||||
### 1) 安装依赖
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## Test and Deploy
|
||||
### 2) 启动
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
```bash
|
||||
python run.py
|
||||
```
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
默认端口:
|
||||
|
||||
***
|
||||
- `http://0.0.0.0:8001`
|
||||
|
||||
# Editing this README
|
||||
---
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
## 四、配置说明(config.py)
|
||||
|
||||
## Suggestions for a good README
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
### 1) 接口 A 配置
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
- `APP_ID`
|
||||
- `TOKEN`
|
||||
- `ENCODING_AES_KEY`
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
这些值必须与微信对话平台后台一致。
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
### 2) PocketBase 配置
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
- `PB_URL`
|
||||
- `PB_ADMIN_EMAIL`
|
||||
- `PB_ADMIN_PASSWORD`
|
||||
- `PB_COLLECTION`
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
当前策略:
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
- Windows 本地调试默认使用 `PB_DOMAIN_URL`
|
||||
- 非 Windows 默认使用 `PB_INTERNAL_URL`
|
||||
- 若设置环境变量 `PB_URL`,优先使用环境变量
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
### 3) 接口 B 配置
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
- `PM_SYNC_AUTHTOKEN`
|
||||
- `PM_SYNC_DEFAULT_WXBOT_BID`
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
说明:B 是后台同步数据源,不影响 A 主回复链路。
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
---
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
## 五、回调处理流程
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
1. 微信平台回调到 A(`/` 或 `/wechat/thirdapi`)
|
||||
2. 服务端读取 body 并解密
|
||||
3. 解析为统一字段(`UserId`、`Query`、`Timestamp` 等)
|
||||
4. 关键词命中后生成回复内容
|
||||
5. 主流程优先返回(保证用户体验)
|
||||
6. 后台异步触发 B 接口
|
||||
7. 匹配用户并同步到 PocketBase
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
---
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
## 六、接口清单
|
||||
|
||||
### 1) 业务接口
|
||||
|
||||
- `POST /`
|
||||
- `POST /wechat/thirdapi`
|
||||
|
||||
### 2) 调试接口
|
||||
|
||||
- `GET /health`
|
||||
- `GET /debug/echo`
|
||||
- `POST /debug/sync-test`
|
||||
|
||||
### 3) 调试页面
|
||||
|
||||
- `GET /private-message`
|
||||
|
||||
用于测试 B 查询、Token 分析、用户列表展示。
|
||||
|
||||
---
|
||||
|
||||
## 七、PocketBase 集合建议
|
||||
|
||||
集合名:`wechat_private_users`
|
||||
|
||||
建议索引:
|
||||
|
||||
- `userid + channel_id` 组合索引
|
||||
- 或 `source_message_id` 唯一索引(若来源稳定唯一)
|
||||
|
||||
---
|
||||
|
||||
## 八、常见问题排查
|
||||
|
||||
### Q1:回调收到了但用户没看到回复
|
||||
|
||||
- 检查 `APP_ID/TOKEN/ENCODING_AES_KEY` 是否和后台一致
|
||||
- 检查回调 URL 是否为当前服务地址
|
||||
- 查看日志中是否有解密失败/解析失败
|
||||
|
||||
### Q2:B 接口正常,PB 失败
|
||||
|
||||
通常是 PB 地址或认证路径问题:
|
||||
|
||||
- 已兼容 `/api/admins/auth-with-password`
|
||||
- 已兼容 `/api/collections/_superusers/auth-with-password`
|
||||
|
||||
### Q3:B 或 PB 失败会不会影响用户回复
|
||||
|
||||
不会。当前设计是:
|
||||
|
||||
- 关键词回复优先
|
||||
- B/PB 为后台任务,失败只记日志
|
||||
|
||||
---
|
||||
|
||||
## 九、参考文档
|
||||
|
||||
- 微信开放文档(发送客服消息):
|
||||
<https://developers.weixin.qq.com/doc/aispeech/confapi/thirdkefu/sendmsg.html>
|
||||
|
||||
---
|
||||
|
||||
## 十、后续优化建议
|
||||
|
||||
- 将关键词规则做成数据库配置化
|
||||
- 增加持久化幂等(避免服务重启后重复处理)
|
||||
- 增加结构化日志和告警
|
||||
- 将敏感配置迁移到环境变量统一管理
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
52
config.py
52
config.py
@@ -1,3 +1,49 @@
|
||||
APP_ID = "fXYWvGfq04uMScP"
|
||||
TOKEN = "EWRotyMHfTLAlYmCHpdH8AZcuZPBHn"
|
||||
ENCODING_AES_KEY = "1wJZiJm8URfRjkHu1QfIVDeNFc2jbzzeCZqvhQecsCx"
|
||||
import os
|
||||
|
||||
# 机器人开放API配置(可切换)
|
||||
# 当前默认调试:Eric在旅行
|
||||
OPEN_API_PROFILES = {
|
||||
"eric": {
|
||||
"name": "Eric在旅行",
|
||||
"APP_ID": "fXYWvGfq04uMScP",
|
||||
"TOKEN": "EWRotyMHfTLAlYmCHpdH8AZcuZPBHn",
|
||||
"ENCODING_AES_KEY": "1wJZiJm8URfRjkHu1QfIVDeNFc2jbzzeCZqvhQecsCx",
|
||||
},
|
||||
"xidu": {
|
||||
"name": "异度世界",
|
||||
"APP_ID": "LTKfSFeK0h8TRLM",
|
||||
"TOKEN": "64DbvAd5m7YOJ1XslyMgJ9V42jDIUH",
|
||||
"ENCODING_AES_KEY": "KCZGtPDjqFZnBuApvG3xqhvHUMnqFHbC5cnD23HKACX",
|
||||
},
|
||||
}
|
||||
|
||||
# 可通过环境变量 CHATBOT_ACTIVE_PROFILE 切换:eric / xidu
|
||||
ACTIVE_PROFILE = (os.getenv("CHATBOT_ACTIVE_PROFILE") or "eric").strip().lower()
|
||||
if ACTIVE_PROFILE not in OPEN_API_PROFILES:
|
||||
ACTIVE_PROFILE = "eric"
|
||||
|
||||
APP_ID = OPEN_API_PROFILES[ACTIVE_PROFILE]["APP_ID"]
|
||||
TOKEN = OPEN_API_PROFILES[ACTIVE_PROFILE]["TOKEN"]
|
||||
ENCODING_AES_KEY = OPEN_API_PROFILES[ACTIVE_PROFILE]["ENCODING_AES_KEY"]
|
||||
|
||||
# PocketBase 自动切换策略:
|
||||
# - 本地调试(Windows)优先使用数据库域名
|
||||
# - 线上(非 Windows)优先使用内网 IP+端口
|
||||
# 你也可以通过环境变量 PB_URL 强制覆盖。
|
||||
PB_DOMAIN_URL = "https://pocketbase.hackrobot.cn"
|
||||
PB_INTERNAL_URL = "http://127.0.0.1:8090"
|
||||
_pb_force = (os.getenv("PB_URL") or "").strip()
|
||||
if _pb_force:
|
||||
PB_URL = _pb_force
|
||||
elif os.name == "nt":
|
||||
PB_URL = PB_DOMAIN_URL
|
||||
else:
|
||||
PB_URL = PB_INTERNAL_URL
|
||||
|
||||
PB_ADMIN_EMAIL = "xiaoshuang.eric@gmail.com"
|
||||
PB_ADMIN_PASSWORD = "Xiao4669805@"
|
||||
PB_COLLECTION = "wechat_private_users"
|
||||
|
||||
# A 回调触发 B 接口同步的默认配置
|
||||
PM_SYNC_AUTHTOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyaWQiOjE5MzE1MjcsIm9wZW5pZCI6Im85VS04NW1DSXZ0eDZ0a0pteTQyMkkzcUNHVWciLCJzaWduZXRpbWUiOjE3NzQ5MzM0NDQ4MTgsImlhdCI6MTc3NDkzMzQ0NCwiZXhwIjoxNzc3NTI1NDQ0fQ.iC9vdjBqa2LGlqA6F-Dg4GcfDyv3Rp8JwpBaO3j_eE4"
|
||||
PM_SYNC_DEFAULT_WXBOT_BID = "75021053883a9090c67d5becde7f4b0a"
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import struct
|
||||
from typing import Tuple
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
@@ -34,16 +36,43 @@ def get_aes_key_and_iv(encoding_aes_key: str) -> Tuple[bytes, bytes]:
|
||||
|
||||
def aes_decrypt_base64(cipher_b64: str, encoding_aes_key: str) -> str:
|
||||
aes_key, iv = get_aes_key_and_iv(encoding_aes_key)
|
||||
cipher_bytes = base64.b64decode(cipher_b64)
|
||||
# 回调密文偶尔会带换行/空白,先规整再补齐 base64 padding。
|
||||
compact = "".join(str(cipher_b64 or "").split())
|
||||
compact += "=" * (-len(compact) % 4)
|
||||
cipher_bytes = base64.b64decode(compact)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
decrypted = cipher.decrypt(cipher_bytes)
|
||||
decrypted = pkcs5_unpadding(decrypted)
|
||||
# 兼容两种格式:
|
||||
# 1) 微信消息体:16B随机串 + 4B长度 + 明文 + appid
|
||||
# 2) 纯文本:直接是明文 JSON/XML
|
||||
try:
|
||||
if len(decrypted) < 20:
|
||||
raise ValueError("payload too short")
|
||||
content = decrypted[16:]
|
||||
msg_len = struct.unpack("!I", content[:4])[0]
|
||||
msg_start = 4
|
||||
msg_end = msg_start + msg_len
|
||||
if msg_end > len(content):
|
||||
raise ValueError("msg length out of range")
|
||||
msg = content[msg_start:msg_end]
|
||||
text = msg.decode("utf-8")
|
||||
if text:
|
||||
return text
|
||||
except Exception:
|
||||
pass
|
||||
return decrypted.decode("utf-8")
|
||||
|
||||
|
||||
def aes_encrypt_base64(plaintext: str, encoding_aes_key: str) -> str:
|
||||
def aes_encrypt_base64(plaintext: str, encoding_aes_key: str, app_id: str | None = None) -> str:
|
||||
aes_key, iv = get_aes_key_and_iv(encoding_aes_key)
|
||||
data = plaintext.encode("utf-8")
|
||||
raw = plaintext.encode("utf-8")
|
||||
if app_id:
|
||||
# 微信消息体格式:16B随机串 + 4B网络序长度 + 明文 + appid
|
||||
data = os.urandom(16) + struct.pack("!I", len(raw)) + raw + app_id.encode("utf-8")
|
||||
else:
|
||||
# 纯明文格式
|
||||
data = raw
|
||||
padded = pkcs5_padding(data)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
encrypted = cipher.encrypt(padded)
|
||||
|
||||
669
main.py
669
main.py
@@ -1,14 +1,26 @@
|
||||
import json
|
||||
import logging
|
||||
import base64
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from fastapi import FastAPI, Request, HTTPException, BackgroundTasks
|
||||
from fastapi.responses import PlainTextResponse, HTMLResponse
|
||||
|
||||
from config import APP_ID, TOKEN, ENCODING_AES_KEY
|
||||
from config import (
|
||||
APP_ID,
|
||||
TOKEN,
|
||||
ENCODING_AES_KEY,
|
||||
PB_URL,
|
||||
PB_ADMIN_EMAIL,
|
||||
PB_ADMIN_PASSWORD,
|
||||
PB_COLLECTION,
|
||||
PM_SYNC_AUTHTOKEN,
|
||||
PM_SYNC_DEFAULT_WXBOT_BID,
|
||||
)
|
||||
from crypto_utils import aes_decrypt_base64, aes_encrypt_base64, calc_signature
|
||||
|
||||
|
||||
@@ -17,6 +29,392 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(title="WeChat Dialog ThirdAPI Demo")
|
||||
|
||||
_processed_callback_cache: dict[str, int] = {}
|
||||
|
||||
|
||||
def _build_keyword_h5_obj(query: str, user_id: str) -> Optional[dict]:
|
||||
q = (query or "").strip()
|
||||
if not q:
|
||||
return None
|
||||
if "电子书" in q:
|
||||
return {
|
||||
"news": {
|
||||
"articles": [
|
||||
{
|
||||
"title": "数字游民",
|
||||
"description": "地理套利与自动化杠杆",
|
||||
"url": f"https://vip.hackrobot.cn/ebook?userid={user_id}",
|
||||
"picurl": "https://www.hackrobot.cn/static/images/images/dgnomad.png",
|
||||
"type": "h5",
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
if "群" in q:
|
||||
return {
|
||||
"news": {
|
||||
"articles": [
|
||||
{
|
||||
"title": "异度星球",
|
||||
"description": "电子书、视频教程、私密社群",
|
||||
"url": f"https://vip.hackrobot.cn?userid={user_id}",
|
||||
"picurl": "https://www.hackrobot.cn/static/images/images/dgnomad.png",
|
||||
"type": "h5",
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def _parse_decrypted_payload(decrypted_text: str) -> dict:
|
||||
"""
|
||||
同时兼容 JSON 与 XML 的回调明文,统一成业务侧可读字段。
|
||||
"""
|
||||
text = (decrypted_text or "").strip()
|
||||
if not text:
|
||||
raise ValueError("empty decrypted payload")
|
||||
|
||||
# 1) 优先 JSON
|
||||
if text.startswith("{"):
|
||||
obj = json.loads(text)
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("invalid json payload")
|
||||
obj["_payload_format"] = "json"
|
||||
return obj
|
||||
|
||||
# 2) XML(第三方客服回调常见)
|
||||
if text.startswith("<"):
|
||||
root = ET.fromstring(text)
|
||||
|
||||
def get_text(tag: str, default: str = "") -> str:
|
||||
node = root.find(tag)
|
||||
return (node.text or "").strip() if node is not None and node.text is not None else default
|
||||
|
||||
content_node = root.find("content")
|
||||
query = ""
|
||||
msg_type = get_text("msgtype", "")
|
||||
if content_node is not None:
|
||||
msg_node = content_node.find("msg")
|
||||
type_node = content_node.find("msgtype")
|
||||
if msg_node is not None and msg_node.text:
|
||||
query = msg_node.text.strip()
|
||||
if type_node is not None and type_node.text:
|
||||
msg_type = type_node.text.strip()
|
||||
|
||||
return {
|
||||
# 统一成原业务逻辑使用的字段
|
||||
"UserId": get_text("userid", ""),
|
||||
"Query": query,
|
||||
"Timestamp": get_text("createtime", ""),
|
||||
"MsgId": get_text("msgid", ""),
|
||||
"ChannelId": get_text("appid", ""),
|
||||
"MessageType": msg_type,
|
||||
# 保留原始字段便于日志与后续扩展
|
||||
"appid": get_text("appid", ""),
|
||||
"channel": get_text("channel", ""),
|
||||
"from": get_text("from", ""),
|
||||
"status": get_text("status", ""),
|
||||
"kfstate": get_text("kfstate", ""),
|
||||
"_payload_format": "xml",
|
||||
}
|
||||
|
||||
raise ValueError("unsupported decrypted payload format")
|
||||
|
||||
|
||||
def _build_keyword_h5_reply(query: str, user_id: str) -> Optional[str]:
|
||||
"""
|
||||
按关键词返回 H5 卡片(answer/short_answer 需为 JSON 字符串)。
|
||||
"""
|
||||
msg = _build_keyword_h5_obj(query, user_id)
|
||||
return json.dumps(msg, ensure_ascii=False) if msg else None
|
||||
|
||||
|
||||
def _build_xml_callback_reply(data: dict, answer_text: str) -> dict:
|
||||
"""
|
||||
XML 回调直接回包给平台,由平台转发给用户。
|
||||
返回结构按“userid/appid/content/channel/from”组织。
|
||||
"""
|
||||
userid = str(data.get("UserId", "")).strip()
|
||||
appid = str(data.get("ChannelId", "") or data.get("appid", "")).strip()
|
||||
channel_raw = str(data.get("channel", "0") or "0")
|
||||
try:
|
||||
channel = int(channel_raw)
|
||||
except Exception:
|
||||
channel = 0
|
||||
|
||||
# 关键词命中返回 H5 结构;其他走文本结构
|
||||
keyword_msg = _build_keyword_h5_obj(str(data.get("Query", "")), userid)
|
||||
content = keyword_msg if keyword_msg else {"msg": answer_text}
|
||||
|
||||
return {
|
||||
"userid": userid,
|
||||
"appid": appid,
|
||||
"content": content,
|
||||
"channel": channel,
|
||||
"from": 1,
|
||||
}
|
||||
|
||||
|
||||
def _safe_filter_value(value: str) -> str:
|
||||
return (value or "").replace("\\", "\\\\").replace('"', '\\"')
|
||||
|
||||
|
||||
def _to_int(value) -> Optional[int]:
|
||||
try:
|
||||
return int(str(value).strip())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
def _build_callback_dedupe_key(data: dict) -> str:
|
||||
userid = _normalize_text(data.get("UserId") or data.get("userId"))
|
||||
msg_id = _normalize_text(data.get("MsgId") or data.get("MessageId") or data.get("msgId"))
|
||||
ts = _normalize_text(data.get("Timestamp") or data.get("MessageTime") or data.get("msgTime"))
|
||||
query = _normalize_text(data.get("Query"))
|
||||
return "|".join([userid, msg_id, ts, query])
|
||||
|
||||
|
||||
def _is_duplicate_callback(data: dict, ttl_seconds: int = 3600) -> bool:
|
||||
"""
|
||||
回调幂等(进程内):同 userid/msg_id/time/query 在 TTL 内仅处理一次同步逻辑。
|
||||
不影响主回复。
|
||||
"""
|
||||
now_ts = int(time.time())
|
||||
# 清理过期 key,避免缓存无限增长
|
||||
expired = [k for k, exp in _processed_callback_cache.items() if exp <= now_ts]
|
||||
for k in expired:
|
||||
_processed_callback_cache.pop(k, None)
|
||||
|
||||
key = _build_callback_dedupe_key(data)
|
||||
if not key.strip("|"):
|
||||
return False
|
||||
if key in _processed_callback_cache:
|
||||
return True
|
||||
_processed_callback_cache[key] = now_ts + ttl_seconds
|
||||
return False
|
||||
|
||||
|
||||
def _extract_b_last_msg(contact: dict) -> dict:
|
||||
return (contact.get("lastMsg") or {}) if isinstance(contact, dict) else {}
|
||||
|
||||
|
||||
def _pick_best_contact_match(contacts: list, target_userid: str, source_query: str, source_msg_id: str, source_msg_time) -> Optional[dict]:
|
||||
"""
|
||||
在同 userid 的候选中做二次匹配:
|
||||
- msg_id 一致优先
|
||||
- 文本一致次优
|
||||
- 时间最接近再次优先
|
||||
"""
|
||||
if not target_userid:
|
||||
return None
|
||||
|
||||
same_user = [
|
||||
c for c in contacts
|
||||
if _normalize_text(c.get("userId") or c.get("userid")) == target_userid
|
||||
]
|
||||
if not same_user:
|
||||
return None
|
||||
|
||||
query_norm = _normalize_text(source_query)
|
||||
source_msg_id_norm = _normalize_text(source_msg_id)
|
||||
src_ts = _to_int(source_msg_time)
|
||||
|
||||
def score(contact: dict) -> tuple[int, int, int]:
|
||||
last_msg = _extract_b_last_msg(contact)
|
||||
last_msg_id = _normalize_text(last_msg.get("msgId") or last_msg.get("id"))
|
||||
last_content = _normalize_text(last_msg.get("content"))
|
||||
last_active = _to_int(contact.get("lastActiveTime"))
|
||||
|
||||
msg_id_hit = 1 if source_msg_id_norm and last_msg_id and source_msg_id_norm == last_msg_id else 0
|
||||
content_hit = 1 if query_norm and last_content and query_norm == last_content else 0
|
||||
# 时间越接近分越高(负值用于降序)
|
||||
if src_ts is None or last_active is None:
|
||||
time_delta = 10**12
|
||||
else:
|
||||
time_delta = abs(src_ts - last_active)
|
||||
return (msg_id_hit, content_hit, -time_delta)
|
||||
|
||||
return sorted(same_user, key=score, reverse=True)[0]
|
||||
|
||||
|
||||
async def _pb_upsert_user_profile(record: dict) -> None:
|
||||
"""
|
||||
使用 PocketBase Admin API upsert 用户资料。
|
||||
需要环境变量:
|
||||
- PB_URL
|
||||
- PB_ADMIN_EMAIL
|
||||
- PB_ADMIN_PASSWORD
|
||||
可选:
|
||||
- PB_COLLECTION(默认 wechat_private_users)
|
||||
"""
|
||||
pb_url = (PB_URL or "").rstrip("/")
|
||||
pb_admin_email = PB_ADMIN_EMAIL or ""
|
||||
pb_admin_password = PB_ADMIN_PASSWORD or ""
|
||||
pb_collection = PB_COLLECTION or "wechat_private_users"
|
||||
if not pb_url or not pb_admin_email or not pb_admin_password:
|
||||
logger.warning("PocketBase 配置不完整,跳过资料同步")
|
||||
return
|
||||
|
||||
userid = str(record.get("userid", "")).strip()
|
||||
channel_id = str(record.get("channel_id", "")).strip()
|
||||
if not userid:
|
||||
return
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10, verify=False) as client:
|
||||
auth_resp = await client.post(
|
||||
f"{pb_url}/api/admins/auth-with-password",
|
||||
json={"identity": pb_admin_email, "password": pb_admin_password},
|
||||
)
|
||||
# 兼容新旧 PocketBase:旧版本 admins,新版本 _superusers
|
||||
if auth_resp.status_code == 404:
|
||||
auth_resp = await client.post(
|
||||
f"{pb_url}/api/collections/_superusers/auth-with-password",
|
||||
json={"identity": pb_admin_email, "password": pb_admin_password},
|
||||
)
|
||||
auth_resp.raise_for_status()
|
||||
token = (auth_resp.json() or {}).get("token", "")
|
||||
if not token:
|
||||
logger.warning("PocketBase 登录无 token,跳过资料同步")
|
||||
return
|
||||
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
user_expr = _safe_filter_value(userid)
|
||||
chan_expr = _safe_filter_value(channel_id)
|
||||
filter_exp = f'userid="{user_expr}" && channel_id="{chan_expr}"' if channel_id else f'userid="{user_expr}"'
|
||||
list_resp = await client.get(
|
||||
f"{pb_url}/api/collections/{pb_collection}/records",
|
||||
params={"page": 1, "perPage": 1, "filter": filter_exp, "sort": "-updated"},
|
||||
headers=headers,
|
||||
)
|
||||
list_resp.raise_for_status()
|
||||
items = ((list_resp.json() or {}).get("items")) or []
|
||||
|
||||
if items:
|
||||
rid = items[0].get("id")
|
||||
if rid:
|
||||
patch_resp = await client.patch(
|
||||
f"{pb_url}/api/collections/{pb_collection}/records/{rid}",
|
||||
json=record,
|
||||
headers=headers,
|
||||
)
|
||||
patch_resp.raise_for_status()
|
||||
return
|
||||
|
||||
create_resp = await client.post(
|
||||
f"{pb_url}/api/collections/{pb_collection}/records",
|
||||
json=record,
|
||||
headers=headers,
|
||||
)
|
||||
create_resp.raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
logger.error("PocketBase 同步失败:%s", str(e))
|
||||
|
||||
|
||||
async def _sync_user_profile_from_b(data: dict) -> None:
|
||||
"""
|
||||
A 接口收到消息后,立即调用 B 接口拉取会话并同步用户资料到 PocketBase。
|
||||
环境变量:
|
||||
- PM_SYNC_AUTHTOKEN(必填)
|
||||
- PM_SYNC_DEFAULT_WXBOT_BID(可选)
|
||||
- PM_SYNC_BID_BY_CHANNEL_JSON(可选,形如 {"wx5cee...":"4888..."})
|
||||
"""
|
||||
authtoken = (PM_SYNC_AUTHTOKEN or "").strip()
|
||||
if not authtoken:
|
||||
logger.info("未配置 PM_SYNC_AUTHTOKEN,跳过 B 接口同步")
|
||||
return
|
||||
|
||||
channel_id = str(data.get("ChannelId", "") or data.get("channelId", "")).strip()
|
||||
# B 接口配置与 A 回调路由解耦:固定使用 B 的默认凭据。
|
||||
wxbot_bid = (PM_SYNC_DEFAULT_WXBOT_BID or "").strip()
|
||||
if not wxbot_bid:
|
||||
logger.warning("未配置可用 wxbot_bid,跳过 B 接口同步")
|
||||
return
|
||||
|
||||
target_userid = str(data.get("UserId", "") or data.get("userId", "")).strip()
|
||||
if not target_userid:
|
||||
return
|
||||
|
||||
if _is_duplicate_callback(data):
|
||||
logger.info("命中回调幂等缓存,跳过重复同步:userid=%s", target_userid)
|
||||
return
|
||||
|
||||
msg_id = str(data.get("MsgId", "") or data.get("MessageId", "") or data.get("msgId", "")).strip()
|
||||
msg_time = data.get("Timestamp", "") or data.get("MessageTime", "") or data.get("msgTime", "")
|
||||
query = str(data.get("Query", "")).strip()
|
||||
|
||||
b_resp = await query_private_messages(
|
||||
authtoken=authtoken,
|
||||
wxbot_bid=wxbot_bid,
|
||||
page=0,
|
||||
size=100,
|
||||
filter_value=0,
|
||||
request_id=f"thirdapi-{target_userid}",
|
||||
)
|
||||
contacts = b_resp.get("contacts") or []
|
||||
target = _pick_best_contact_match(
|
||||
contacts=contacts,
|
||||
target_userid=target_userid,
|
||||
source_query=query,
|
||||
source_msg_id=msg_id,
|
||||
source_msg_time=msg_time,
|
||||
)
|
||||
if not target:
|
||||
logger.info("B 接口未匹配到用户:%s", target_userid)
|
||||
return
|
||||
|
||||
last_msg = target.get("lastMsg") or {}
|
||||
record = {
|
||||
"userid": target_userid,
|
||||
"channel_id": channel_id,
|
||||
"nick": target.get("nick", ""),
|
||||
"avatar": target.get("headImg") or target.get("avatar") or target.get("headimgurl") or target.get("headImgUrl") or "",
|
||||
"source_query": query,
|
||||
"source_message_id": msg_id,
|
||||
"source_message_time": str(msg_time),
|
||||
"matched_last_msg": last_msg.get("content", ""),
|
||||
"matched_last_msg_id": str(last_msg.get("msgId", "") or last_msg.get("id", "")),
|
||||
"matched_last_msg_time": str(target.get("lastActiveTime", "")),
|
||||
"raw_contact": json.dumps(target, ensure_ascii=False),
|
||||
}
|
||||
await _pb_upsert_user_profile(record)
|
||||
|
||||
|
||||
async def _safe_sync_user_profile_from_b(data: dict) -> None:
|
||||
"""
|
||||
后台任务安全包装:B/PocketBase 失败只记日志,不抛异常影响 ASGI。
|
||||
"""
|
||||
try:
|
||||
await _sync_user_profile_from_b(data)
|
||||
except Exception:
|
||||
logger.error("后台同步失败(已忽略,不影响A接口主回复)")
|
||||
|
||||
|
||||
@app.post("/debug/sync-test")
|
||||
async def debug_sync_test(payload: dict):
|
||||
"""
|
||||
手动调试 A->B->PocketBase 同步链路。
|
||||
body 示例:
|
||||
{
|
||||
"UserId": "...",
|
||||
"ChannelId": "...",
|
||||
"Query": "电子书",
|
||||
"MsgId": "...",
|
||||
"Timestamp": 1774933444
|
||||
}
|
||||
"""
|
||||
await _sync_user_profile_from_b(payload or {})
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "sync triggered",
|
||||
"dedupe_key": _build_callback_dedupe_key(payload or {}),
|
||||
}
|
||||
|
||||
|
||||
async def handle_business(data: dict) -> str:
|
||||
"""
|
||||
@@ -39,22 +437,10 @@ async def handle_business(data: dict) -> str:
|
||||
# ]
|
||||
# return ";".join(parts)
|
||||
|
||||
# 当前示例:返回一个 H5 富文本结构(平台会对 short_answer 做 JSON.parse)
|
||||
h5_msg = {
|
||||
"news": {
|
||||
"articles": [
|
||||
{
|
||||
"title": "实时更新:新型肺炎疫情最新动态",
|
||||
"description": "腾讯新闻第一时间同步全国新型肺炎疫情动态,欢迎关注、转发",
|
||||
"url": "https://news.qq.com/zt2020/page/feiyan.htm",
|
||||
"picurl": "http://mmbiz.qpic.cn/mmbiz_jpg/W3gQtpV3j8D8kZRqfpTJlfVqubwgFQf47H0GWlGV6leaDF80ZpdtuFhQVsCsM3YKmwkujXzdjR2k6aWfA41ic7Q/0?wx_fmt=jpeg",
|
||||
"type": "h5",
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
# 按文档要求,answer/short_answer 是字符串,内部再 JSON.parse 才是对象
|
||||
return json.dumps(h5_msg, ensure_ascii=False)
|
||||
keyword_reply = _build_keyword_h5_reply(query, user_id)
|
||||
if keyword_reply:
|
||||
return keyword_reply
|
||||
return "1111111"
|
||||
|
||||
|
||||
def _decode_jwt_payload_without_verify(token: str) -> dict:
|
||||
@@ -106,7 +492,7 @@ async def query_private_messages(
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def _handle_wechat_request(request: Request, app_id: Optional[str]) -> str:
|
||||
async def _handle_wechat_request(request: Request, app_id: Optional[str], background_tasks: BackgroundTasks) -> str:
|
||||
"""
|
||||
公共处理逻辑:便于同时支持 "/" 和 "/wechat/thirdapi" 两种回调路径。
|
||||
"""
|
||||
@@ -127,11 +513,11 @@ async def _handle_wechat_request(request: Request, app_id: Optional[str]) -> str
|
||||
logger.info(f"收到原始 body(未解密,前 500 字符):{cipher_b64[:500]}")
|
||||
|
||||
# 平台当前实际发送的是 {"encrypted":"..."} 这一层 JSON,需要先解析再取字段
|
||||
if cipher_b64.startswith("{"):
|
||||
if "encrypted" in cipher_b64:
|
||||
try:
|
||||
outer = json.loads(cipher_b64)
|
||||
if isinstance(outer, dict) and "encrypted" in outer:
|
||||
cipher_b64 = str(outer["encrypted"]).replace("\n", "").strip()
|
||||
cipher_b64 = "".join(str(outer["encrypted"]).split()).strip()
|
||||
except Exception:
|
||||
# 如果解析失败,就按原始字符串继续处理(保持兼容)
|
||||
logger.warning("外层 JSON 解析失败,按原始 body 作为密文处理")
|
||||
@@ -146,12 +532,12 @@ async def _handle_wechat_request(request: Request, app_id: Optional[str]) -> str
|
||||
)
|
||||
raise HTTPException(status_code=400, detail="decrypt error")
|
||||
|
||||
# 4. 解析 JSON
|
||||
# 4. 解析明文(兼容 JSON/XML)
|
||||
try:
|
||||
data = json.loads(decrypted_json_str)
|
||||
except json.JSONDecodeError:
|
||||
logger.error(f"解密结果不是合法 JSON: {decrypted_json_str}")
|
||||
raise HTTPException(status_code=400, detail="invalid json in decrypted body")
|
||||
data = _parse_decrypted_payload(decrypted_json_str)
|
||||
except Exception:
|
||||
logger.error(f"解密结果无法解析为 JSON/XML: {decrypted_json_str}")
|
||||
raise HTTPException(status_code=400, detail="invalid decrypted payload")
|
||||
|
||||
# 5. 打印请求内容到终端日志(分析、显示,带中文注释)
|
||||
logger.info("收到微信第三方服务请求(已解密):")
|
||||
@@ -186,13 +572,19 @@ async def _handle_wechat_request(request: Request, app_id: Optional[str]) -> str
|
||||
except Exception:
|
||||
logger.exception("签名校验异常(忽略或按需处理)")
|
||||
|
||||
# 7. 根据业务逻辑构造应答
|
||||
# 7. 根据业务逻辑构造应答(关键词回复优先)
|
||||
try:
|
||||
answer_text = await handle_business(data)
|
||||
except Exception:
|
||||
logger.exception("业务处理异常,将返回兜底文案")
|
||||
answer_text = "系统繁忙,请稍后再试。"
|
||||
|
||||
# 7.1 主回复确定后再后台触发 B 同步,避免影响回复链路耗时
|
||||
background_tasks.add_task(_safe_sync_user_profile_from_b, data)
|
||||
if str(data.get("_payload_format", "")) == "xml":
|
||||
# XML 回调按“回调直接回复”处理,不依赖 sendmsg 权限
|
||||
resp_json_str = json.dumps(_build_xml_callback_reply(data, answer_text), ensure_ascii=False)
|
||||
else:
|
||||
resp_obj = {
|
||||
# 文本类型,内容为可被 JSON.parse 的 H5 结构字符串
|
||||
"answer_type": "text",
|
||||
@@ -200,12 +592,22 @@ async def _handle_wechat_request(request: Request, app_id: Optional[str]) -> str
|
||||
"short_answer": answer_text
|
||||
}
|
||||
}
|
||||
|
||||
resp_json_str = json.dumps(resp_obj, ensure_ascii=False)
|
||||
|
||||
# 8. 加密响应 JSON
|
||||
logger.info("回包明文(加密前): %s", resp_json_str)
|
||||
|
||||
# 8. 加密响应
|
||||
# - /?app_id=... 的第三方服务接口请求通常使用纯AES明文加密(不拼接 appid)
|
||||
# - XML 回调场景使用会话 appid 封装加密
|
||||
# - 其余 JSON 场景默认使用纯AES,提升兼容性
|
||||
response_app_id: Optional[str] = None
|
||||
if str(data.get("_payload_format", "")) == "xml":
|
||||
response_app_id = str(data.get("ChannelId", "") or data.get("appid", "")).strip() or APP_ID
|
||||
elif app_id:
|
||||
response_app_id = None
|
||||
logger.info("响应加密模式: %s", "envelope" if response_app_id else "plain")
|
||||
try:
|
||||
encrypted_resp = aes_encrypt_base64(resp_json_str, ENCODING_AES_KEY)
|
||||
encrypted_resp = aes_encrypt_base64(resp_json_str, ENCODING_AES_KEY, response_app_id)
|
||||
except Exception as e:
|
||||
logger.exception("响应 AES 加密失败")
|
||||
raise HTTPException(status_code=500, detail="encrypt error") from e
|
||||
@@ -215,21 +617,21 @@ async def _handle_wechat_request(request: Request, app_id: Optional[str]) -> str
|
||||
|
||||
|
||||
@app.post("/", response_class=PlainTextResponse)
|
||||
async def wechat_root(request: Request, app_id: Optional[str] = None):
|
||||
async def wechat_root(request: Request, background_tasks: BackgroundTasks, app_id: Optional[str] = None):
|
||||
"""
|
||||
有些配置示例直接写根路径,例如:
|
||||
url: http://example.com/
|
||||
这种情况下,微信会 POST 到 "/",所以这里也做同样处理。
|
||||
"""
|
||||
return await _handle_wechat_request(request, app_id)
|
||||
return await _handle_wechat_request(request, app_id, background_tasks)
|
||||
|
||||
|
||||
@app.post("/wechat/thirdapi", response_class=PlainTextResponse)
|
||||
async def wechat_thirdapi(request: Request, app_id: Optional[str] = None):
|
||||
async def wechat_thirdapi(request: Request, background_tasks: BackgroundTasks, app_id: Optional[str] = None):
|
||||
"""
|
||||
显式的 /wechat/thirdapi 路径,同样处理。
|
||||
"""
|
||||
return await _handle_wechat_request(request, app_id)
|
||||
return await _handle_wechat_request(request, app_id, background_tasks)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
@@ -314,7 +716,7 @@ def private_message_page():
|
||||
color: #cbd5e1;
|
||||
font-size: 13px;
|
||||
}
|
||||
textarea, input {
|
||||
textarea, input, select {
|
||||
width: 100%;
|
||||
border: 1px solid rgba(148, 163, 184, 0.35);
|
||||
background: rgba(15, 23, 42, 0.75);
|
||||
@@ -325,7 +727,7 @@ def private_message_page():
|
||||
outline: none;
|
||||
transition: border-color .2s, box-shadow .2s;
|
||||
}
|
||||
textarea:focus, input:focus {
|
||||
textarea:focus, input:focus, select:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.15);
|
||||
}
|
||||
@@ -362,6 +764,87 @@ def private_message_page():
|
||||
color: var(--ok);
|
||||
}
|
||||
.status.warn { color: var(--warn); }
|
||||
.panel-title {
|
||||
margin: 0 0 8px;
|
||||
font-size: 15px;
|
||||
color: #dbeafe;
|
||||
}
|
||||
.token-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
.token-kpi {
|
||||
border: 1px solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 12px;
|
||||
background: rgba(15, 23, 42, 0.55);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.token-kpi .label {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.token-kpi .value {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: #bfdbfe;
|
||||
}
|
||||
.user-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.user-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.2);
|
||||
border-radius: 12px;
|
||||
background: rgba(15, 23, 42, 0.55);
|
||||
padding: 10px;
|
||||
}
|
||||
.avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 999px;
|
||||
object-fit: cover;
|
||||
background: rgba(148, 163, 184, 0.2);
|
||||
border: 1px solid rgba(148, 163, 184, 0.35);
|
||||
}
|
||||
.avatar-placeholder {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 999px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(99, 102, 241, 0.35);
|
||||
color: #e0e7ff;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
border: 1px solid rgba(148, 163, 184, 0.35);
|
||||
}
|
||||
.user-meta {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
}
|
||||
.user-nick {
|
||||
font-size: 14px;
|
||||
color: #f1f5f9;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.user-id {
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
pre {
|
||||
margin: 0;
|
||||
background: #090d18;
|
||||
@@ -375,6 +858,7 @@ def private_message_page():
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.row { grid-template-columns: 1fr; }
|
||||
.token-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -383,6 +867,8 @@ def private_message_page():
|
||||
<section class="card">
|
||||
<h2>私信查询调试台</h2>
|
||||
<p class="sub">用于调试微信对话开放平台私信列表接口,支持一键查询、Token 过期分析与结果可视化。</p>
|
||||
<label>默认配置</label>
|
||||
<select id="presetSelect"></select>
|
||||
<label>authtoken</label>
|
||||
<textarea id="authtoken" rows="4" placeholder="粘贴 Charles 抓包中的 authtoken"></textarea>
|
||||
<label>wxbot_bid</label>
|
||||
@@ -406,6 +892,20 @@ def private_message_page():
|
||||
|
||||
<section class="card">
|
||||
<p id="status" class="status">等待操作...</p>
|
||||
<h3 class="panel-title">Token 过期信息</h3>
|
||||
<div id="tokenReport" class="token-grid">
|
||||
<div class="token-kpi">
|
||||
<div class="label">状态</div>
|
||||
<div id="tokenStatus" class="value">-</div>
|
||||
</div>
|
||||
<div class="token-kpi">
|
||||
<div class="label">剩余时间</div>
|
||||
<div id="tokenRemain" class="value">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<h3 class="panel-title" style="margin-top: 12px;">用户列表(userid / 头像 / 昵称)</h3>
|
||||
<div id="userList" class="user-list"></div>
|
||||
<h3 class="panel-title" style="margin-top: 12px;">原始返回</h3>
|
||||
<pre id="output">{
|
||||
"message": "点击上方按钮开始查询"
|
||||
}</pre>
|
||||
@@ -413,6 +913,47 @@ def private_message_page():
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const defaultPresets = [
|
||||
{
|
||||
id: 'eric-travel',
|
||||
name: 'Eric在旅行',
|
||||
authtoken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyaWQiOjE5MzE1MjcsIm9wZW5pZCI6Im85VS04NW1DSXZ0eDZ0a0pteTQyMkkzcUNHVWciLCJzaWduZXRpbWUiOjE3NzQ5MzM0NDQ4MTgsImlhdCI6MTc3NDkzMzQ0NCwiZXhwIjoxNzc3NTI1NDQ0fQ.iC9vdjBqa2LGlqA6F-Dg4GcfDyv3Rp8JwpBaO3j_eE4',
|
||||
wxbot_bid: '75021053883a9090c67d5becde7f4b0a',
|
||||
},
|
||||
{
|
||||
id: 'xidu-shijie',
|
||||
name: '异度世界',
|
||||
authtoken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyaWQiOjE5MzE1MjcsIm9wZW5pZCI6Im85VS04NW1DSXZ0eDZ0a0pteTQyMkkzcUNHVWciLCJzaWduZXRpbWUiOjE3NzQ5MzM0NDQ4MTgsImlhdCI6MTc3NDkzMzQ0NCwiZXhwIjoxNzc3NTI1NDQ0fQ.iC9vdjBqa2LGlqA6F-Dg4GcfDyv3Rp8JwpBaO3j_eE4',
|
||||
wxbot_bid: '4888c6ab5cb70dcc3adea1e2d2ff0201',
|
||||
},
|
||||
];
|
||||
|
||||
function initPresetSelector() {
|
||||
const select = document.getElementById('presetSelect');
|
||||
select.innerHTML = defaultPresets
|
||||
.map((item) => `<option value="${item.id}">${item.name}</option>`)
|
||||
.join('');
|
||||
select.addEventListener('change', () => {
|
||||
const preset = defaultPresets.find((x) => x.id === select.value);
|
||||
if (!preset) return;
|
||||
document.getElementById('authtoken').value = preset.authtoken;
|
||||
document.getElementById('wxbot_bid').value = preset.wxbot_bid;
|
||||
});
|
||||
if (defaultPresets.length > 0) {
|
||||
select.value = defaultPresets[0].id;
|
||||
select.dispatchEvent(new Event('change'));
|
||||
}
|
||||
}
|
||||
|
||||
function updatePresetAuthtoken() {
|
||||
const select = document.getElementById('presetSelect');
|
||||
const selectedId = select.value;
|
||||
const idx = defaultPresets.findIndex((x) => x.id === selectedId);
|
||||
if (idx >= 0) {
|
||||
defaultPresets[idx].authtoken = document.getElementById('authtoken').value.trim();
|
||||
}
|
||||
}
|
||||
|
||||
function setLoading(loading, text) {
|
||||
document.getElementById('queryBtn').disabled = loading;
|
||||
document.getElementById('analyzeBtn').disabled = loading;
|
||||
@@ -426,7 +967,47 @@ def private_message_page():
|
||||
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
function formatRemain(seconds) {
|
||||
if (typeof seconds !== 'number') return '-';
|
||||
if (seconds <= 0) return '已过期';
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const mins = Math.floor((seconds % 3600) / 60);
|
||||
return `${days}天 ${hours}小时 ${mins}分钟`;
|
||||
}
|
||||
|
||||
function renderTokenReport(report) {
|
||||
const statusEl = document.getElementById('tokenStatus');
|
||||
const remainEl = document.getElementById('tokenRemain');
|
||||
const statusText = report?.status || '-';
|
||||
const remainText = formatRemain(report?.analysis?.expires_in_seconds);
|
||||
statusEl.textContent = statusText;
|
||||
remainEl.textContent = remainText;
|
||||
statusEl.style.color = statusText.includes('过期') ? '#fca5a5' : '#86efac';
|
||||
remainEl.style.color = remainText === '已过期' ? '#fca5a5' : '#bfdbfe';
|
||||
}
|
||||
|
||||
function renderUsers(users) {
|
||||
const list = document.getElementById('userList');
|
||||
if (!Array.isArray(users) || users.length === 0) {
|
||||
list.innerHTML = '<div class="hint">当前暂无用户数据,先点击“查询私信”。</div>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = users.map((u) => {
|
||||
const nick = u.nick || '未命名用户';
|
||||
const uid = u.userId || '未知 userid';
|
||||
const avatar = u.avatar || '';
|
||||
const safeNick = String(nick).replace(/</g, '<').replace(/>/g, '>');
|
||||
const safeUid = String(uid).replace(/</g, '<').replace(/>/g, '>');
|
||||
const avatarHtml = avatar
|
||||
? `<img class="avatar" src="${avatar}" alt="${safeNick}" referrerpolicy="no-referrer" />`
|
||||
: `<div class="avatar-placeholder">${safeNick.slice(0, 1)}</div>`;
|
||||
return `<div class="user-item">${avatarHtml}<div class="user-meta"><div class="user-nick">${safeNick}</div><div class="user-id">${safeUid}</div></div></div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function queryPm() {
|
||||
updatePresetAuthtoken();
|
||||
const payload = {
|
||||
authtoken: document.getElementById('authtoken').value.trim(),
|
||||
wxbot_bid: document.getElementById('wxbot_bid').value.trim(),
|
||||
@@ -447,6 +1028,7 @@ def private_message_page():
|
||||
} else {
|
||||
document.getElementById('status').textContent = '查询成功';
|
||||
}
|
||||
renderUsers(data.users);
|
||||
render(data);
|
||||
} catch (err) {
|
||||
document.getElementById('status').classList.add('warn');
|
||||
@@ -458,6 +1040,7 @@ def private_message_page():
|
||||
}
|
||||
|
||||
async function analyzeToken() {
|
||||
updatePresetAuthtoken();
|
||||
const payload = {
|
||||
authtoken: document.getElementById('authtoken').value.trim(),
|
||||
};
|
||||
@@ -475,6 +1058,7 @@ def private_message_page():
|
||||
} else {
|
||||
document.getElementById('status').textContent = '分析成功';
|
||||
}
|
||||
renderTokenReport(data);
|
||||
render(data);
|
||||
} catch (err) {
|
||||
document.getElementById('status').classList.add('warn');
|
||||
@@ -484,6 +1068,9 @@ def private_message_page():
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
initPresetSelector();
|
||||
renderUsers([]);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -522,6 +1109,16 @@ async def api_private_message_query(payload: dict):
|
||||
return {
|
||||
"ok": True,
|
||||
"count": result.get("count"),
|
||||
"users": [
|
||||
{
|
||||
"nick": c.get("nick"),
|
||||
"userId": c.get("userId") or c.get("userid"),
|
||||
"avatar": c.get("avatar") or c.get("headImg") or c.get("headimgurl") or c.get("headImgUrl"),
|
||||
"lastMsg": (c.get("lastMsg") or {}).get("content"),
|
||||
"lastActiveTime": c.get("lastActiveTime"),
|
||||
}
|
||||
for c in contacts
|
||||
],
|
||||
"contacts_preview": [
|
||||
{
|
||||
"nick": c.get("nick"),
|
||||
|
||||
Reference in New Issue
Block a user