;'s'
This commit is contained in:
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.
30
config.py
30
config.py
@@ -1,9 +1,31 @@
|
||||
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+端口
|
||||
|
||||
102
main.py
102
main.py
@@ -2,7 +2,6 @@ import json
|
||||
import logging
|
||||
import base64
|
||||
import time
|
||||
from html import escape
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
@@ -131,60 +130,30 @@ def _build_keyword_h5_reply(query: str, user_id: str) -> Optional[str]:
|
||||
return json.dumps(msg, ensure_ascii=False) if msg else None
|
||||
|
||||
|
||||
async def _send_kefu_msg_for_xml_callback(data: dict) -> None:
|
||||
def _build_xml_callback_reply(data: dict, answer_text: str) -> dict:
|
||||
"""
|
||||
XML 回调渠道下,主动调用 sendmsg 下发消息(回调响应体不会直接展示给用户)。
|
||||
XML 回调直接回包给平台,由平台转发给用户。
|
||||
返回结构按“userid/appid/content/channel/from”组织。
|
||||
"""
|
||||
query = str(data.get("Query", "")).strip()
|
||||
user_id = str(data.get("UserId", "")).strip()
|
||||
userid = str(data.get("UserId", "")).strip()
|
||||
appid = str(data.get("ChannelId", "") or data.get("appid", "")).strip()
|
||||
channel = int(str(data.get("channel", "0") or "0"))
|
||||
msg = _build_keyword_h5_obj(query, user_id)
|
||||
if not msg:
|
||||
return
|
||||
channel_raw = str(data.get("channel", "0") or "0")
|
||||
try:
|
||||
channel = int(channel_raw)
|
||||
except Exception:
|
||||
channel = 0
|
||||
|
||||
url = f"https://chatbot.weixin.qq.com/openapi/sendmsg/{TOKEN}"
|
||||
body = {
|
||||
# 关键词命中返回 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,
|
||||
"openid": user_id,
|
||||
"msg": msg,
|
||||
"content": content,
|
||||
"channel": channel,
|
||||
"from": 1,
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=10, verify=False) as client:
|
||||
# 1) 先尝试明文 JSON 发送(多数场景可直接工作)
|
||||
resp = await client.post(url, json=body, headers={"content-type": "application/json"})
|
||||
resp.raise_for_status()
|
||||
payload = resp.json() if resp.content else {}
|
||||
errcode = int(payload.get("errcode", -1)) if isinstance(payload, dict) else -1
|
||||
if errcode == 0:
|
||||
logger.info("关键词命中,sendmsg 明文发送成功")
|
||||
return
|
||||
|
||||
logger.warning("sendmsg 明文返回非成功,准备加密重试:%s", payload)
|
||||
|
||||
# 2) 按文档加密格式重试:body = {"encrypt": "..."}
|
||||
msg_text = json.dumps(msg, ensure_ascii=False)
|
||||
xml_data = (
|
||||
"<xml>"
|
||||
f"<appid><![CDATA[{escape(appid)}]]></appid>"
|
||||
f"<openid><![CDATA[{escape(user_id)}]]></openid>"
|
||||
f"<msg><![CDATA[{msg_text}]]></msg>"
|
||||
f"<channel>{channel}</channel>"
|
||||
"</xml>"
|
||||
)
|
||||
encrypted = aes_encrypt_base64(xml_data, ENCODING_AES_KEY, APP_ID)
|
||||
enc_resp = await client.post(
|
||||
url,
|
||||
json={"encrypt": encrypted},
|
||||
headers={"content-type": "application/json"},
|
||||
)
|
||||
enc_resp.raise_for_status()
|
||||
enc_payload = enc_resp.json() if enc_resp.content else {}
|
||||
enc_errcode = int(enc_payload.get("errcode", -1)) if isinstance(enc_payload, dict) else -1
|
||||
if enc_errcode == 0:
|
||||
logger.info("关键词命中,sendmsg 加密发送成功")
|
||||
return
|
||||
logger.error("sendmsg 加密发送失败:%s", enc_payload)
|
||||
|
||||
|
||||
def _safe_filter_value(value: str) -> str:
|
||||
@@ -471,7 +440,7 @@ async def handle_business(data: dict) -> str:
|
||||
keyword_reply = _build_keyword_h5_reply(query, user_id)
|
||||
if keyword_reply:
|
||||
return keyword_reply
|
||||
return "已收到你的消息,输入“电子书”或“群”可获取对应卡片。"
|
||||
return "1111111"
|
||||
|
||||
|
||||
def _decode_jwt_payload_without_verify(token: str) -> dict:
|
||||
@@ -610,29 +579,30 @@ async def _handle_wechat_request(request: Request, app_id: Optional[str], backgr
|
||||
logger.exception("业务处理异常,将返回兜底文案")
|
||||
answer_text = "系统繁忙,请稍后再试。"
|
||||
|
||||
# XML 回调场景需要主动 sendmsg 才能给用户展示消息
|
||||
if str(data.get("_payload_format", "")) == "xml":
|
||||
try:
|
||||
await _send_kefu_msg_for_xml_callback(data)
|
||||
except Exception:
|
||||
logger.error("sendmsg 下发失败(不影响回调200)")
|
||||
|
||||
# 7.1 主回复确定后再后台触发 B 同步,避免影响回复链路耗时
|
||||
background_tasks.add_task(_safe_sync_user_profile_from_b, data)
|
||||
|
||||
resp_obj = {
|
||||
# 文本类型,内容为可被 JSON.parse 的 H5 结构字符串
|
||||
"answer_type": "text",
|
||||
"text_info": {
|
||||
"short_answer": answer_text
|
||||
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",
|
||||
"text_info": {
|
||||
"short_answer": answer_text
|
||||
}
|
||||
}
|
||||
}
|
||||
resp_json_str = json.dumps(resp_obj, ensure_ascii=False)
|
||||
|
||||
resp_json_str = json.dumps(resp_obj, ensure_ascii=False)
|
||||
logger.info("回包明文(加密前): %s", resp_json_str)
|
||||
|
||||
# 8. 加密响应 JSON
|
||||
# 8. 加密响应
|
||||
# XML 回调场景使用当前会话 appid(公众号 appid)加密,避免与开放 API appid 不一致导致平台解密失败。
|
||||
response_app_id = APP_ID
|
||||
if str(data.get("_payload_format", "")) == "xml":
|
||||
response_app_id = str(data.get("ChannelId", "") or data.get("appid", "")).strip() or APP_ID
|
||||
try:
|
||||
encrypted_resp = aes_encrypt_base64(resp_json_str, ENCODING_AES_KEY, APP_ID)
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user