QQPyBot 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
qqpybot-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: QQPyBot
3
+ Version: 0.1.0
4
+ Summary: FastAPI Webhook SDK for the QQ Bot Open Platform
5
+ Project-URL: Repository, https://github.com/Murphy08/QQPyBot
6
+ Project-URL: Issues, https://github.com/Murphy08/QQPyBot/issues
7
+ Keywords: qqbot,qq,webhook,fastapi
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Framework :: FastAPI
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.11
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: fastapi<1,>=0.115
14
+
15
+ # QQPyBot
16
+
17
+ [![CI](https://github.com/Murphy08/QQPyBot/actions/workflows/ci.yml/badge.svg)](https://github.com/Murphy08/QQPyBot/actions/workflows/ci.yml)
18
+ [![PyPI](https://img.shields.io/pypi/v/QQPyBot)](https://pypi.org/project/QQPyBot/)
19
+ [![Python](https://img.shields.io/badge/Python-3.11%2B-blue)](https://www.python.org/)
20
+ [![GitHub Stars](https://img.shields.io/github/stars/Murphy08/QQPyBot?style=social)](https://github.com/Murphy08/QQPyBot/stargazers)
21
+
22
+ QQ 开放平台的 Python **Webhook SDK**。用 FastAPI 接收 QQ 事件,使用装饰器注册命令,并通过异步客户端调用 QQ REST API。
23
+
24
+ ## 快速开始
25
+
26
+ PyPI 首发完成后,使用 `pip install QQPyBot uvicorn`。也可以克隆本仓库后运行 `python -m pip install -e . uvicorn`。运行环境需要 Python 3.11 以上及提供 Ed25519 的 OpenSSL。Windows 版 CPython 可使用自带的 OpenSSL。
27
+
28
+ 把下面的示例保存为 `main.py`。
29
+
30
+ ```python
31
+ import os
32
+
33
+ from qqpybot import Bot, Context
34
+
35
+ bot = Bot(os.environ["QQBOT_APP_ID"], os.environ["QQBOT_APP_SECRET"])
36
+
37
+ @bot.command("你好", aliases=("hi",), events={"GROUP_MESSAGE_CREATE", "GROUP_AT_MESSAGE_CREATE"})
38
+ async def hello(ctx: Context):
39
+ await ctx.reply(f"你好,{ctx.args or '朋友'}!")
40
+
41
+ app = bot.create_app()
42
+ ```
43
+
44
+ 执行 `python -m uvicorn main:app --host 0.0.0.0 --port 8080`。在 QQ 开放平台填写对外的 HTTPS 回调地址 `https://你的域名/qq/callback`。可在已有 FastAPI 中使用 `app.include_router(bot.router)`。
45
+
46
+ 勾选 `GROUP_MESSAGE_CREATE` 并为机器人启用接收所有消息。群里直接发送 `你好 小明` 或 `/hi 小明`。只订阅 AT 事件的群,用 `@机器人 你好 小明`。QQ 平台管理的账号注册、事件订阅、权限和回调地址配置请参阅[官方接入指南](https://bot.q.qq.com/wiki/develop/api-v2/dev-prepare/getting-started.html)。
47
+
48
+ ## 事件与 REST
49
+
50
+ ```python
51
+ @bot.on_event("GROUP_ADD_ROBOT")
52
+ async def joined(ctx: Context):
53
+ print("已加入群聊", ctx.event.group_openid)
54
+
55
+ @bot.on_event("*")
56
+ async def delivered(ctx: Context):
57
+ print(ctx.event.type, ctx.event.event_id)
58
+ ```
59
+
60
+ [全事件示例](docs/events.md)包含逐项订阅的调用方式。也可运行 `uvicorn examples.all_events:app` 观察官方回调。事件数据通过 `ctx.event.data` 取得。
61
+
62
+ ```python
63
+ await bot.api.send_group_message("群 OpenID", msg_type=0, content="晚上好")
64
+ await bot.api.call("v2_groups_group_openid_info_get", group_openid="群 OpenID")
65
+ await bot.api.request("GET", "/users/@me")
66
+ ```
67
+
68
+ [REST 目录](docs/api.md)列出官网自动生成的接口及参数示例。登录凭证由 SDK 缓存,API 失败时可从 `QQAPIError` 读取 HTTP 状态、业务码和 Trace ID。管理、主动消息及其他受限接口取决于应用权限。
69
+
70
+ 回调会先验签、应答 QQ,随后在当前进程执行已注册的处理器。同一进程内会过滤近期重复事件。需要跨进程去重或可靠重放的业务,应在业务层持久化事件 ID。
71
+
72
+ ## 开发与发布
73
+
74
+ 在项目的虚拟环境运行 `python -m pip install -e .`,然后执行 `python -m unittest discover -s tests -v`。执行 `python scripts/sync_catalog.py` 可将官方接口目录同步到包内。
75
+
76
+ 发布前在 PyPI 建立 Trusted Publisher,项目名填 `QQPyBot`,GitHub Owner 填 `Murphy08`,仓库填 `QQPyBot`,工作流填 `publish.yml`,环境填 `pypi`。更新 `pyproject.toml` 中的版本,推送对应 `vX.Y.Z` 标签即可构建并发布。
@@ -0,0 +1,62 @@
1
+ # QQPyBot
2
+
3
+ [![CI](https://github.com/Murphy08/QQPyBot/actions/workflows/ci.yml/badge.svg)](https://github.com/Murphy08/QQPyBot/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/QQPyBot)](https://pypi.org/project/QQPyBot/)
5
+ [![Python](https://img.shields.io/badge/Python-3.11%2B-blue)](https://www.python.org/)
6
+ [![GitHub Stars](https://img.shields.io/github/stars/Murphy08/QQPyBot?style=social)](https://github.com/Murphy08/QQPyBot/stargazers)
7
+
8
+ QQ 开放平台的 Python **Webhook SDK**。用 FastAPI 接收 QQ 事件,使用装饰器注册命令,并通过异步客户端调用 QQ REST API。
9
+
10
+ ## 快速开始
11
+
12
+ PyPI 首发完成后,使用 `pip install QQPyBot uvicorn`。也可以克隆本仓库后运行 `python -m pip install -e . uvicorn`。运行环境需要 Python 3.11 以上及提供 Ed25519 的 OpenSSL。Windows 版 CPython 可使用自带的 OpenSSL。
13
+
14
+ 把下面的示例保存为 `main.py`。
15
+
16
+ ```python
17
+ import os
18
+
19
+ from qqpybot import Bot, Context
20
+
21
+ bot = Bot(os.environ["QQBOT_APP_ID"], os.environ["QQBOT_APP_SECRET"])
22
+
23
+ @bot.command("你好", aliases=("hi",), events={"GROUP_MESSAGE_CREATE", "GROUP_AT_MESSAGE_CREATE"})
24
+ async def hello(ctx: Context):
25
+ await ctx.reply(f"你好,{ctx.args or '朋友'}!")
26
+
27
+ app = bot.create_app()
28
+ ```
29
+
30
+ 执行 `python -m uvicorn main:app --host 0.0.0.0 --port 8080`。在 QQ 开放平台填写对外的 HTTPS 回调地址 `https://你的域名/qq/callback`。可在已有 FastAPI 中使用 `app.include_router(bot.router)`。
31
+
32
+ 勾选 `GROUP_MESSAGE_CREATE` 并为机器人启用接收所有消息。群里直接发送 `你好 小明` 或 `/hi 小明`。只订阅 AT 事件的群,用 `@机器人 你好 小明`。QQ 平台管理的账号注册、事件订阅、权限和回调地址配置请参阅[官方接入指南](https://bot.q.qq.com/wiki/develop/api-v2/dev-prepare/getting-started.html)。
33
+
34
+ ## 事件与 REST
35
+
36
+ ```python
37
+ @bot.on_event("GROUP_ADD_ROBOT")
38
+ async def joined(ctx: Context):
39
+ print("已加入群聊", ctx.event.group_openid)
40
+
41
+ @bot.on_event("*")
42
+ async def delivered(ctx: Context):
43
+ print(ctx.event.type, ctx.event.event_id)
44
+ ```
45
+
46
+ [全事件示例](docs/events.md)包含逐项订阅的调用方式。也可运行 `uvicorn examples.all_events:app` 观察官方回调。事件数据通过 `ctx.event.data` 取得。
47
+
48
+ ```python
49
+ await bot.api.send_group_message("群 OpenID", msg_type=0, content="晚上好")
50
+ await bot.api.call("v2_groups_group_openid_info_get", group_openid="群 OpenID")
51
+ await bot.api.request("GET", "/users/@me")
52
+ ```
53
+
54
+ [REST 目录](docs/api.md)列出官网自动生成的接口及参数示例。登录凭证由 SDK 缓存,API 失败时可从 `QQAPIError` 读取 HTTP 状态、业务码和 Trace ID。管理、主动消息及其他受限接口取决于应用权限。
55
+
56
+ 回调会先验签、应答 QQ,随后在当前进程执行已注册的处理器。同一进程内会过滤近期重复事件。需要跨进程去重或可靠重放的业务,应在业务层持久化事件 ID。
57
+
58
+ ## 开发与发布
59
+
60
+ 在项目的虚拟环境运行 `python -m pip install -e .`,然后执行 `python -m unittest discover -s tests -v`。执行 `python scripts/sync_catalog.py` 可将官方接口目录同步到包内。
61
+
62
+ 发布前在 PyPI 建立 Trusted Publisher,项目名填 `QQPyBot`,GitHub Owner 填 `Murphy08`,仓库填 `QQPyBot`,工作流填 `publish.yml`,环境填 `pypi`。更新 `pyproject.toml` 中的版本,推送对应 `vX.Y.Z` 标签即可构建并发布。
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "QQPyBot"
7
+ version = "0.1.0"
8
+ description = "FastAPI Webhook SDK for the QQ Bot Open Platform"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = ["fastapi>=0.115,<1"]
12
+ keywords = ["qqbot", "qq", "webhook", "fastapi"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Framework :: FastAPI",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+
19
+ [project.urls]
20
+ Repository = "https://github.com/Murphy08/QQPyBot"
21
+ Issues = "https://github.com/Murphy08/QQPyBot/issues"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.setuptools.package-data]
27
+ qqpybot = ["catalog.json", "py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: QQPyBot
3
+ Version: 0.1.0
4
+ Summary: FastAPI Webhook SDK for the QQ Bot Open Platform
5
+ Project-URL: Repository, https://github.com/Murphy08/QQPyBot
6
+ Project-URL: Issues, https://github.com/Murphy08/QQPyBot/issues
7
+ Keywords: qqbot,qq,webhook,fastapi
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Framework :: FastAPI
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.11
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: fastapi<1,>=0.115
14
+
15
+ # QQPyBot
16
+
17
+ [![CI](https://github.com/Murphy08/QQPyBot/actions/workflows/ci.yml/badge.svg)](https://github.com/Murphy08/QQPyBot/actions/workflows/ci.yml)
18
+ [![PyPI](https://img.shields.io/pypi/v/QQPyBot)](https://pypi.org/project/QQPyBot/)
19
+ [![Python](https://img.shields.io/badge/Python-3.11%2B-blue)](https://www.python.org/)
20
+ [![GitHub Stars](https://img.shields.io/github/stars/Murphy08/QQPyBot?style=social)](https://github.com/Murphy08/QQPyBot/stargazers)
21
+
22
+ QQ 开放平台的 Python **Webhook SDK**。用 FastAPI 接收 QQ 事件,使用装饰器注册命令,并通过异步客户端调用 QQ REST API。
23
+
24
+ ## 快速开始
25
+
26
+ PyPI 首发完成后,使用 `pip install QQPyBot uvicorn`。也可以克隆本仓库后运行 `python -m pip install -e . uvicorn`。运行环境需要 Python 3.11 以上及提供 Ed25519 的 OpenSSL。Windows 版 CPython 可使用自带的 OpenSSL。
27
+
28
+ 把下面的示例保存为 `main.py`。
29
+
30
+ ```python
31
+ import os
32
+
33
+ from qqpybot import Bot, Context
34
+
35
+ bot = Bot(os.environ["QQBOT_APP_ID"], os.environ["QQBOT_APP_SECRET"])
36
+
37
+ @bot.command("你好", aliases=("hi",), events={"GROUP_MESSAGE_CREATE", "GROUP_AT_MESSAGE_CREATE"})
38
+ async def hello(ctx: Context):
39
+ await ctx.reply(f"你好,{ctx.args or '朋友'}!")
40
+
41
+ app = bot.create_app()
42
+ ```
43
+
44
+ 执行 `python -m uvicorn main:app --host 0.0.0.0 --port 8080`。在 QQ 开放平台填写对外的 HTTPS 回调地址 `https://你的域名/qq/callback`。可在已有 FastAPI 中使用 `app.include_router(bot.router)`。
45
+
46
+ 勾选 `GROUP_MESSAGE_CREATE` 并为机器人启用接收所有消息。群里直接发送 `你好 小明` 或 `/hi 小明`。只订阅 AT 事件的群,用 `@机器人 你好 小明`。QQ 平台管理的账号注册、事件订阅、权限和回调地址配置请参阅[官方接入指南](https://bot.q.qq.com/wiki/develop/api-v2/dev-prepare/getting-started.html)。
47
+
48
+ ## 事件与 REST
49
+
50
+ ```python
51
+ @bot.on_event("GROUP_ADD_ROBOT")
52
+ async def joined(ctx: Context):
53
+ print("已加入群聊", ctx.event.group_openid)
54
+
55
+ @bot.on_event("*")
56
+ async def delivered(ctx: Context):
57
+ print(ctx.event.type, ctx.event.event_id)
58
+ ```
59
+
60
+ [全事件示例](docs/events.md)包含逐项订阅的调用方式。也可运行 `uvicorn examples.all_events:app` 观察官方回调。事件数据通过 `ctx.event.data` 取得。
61
+
62
+ ```python
63
+ await bot.api.send_group_message("群 OpenID", msg_type=0, content="晚上好")
64
+ await bot.api.call("v2_groups_group_openid_info_get", group_openid="群 OpenID")
65
+ await bot.api.request("GET", "/users/@me")
66
+ ```
67
+
68
+ [REST 目录](docs/api.md)列出官网自动生成的接口及参数示例。登录凭证由 SDK 缓存,API 失败时可从 `QQAPIError` 读取 HTTP 状态、业务码和 Trace ID。管理、主动消息及其他受限接口取决于应用权限。
69
+
70
+ 回调会先验签、应答 QQ,随后在当前进程执行已注册的处理器。同一进程内会过滤近期重复事件。需要跨进程去重或可靠重放的业务,应在业务层持久化事件 ID。
71
+
72
+ ## 开发与发布
73
+
74
+ 在项目的虚拟环境运行 `python -m pip install -e .`,然后执行 `python -m unittest discover -s tests -v`。执行 `python scripts/sync_catalog.py` 可将官方接口目录同步到包内。
75
+
76
+ 发布前在 PyPI 建立 Trusted Publisher,项目名填 `QQPyBot`,GitHub Owner 填 `Murphy08`,仓库填 `QQPyBot`,工作流填 `publish.yml`,环境填 `pypi`。更新 `pyproject.toml` 中的版本,推送对应 `vX.Y.Z` 标签即可构建并发布。
@@ -0,0 +1,14 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/QQPyBot.egg-info/PKG-INFO
4
+ src/QQPyBot.egg-info/SOURCES.txt
5
+ src/QQPyBot.egg-info/dependency_links.txt
6
+ src/QQPyBot.egg-info/requires.txt
7
+ src/QQPyBot.egg-info/top_level.txt
8
+ src/qqpybot/__init__.py
9
+ src/qqpybot/bot.py
10
+ src/qqpybot/catalog.json
11
+ src/qqpybot/client.py
12
+ src/qqpybot/py.typed
13
+ src/qqpybot/signing.py
14
+ tests/test_webhook.py
@@ -0,0 +1 @@
1
+ fastapi<1,>=0.115
@@ -0,0 +1 @@
1
+ qqpybot
@@ -0,0 +1,6 @@
1
+ """公开 QQPyBot Webhook 和 REST SDK。"""
2
+
3
+ from .bot import Bot, Context, Event
4
+ from .client import CATALOG, QQAPIError, QQClient
5
+
6
+ __all__ = ["Bot", "Context", "Event", "CATALOG", "QQAPIError", "QQClient"]
@@ -0,0 +1,209 @@
1
+ """FastAPI 回调、事件分发和命令装饰器。"""
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ import re
7
+ import time
8
+ from collections import OrderedDict
9
+ from dataclasses import dataclass
10
+
11
+ from fastapi import APIRouter, BackgroundTasks, FastAPI, HTTPException, Request
12
+ from starlette.requests import ClientDisconnect
13
+
14
+ from .client import QQClient
15
+ from .signing import WebhookSigner
16
+
17
+ LOGGER = logging.getLogger("qqpybot")
18
+ MESSAGE_EVENTS = {
19
+ "GROUP_MESSAGE_CREATE", "GROUP_AT_MESSAGE_CREATE", "C2C_MESSAGE_CREATE",
20
+ "AT_MESSAGE_CREATE", "MESSAGE_CREATE", "DIRECT_MESSAGE_CREATE",
21
+ }
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Event:
26
+ """保留官方事件名、事件 ID 和完整业务载荷。"""
27
+
28
+ type: str
29
+ data: dict
30
+ event_id: str | None = None
31
+
32
+ @property
33
+ def message_id(self) -> str | None:
34
+ return self.data.get("id")
35
+
36
+ @property
37
+ def group_openid(self) -> str | None:
38
+ return self.data.get("group_openid")
39
+
40
+ @property
41
+ def content(self) -> str:
42
+ content = self.data.get("content")
43
+ return content if isinstance(content, str) else ""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Context:
48
+ """事件处理上下文和被动回复助手。"""
49
+
50
+ event: Event
51
+ api: QQClient
52
+ args: str = ""
53
+
54
+ async def reply(self, content: str):
55
+ """回复群聊、单聊、频道或频道私信。"""
56
+ event = self.event
57
+ data = event.data
58
+ if not event.message_id:
59
+ raise ValueError("Event has no message ID")
60
+ if event.group_openid:
61
+ return await self.api.send_group_message(
62
+ event.group_openid, content=content, msg_id=event.message_id, msg_type=0,
63
+ )
64
+ if event.type == "C2C_MESSAGE_CREATE":
65
+ from urllib.parse import quote
66
+ user = data["author"]["user_openid"]
67
+ return await self.api.request(
68
+ "POST", f"/v2/users/{quote(user, safe='')}/messages",
69
+ json_body={"content": content, "msg_id": event.message_id, "msg_type": 0},
70
+ )
71
+ from urllib.parse import quote
72
+ if event.type == "DIRECT_MESSAGE_CREATE":
73
+ path = f"/dms/{quote(data['guild_id'], safe='')}/messages"
74
+ elif event.type in {"AT_MESSAGE_CREATE", "MESSAGE_CREATE"}:
75
+ path = f"/channels/{quote(data['channel_id'], safe='')}/messages"
76
+ else:
77
+ raise ValueError("Event does not support a text reply")
78
+ return await self.api.request("POST", path, json_body={"content": content, "msg_id": event.message_id})
79
+
80
+
81
+ class Bot:
82
+ """在 FastAPI 中接收 QQ 官方回调并注册异步事件和命令。"""
83
+
84
+ def __init__(
85
+ self, app_id: str, app_secret: str, *, path: str = "/qq/callback",
86
+ sandbox=False, max_body_bytes=1024 * 1024, max_clock_skew=300,
87
+ ):
88
+ self.api = QQClient(app_id, app_secret, sandbox=sandbox)
89
+ self.signer = WebhookSigner(app_secret)
90
+ self.router = APIRouter()
91
+ self.router.add_api_route(path, self._receive, methods=["POST"], include_in_schema=False)
92
+ self._app_id = app_id
93
+ self._max_body_bytes = max_body_bytes
94
+ self._max_clock_skew = max_clock_skew
95
+ self._handlers = {}
96
+ self._commands = {}
97
+ self._seen = OrderedDict()
98
+ self._slots = asyncio.Semaphore(16)
99
+
100
+ def create_app(self, **kwargs) -> FastAPI:
101
+ """构建独立应用,或用 router 挂载到已有 FastAPI 服务。"""
102
+ app = FastAPI(**kwargs)
103
+ app.include_router(self.router)
104
+ return app
105
+
106
+ def on_event(self, name: str = "*"):
107
+ """注册任意官方事件,使用 * 监听全部已订阅事件。"""
108
+ def register(handler):
109
+ self._handlers.setdefault(name.upper(), []).append(handler)
110
+ return handler
111
+ return register
112
+
113
+ def command(self, name: str, *, aliases=(), events=None):
114
+ """注册命令及别名,支持可选斜杠前缀和原始参数文本。"""
115
+ event_types = MESSAGE_EVENTS if events is None else frozenset(events)
116
+ def register(handler):
117
+ names = (name, *aliases)
118
+ if any(not value or value.startswith("/") or any(c.isspace() for c in value) for value in names):
119
+ raise ValueError("Command names must be nonempty words")
120
+ if any(value in self._commands for value in names):
121
+ raise ValueError("Command name or alias is already registered")
122
+ for value in names:
123
+ self._commands[value] = (event_types, handler)
124
+ return handler
125
+ return register
126
+
127
+ async def dispatch(self, event: Event):
128
+ """分发已验证的事件,并对命令执行去重。"""
129
+ async with self._slots:
130
+ context = Context(event, self.api)
131
+ for handler in (*self._handlers.get("*", ()), *self._handlers.get(event.type, ())):
132
+ await self._invoke(handler, context)
133
+ content = event.content.strip()
134
+ if event.type in {"GROUP_AT_MESSAGE_CREATE", "AT_MESSAGE_CREATE"}:
135
+ content = re.sub(r"^<@!?[A-Za-z0-9_-]+>\s*", "", content)
136
+ parts = content.removeprefix("/").split(maxsplit=1)
137
+ if event.type not in MESSAGE_EVENTS or not parts or parts[0] not in self._commands:
138
+ return
139
+ events, handler = self._commands[parts[0]]
140
+ if event.type not in events or self._duplicate(("command", event.group_openid, event.message_id)):
141
+ return
142
+ await self._invoke(handler, Context(event, self.api, parts[1] if len(parts) == 2 else ""))
143
+
144
+ async def _invoke(self, handler, context):
145
+ """记录处理错误,同时保持同一事件的其他处理器可继续运行。"""
146
+ try:
147
+ await handler(context)
148
+ except Exception as error:
149
+ LOGGER.error(
150
+ "QQ event handler failed event=%s handler=%s error=%s",
151
+ context.event.type, getattr(handler, "__name__", type(handler).__name__), type(error).__name__,
152
+ )
153
+
154
+ def _duplicate(self, key):
155
+ """用有限容量和生存期拦截同一进程内重复投递。"""
156
+ if not key[-1]:
157
+ return False
158
+ now = time.monotonic()
159
+ while self._seen and next(iter(self._seen.values())) < now - 600:
160
+ self._seen.popitem(last=False)
161
+ if key in self._seen:
162
+ return True
163
+ self._seen[key] = now
164
+ if len(self._seen) > 4096:
165
+ self._seen.popitem(last=False)
166
+ return False
167
+
168
+ async def _receive(self, request: Request, background: BackgroundTasks):
169
+ """验证 QQ 请求,快速应答,并在应答后分发业务事件。"""
170
+ if request.headers.get("X-Bot-Appid") != self._app_id:
171
+ raise HTTPException(401, "Invalid bot App ID")
172
+ body = bytearray()
173
+ try:
174
+ async for chunk in request.stream():
175
+ if len(body) + len(chunk) > self._max_body_bytes:
176
+ raise HTTPException(413, "QQ callback is too large")
177
+ body.extend(chunk)
178
+ except ClientDisconnect as error:
179
+ raise HTTPException(400, "QQ callback disconnected") from error
180
+ try:
181
+ payload = json.loads(body)
182
+ except (ValueError, RecursionError) as error:
183
+ raise HTTPException(400, "Invalid QQ callback JSON") from error
184
+ if not isinstance(payload, dict) or not isinstance(payload.get("d"), dict):
185
+ raise HTTPException(400, "Invalid QQ callback payload")
186
+ data = payload["d"]
187
+ if payload.get("op") == 13:
188
+ timestamp, token = data.get("event_ts"), data.get("plain_token")
189
+ if not isinstance(timestamp, str) or not re.fullmatch(r"[0-9]{1,16}", timestamp):
190
+ raise HTTPException(400, "Invalid challenge timestamp")
191
+ if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,256}", token):
192
+ raise HTTPException(400, "Invalid challenge token")
193
+ return {"plain_token": token, "signature": self.signer.sign((timestamp + token).encode())}
194
+
195
+ timestamp = request.headers.get("X-Signature-Timestamp", "")
196
+ signature = request.headers.get("X-Signature-Ed25519", "")
197
+ if not re.fullmatch(r"[0-9]{1,12}", timestamp) or abs(time.time() - int(timestamp)) > self._max_clock_skew:
198
+ raise HTTPException(401, "Invalid QQ signature timestamp")
199
+ if not self.signer.verify(timestamp.encode() + body, signature):
200
+ raise HTTPException(401, "Invalid QQ signature")
201
+ name = payload.get("t")
202
+ if payload.get("op") != 0 or not isinstance(name, str) or not re.fullmatch(r"[A-Z][A-Z0-9_]{1,128}", name):
203
+ raise HTTPException(400, "Invalid QQ event")
204
+ event_id = payload.get("id")
205
+ if not isinstance(event_id, str):
206
+ event_id = None
207
+ if not self._duplicate(("delivery", name, event_id)):
208
+ background.add_task(self.dispatch, Event(name, data, event_id))
209
+ return {"op": 12}
@@ -0,0 +1,382 @@
1
+ {
2
+ "apis": {
3
+ "channels_channel_id_delete": {
4
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/channels_channel_id.delete.html",
5
+ "method": "DELETE",
6
+ "path": "/channels/{channel_id}",
7
+ "title": "删除子频道"
8
+ },
9
+ "channels_channel_id_get": {
10
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/channels_channel_id.get.html",
11
+ "method": "GET",
12
+ "path": "/channels/{channel_id}",
13
+ "title": "获取子频道详情"
14
+ },
15
+ "channels_channel_id_patch": {
16
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/channels_channel_id.patch.html",
17
+ "method": "PATCH",
18
+ "path": "/channels/{channel_id}",
19
+ "title": "修改子频道"
20
+ },
21
+ "gateway_get": {
22
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/gateway.get.html",
23
+ "method": "GET",
24
+ "path": "/gateway",
25
+ "title": "获取通用 WSS 接入点"
26
+ },
27
+ "guilds_guild_id_channels_get": {
28
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/guilds_guild_id_channels.get.html",
29
+ "method": "GET",
30
+ "path": "/guilds/{guild_id}/channels",
31
+ "title": "获取子频道列表"
32
+ },
33
+ "guilds_guild_id_channels_post": {
34
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/guilds_guild_id_channels.post.html",
35
+ "method": "POST",
36
+ "path": "/guilds/{guild_id}/channels",
37
+ "title": "创建子频道"
38
+ },
39
+ "guilds_guild_id_get": {
40
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/guilds_guild_id.get.html",
41
+ "method": "GET",
42
+ "path": "/guilds/{guild_id}",
43
+ "title": "获取频道详情"
44
+ },
45
+ "interactions_interaction_id_put": {
46
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/interactions_interaction_id.put.html",
47
+ "method": "PUT",
48
+ "path": "/interactions/{interaction_id}",
49
+ "title": "互动事件响应"
50
+ },
51
+ "users_me_get": {
52
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/users_me.get.html",
53
+ "method": "GET",
54
+ "path": "/users/@me",
55
+ "title": "获取机器人详情"
56
+ },
57
+ "users_me_guilds_get": {
58
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/users_me_guilds.get.html",
59
+ "method": "GET",
60
+ "path": "/users/@me/guilds",
61
+ "title": "获取机器人频道列表"
62
+ },
63
+ "v2_generate_url_link_post": {
64
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_generate_url_link.post.html",
65
+ "method": "POST",
66
+ "path": "/v2/generate_url_link",
67
+ "title": "生成分享链接"
68
+ },
69
+ "v2_groups_group_id_upload_part_finish_post": {
70
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_id_upload_part_finish.post.html",
71
+ "method": "POST",
72
+ "path": "/v2/groups/{group_id}/upload_part_finish",
73
+ "title": "群聊分片上传完成"
74
+ },
75
+ "v2_groups_group_id_upload_prepare_post": {
76
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_id_upload_prepare.post.html",
77
+ "method": "POST",
78
+ "path": "/v2/groups/{group_id}/upload_prepare",
79
+ "title": "群聊富媒体预上传"
80
+ },
81
+ "v2_groups_group_openid_approval_join_request_member_openid_post": {
82
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_approval_join_request_member_openid.post.html",
83
+ "method": "POST",
84
+ "path": "/v2/groups/{group_openid}/approval_join_request/{member_openid}",
85
+ "title": "入群申请审批"
86
+ },
87
+ "v2_groups_group_openid_batch_remove_members_post": {
88
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_batch_remove_members.post.html",
89
+ "method": "POST",
90
+ "path": "/v2/groups/{group_openid}/batch_remove_members",
91
+ "title": "群成员批量移除"
92
+ },
93
+ "v2_groups_group_openid_bot_state_get": {
94
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_bot_state.get.html",
95
+ "method": "GET",
96
+ "path": "/v2/groups/{group_openid}/bot_state",
97
+ "title": "获取机器人群内状态"
98
+ },
99
+ "v2_groups_group_openid_files_post": {
100
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_files.post.html",
101
+ "method": "POST",
102
+ "path": "/v2/groups/{group_openid}/files",
103
+ "title": "群聊富媒体上传"
104
+ },
105
+ "v2_groups_group_openid_info_get": {
106
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_info.get.html",
107
+ "method": "GET",
108
+ "path": "/v2/groups/{group_openid}/info",
109
+ "title": "获取群基本信息"
110
+ },
111
+ "v2_groups_group_openid_join_request_list_get": {
112
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_join_request_list.get.html",
113
+ "method": "GET",
114
+ "path": "/v2/groups/{group_openid}/join_request_list",
115
+ "title": "入群申请列表拉取"
116
+ },
117
+ "v2_groups_group_openid_member_blacklist_get": {
118
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_member_blacklist.get.html",
119
+ "method": "GET",
120
+ "path": "/v2/groups/{group_openid}/member_blacklist",
121
+ "title": "群黑名单查询"
122
+ },
123
+ "v2_groups_group_openid_member_blacklist_post": {
124
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_member_blacklist.post.html",
125
+ "method": "POST",
126
+ "path": "/v2/groups/{group_openid}/member_blacklist",
127
+ "title": "群黑名单操作"
128
+ },
129
+ "v2_groups_group_openid_members_get": {
130
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_members.get.html",
131
+ "method": "GET",
132
+ "path": "/v2/groups/{group_openid}/members",
133
+ "title": "获取群成员列表"
134
+ },
135
+ "v2_groups_group_openid_members_member_openid_get": {
136
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_members_member_openid.get.html",
137
+ "method": "GET",
138
+ "path": "/v2/groups/{group_openid}/members/{member_openid}",
139
+ "title": "获取群成员信息"
140
+ },
141
+ "v2_groups_group_openid_messages_message_id_delete": {
142
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_messages_message_id.delete.html",
143
+ "method": "DELETE",
144
+ "path": "/v2/groups/{group_openid}/messages/{message_id}",
145
+ "title": "撤回群聊消息"
146
+ },
147
+ "v2_groups_group_openid_messages_post": {
148
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_messages.post.html",
149
+ "method": "POST",
150
+ "path": "/v2/groups/{group_openid}/messages",
151
+ "title": "发送群聊消息"
152
+ },
153
+ "v2_groups_group_openid_restrict_chat_setting_get": {
154
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_restrict_chat_setting.get.html",
155
+ "method": "GET",
156
+ "path": "/v2/groups/{group_openid}/restrict_chat_setting",
157
+ "title": "查询群禁言状态"
158
+ },
159
+ "v2_groups_group_openid_restrict_chat_setting_post": {
160
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_restrict_chat_setting.post.html",
161
+ "method": "POST",
162
+ "path": "/v2/groups/{group_openid}/restrict_chat_setting",
163
+ "title": "设置群成员禁言"
164
+ },
165
+ "v2_groups_join_approval_strategy_get": {
166
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_join_approval_strategy.get.html",
167
+ "method": "GET",
168
+ "path": "/v2/groups/join_approval_strategy",
169
+ "title": "查询入群自动审批策略列表"
170
+ },
171
+ "v2_groups_join_approval_strategy_post": {
172
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_join_approval_strategy.post.html",
173
+ "method": "POST",
174
+ "path": "/v2/groups/join_approval_strategy",
175
+ "title": "创建入群自动审批策略"
176
+ },
177
+ "v2_groups_join_approval_strategy_strategy_id_delete": {
178
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_join_approval_strategy_strategy_id.delete.html",
179
+ "method": "DELETE",
180
+ "path": "/v2/groups/join_approval_strategy/{strategy_id}",
181
+ "title": "删除入群自动审批策略"
182
+ },
183
+ "v2_groups_join_approval_strategy_strategy_id_execute_post": {
184
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_join_approval_strategy_strategy_id_execute.post.html",
185
+ "method": "POST",
186
+ "path": "/v2/groups/join_approval_strategy/{strategy_id}/execute",
187
+ "title": "执行入群自动审批策略"
188
+ },
189
+ "v2_groups_join_approval_strategy_strategy_id_patch": {
190
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_join_approval_strategy_strategy_id.patch.html",
191
+ "method": "PATCH",
192
+ "path": "/v2/groups/join_approval_strategy/{strategy_id}",
193
+ "title": "修改入群自动审批策略"
194
+ },
195
+ "v2_groups_join_approval_strategy_strategy_id_whitelist_users_post": {
196
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_join_approval_strategy_strategy_id_whitelist_users.post.html",
197
+ "method": "POST",
198
+ "path": "/v2/groups/join_approval_strategy/{strategy_id}/whitelist_users",
199
+ "title": "修改入群自动审批策略的白名单号码"
200
+ },
201
+ "v2_menu_get": {
202
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_menu.get.html",
203
+ "method": "GET",
204
+ "path": "/v2/menu",
205
+ "title": "查询全局自定义菜单"
206
+ },
207
+ "v2_menu_put": {
208
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_menu.put.html",
209
+ "method": "PUT",
210
+ "path": "/v2/menu",
211
+ "title": "修改全局自定义菜单"
212
+ },
213
+ "v2_panels_get": {
214
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_panels.get.html",
215
+ "method": "GET",
216
+ "path": "/v2/panels",
217
+ "title": "查询指令面板列表"
218
+ },
219
+ "v2_panels_panel_id_delete": {
220
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_panels_panel_id.delete.html",
221
+ "method": "DELETE",
222
+ "path": "/v2/panels/{panel_id}",
223
+ "title": "删除指令面板"
224
+ },
225
+ "v2_panels_panel_id_get": {
226
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_panels_panel_id.get.html",
227
+ "method": "GET",
228
+ "path": "/v2/panels/{panel_id}",
229
+ "title": "查询指令面板详情"
230
+ },
231
+ "v2_panels_panel_id_put": {
232
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_panels_panel_id.put.html",
233
+ "method": "PUT",
234
+ "path": "/v2/panels/{panel_id}",
235
+ "title": "修改指令面板"
236
+ },
237
+ "v2_panels_panel_id_target_put": {
238
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_panels_panel_id_target.put.html",
239
+ "method": "PUT",
240
+ "path": "/v2/panels/{panel_id}/target",
241
+ "title": "修改指令面板关联对象"
242
+ },
243
+ "v2_panels_post": {
244
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_panels.post.html",
245
+ "method": "POST",
246
+ "path": "/v2/panels",
247
+ "title": "创建指令面板"
248
+ },
249
+ "v2_users_user_id_upload_part_finish_post": {
250
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_id_upload_part_finish.post.html",
251
+ "method": "POST",
252
+ "path": "/v2/users/{user_id}/upload_part_finish",
253
+ "title": "单聊分片上传完成"
254
+ },
255
+ "v2_users_user_id_upload_prepare_post": {
256
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_id_upload_prepare.post.html",
257
+ "method": "POST",
258
+ "path": "/v2/users/{user_id}/upload_prepare",
259
+ "title": "单聊富媒体预上传"
260
+ },
261
+ "v2_users_user_openid_files_post": {
262
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_openid_files.post.html",
263
+ "method": "POST",
264
+ "path": "/v2/users/{user_openid}/files",
265
+ "title": "单聊富媒体上传"
266
+ },
267
+ "v2_users_user_openid_info_get": {
268
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_openid_info.get.html",
269
+ "method": "GET",
270
+ "path": "/v2/users/{user_openid}/info",
271
+ "title": "获取用户基本信息"
272
+ },
273
+ "v2_users_user_openid_messages_message_id_delete": {
274
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_openid_messages_message_id.delete.html",
275
+ "method": "DELETE",
276
+ "path": "/v2/users/{user_openid}/messages/{message_id}",
277
+ "title": "撤回单聊消息"
278
+ },
279
+ "v2_users_user_openid_messages_post": {
280
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_openid_messages.post.html",
281
+ "method": "POST",
282
+ "path": "/v2/users/{user_openid}/messages",
283
+ "title": "发送单聊消息"
284
+ },
285
+ "v2_users_user_openid_stream_messages_post": {
286
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_openid_stream_messages.post.html",
287
+ "method": "POST",
288
+ "path": "/v2/users/{user_openid}/stream_messages",
289
+ "title": "流式发送单聊消息"
290
+ }
291
+ },
292
+ "events": {
293
+ "C2C_MESSAGE_CREATE": {
294
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/c2c_message_create.html",
295
+ "title": "单聊消息事件"
296
+ },
297
+ "C2C_MSG_RECEIVE": {
298
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/c2c_msg_receive.html",
299
+ "title": "单聊消息接收开启"
300
+ },
301
+ "C2C_MSG_REJECT": {
302
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/c2c_msg_reject.html",
303
+ "title": "单聊消息接收关闭"
304
+ },
305
+ "CHANNEL_CREATE": {
306
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/channel_create.html",
307
+ "title": "子频道创建"
308
+ },
309
+ "CHANNEL_DELETE": {
310
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/channel_delete.html",
311
+ "title": "子频道删除"
312
+ },
313
+ "CHANNEL_UPDATE": {
314
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/channel_update.html",
315
+ "title": "子频道更新"
316
+ },
317
+ "FRIEND_ADD": {
318
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/friend_add.html",
319
+ "title": "用户添加好友"
320
+ },
321
+ "FRIEND_DEL": {
322
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/friend_del.html",
323
+ "title": "用户删除好友"
324
+ },
325
+ "GROUP_ADD_ROBOT": {
326
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_add_robot.html",
327
+ "title": "机器人加入群聊"
328
+ },
329
+ "GROUP_AT_MESSAGE_CREATE": {
330
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_at_message_create.html",
331
+ "title": "群@机器人消息"
332
+ },
333
+ "GROUP_DEL_ROBOT": {
334
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_del_robot.html",
335
+ "title": "机器人退出群聊"
336
+ },
337
+ "GROUP_JOIN_REQUEST": {
338
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_join_request.html",
339
+ "title": "用户申请加群事件"
340
+ },
341
+ "GROUP_MEMBER_ADD": {
342
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_member_add.html",
343
+ "title": "群成员加入"
344
+ },
345
+ "GROUP_MEMBER_REMOVE": {
346
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_member_remove.html",
347
+ "title": "群成员退出"
348
+ },
349
+ "GROUP_MESSAGE_CREATE": {
350
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_message_create.html",
351
+ "title": "群消息(全量模式)"
352
+ },
353
+ "GROUP_MSG_RECEIVE": {
354
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_msg_receive.html",
355
+ "title": "群聊消息接收开启"
356
+ },
357
+ "GROUP_MSG_REJECT": {
358
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/group_msg_reject.html",
359
+ "title": "群聊消息接收关闭"
360
+ },
361
+ "GUILD_CREATE": {
362
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/guild_create.html",
363
+ "title": "频道创建"
364
+ },
365
+ "GUILD_DELETE": {
366
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/guild_delete.html",
367
+ "title": "频道解散"
368
+ },
369
+ "GUILD_UPDATE": {
370
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/guild_update.html",
371
+ "title": "频道更新"
372
+ },
373
+ "INTERACTION_CREATE": {
374
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/interaction_create.html",
375
+ "title": "互动事件"
376
+ },
377
+ "SUBSCRIBE_MESSAGE_STATUS": {
378
+ "doc": "https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/subscribe_message_status.html",
379
+ "title": "订阅消息授权状态变更"
380
+ }
381
+ }
382
+ }
@@ -0,0 +1,106 @@
1
+ """QQ REST API 客户端,缓存访问凭证,并对请求错误暴露业务码。"""
2
+
3
+ import asyncio
4
+ import json
5
+ import string
6
+ import time
7
+ from importlib.resources import files
8
+ from urllib.error import HTTPError
9
+ from urllib.parse import quote, urlencode, urlsplit
10
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
11
+
12
+ CATALOG = json.loads(files(__package__).joinpath("catalog.json").read_text(encoding="utf-8"))
13
+
14
+
15
+ class QQAPIError(RuntimeError):
16
+ """QQ REST 接口拒绝请求时返回的状态码、业务码与 Trace ID。"""
17
+
18
+ def __init__(self, status: int, code, trace_id: str | None):
19
+ self.status, self.code, self.trace_id = status, code, trace_id
20
+ super().__init__(f"QQ API returned HTTP {status}, code={code}, trace_id={trace_id}")
21
+
22
+
23
+ class _NoRedirect(HTTPRedirectHandler):
24
+ """避免将 QQ 鉴权头转发到重定向目标。"""
25
+
26
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
27
+ return None
28
+
29
+
30
+ class QQClient:
31
+ """使用 QQBot Access Token 调用官方群、私聊和频道接口。"""
32
+
33
+ def __init__(self, app_id: str, app_secret: str, *, sandbox=False, timeout=10):
34
+ if not app_id or not app_secret:
35
+ raise ValueError("QQ App ID and App Secret are required")
36
+ self.app_id = app_id
37
+ self._secret = app_secret
38
+ self._timeout = timeout
39
+ self._base = "https://sandbox.api.sgroup.qq.com" if sandbox else "https://api.sgroup.qq.com"
40
+ self._token = ""
41
+ self._expires = 0.0
42
+ self._token_lock = asyncio.Lock()
43
+ self._opener = build_opener(_NoRedirect())
44
+
45
+ def _send(self, target, method, body, headers):
46
+ """在线程中发送 HTTP 请求,并保留 QQ 错误的诊断元数据。"""
47
+ request = Request(target, data=body, headers=headers, method=method)
48
+ try:
49
+ with self._opener.open(request, timeout=self._timeout) as response:
50
+ data = response.read()
51
+ return json.loads(data) if data else None
52
+ except HTTPError as error:
53
+ with error:
54
+ try:
55
+ content = json.loads(error.read())
56
+ except (ValueError, UnicodeError):
57
+ content = {}
58
+ code = content.get("code") if isinstance(content, dict) else None
59
+ raise QQAPIError(error.code, code, error.headers.get("X-Tps-Trace-ID")) from None
60
+
61
+ async def access_token(self) -> str:
62
+ """获取或复用访问凭证,并在接近过期时自动刷新。"""
63
+ async with self._token_lock:
64
+ if time.monotonic() < self._expires:
65
+ return self._token
66
+ result = await asyncio.to_thread(
67
+ self._send, "https://bots.qq.com/app/getAppAccessToken", "POST",
68
+ json.dumps({"appId": self.app_id, "clientSecret": self._secret}).encode(),
69
+ {"Content-Type": "application/json"},
70
+ )
71
+ if not isinstance(result, dict) or not isinstance(result.get("access_token"), str):
72
+ raise QQAPIError(200, result.get("code") if isinstance(result, dict) else None, None)
73
+ self._token = result["access_token"]
74
+ self._expires = time.monotonic() + max(0, int(result["expires_in"]) - 30)
75
+ return self._token
76
+
77
+ async def request(self, method: str, path: str, *, query=None, json_body=None):
78
+ """调用相对路径的 QQ API,可用于上线后新增的接口。"""
79
+ parts = urlsplit(path)
80
+ if not path.startswith("/") or path.startswith("//") or parts.netloc or parts.fragment or parts.query:
81
+ raise ValueError("Expected an API path without origin, query or fragment")
82
+ token = await self.access_token()
83
+ headers = {"Authorization": f"QQBot {token}", "X-Union-Appid": self.app_id}
84
+ body = None
85
+ if json_body is not None:
86
+ headers["Content-Type"] = "application/json"
87
+ body = json.dumps(json_body, ensure_ascii=False).encode()
88
+ suffix = "?" + urlencode(query, doseq=True) if query else ""
89
+ return await asyncio.to_thread(self._send, self._base + path + suffix, method.upper(), body, headers)
90
+
91
+ async def call(self, name: str, *, query=None, json_body=None, **path_parameters):
92
+ """通过官方接口目录名称调用 REST API,并编码每个路径参数。"""
93
+ api = CATALOG["apis"][name]
94
+ expected = {field for _, field, _, _ in string.Formatter().parse(api["path"]) if field}
95
+ if expected != path_parameters.keys():
96
+ raise ValueError(f"{name} requires path parameters {', '.join(sorted(expected))}")
97
+ path = api["path"].format_map({key: quote(str(value), safe="") for key, value in path_parameters.items()})
98
+ return await self.request(api["method"], path, query=query, json_body=json_body)
99
+
100
+ async def send_group_message(self, group_openid: str, **payload):
101
+ """向 QQ 群主动发送或被动回复一条消息。"""
102
+ return await self.request("POST", f"/v2/groups/{quote(group_openid, safe='')}/messages", json_body=payload)
103
+
104
+ async def upload_group_file(self, group_openid: str, **payload):
105
+ """上传 QQ 群富媒体,返回供发送接口使用的 file_info。"""
106
+ return await self.request("POST", f"/v2/groups/{quote(group_openid, safe='')}/files", json_body=payload)
File without changes
@@ -0,0 +1,88 @@
1
+ """通过系统 OpenSSL EVP 接口完成 QQ Webhook 的 Ed25519 签名。"""
2
+
3
+ import ctypes as c
4
+ import ctypes.util
5
+ import re
6
+ import ssl
7
+ import sys
8
+ from pathlib import Path
9
+
10
+
11
+ def _load_crypto():
12
+ """在 Windows 上选择 Python 自带的 DLL,在其他平台上使用系统 libcrypto。"""
13
+ candidates = []
14
+ if sys.platform == "win32":
15
+ for root in (Path(sys.base_prefix), Path(sys.base_prefix) / "DLLs"):
16
+ candidates.extend(str(p) for p in sorted(root.glob("libcrypto-*.dll")))
17
+ name = ctypes.util.find_library("crypto")
18
+ if name:
19
+ candidates.append(name)
20
+ for candidate in candidates:
21
+ try:
22
+ lib = c.CDLL(candidate)
23
+ if hasattr(lib, "EVP_PKEY_new_raw_private_key"):
24
+ return lib
25
+ except OSError:
26
+ continue
27
+ raise RuntimeError(f"QQPyBot requires OpenSSL with Ed25519 (Python SSL: {ssl.OPENSSL_VERSION})")
28
+
29
+
30
+ class WebhookSigner:
31
+ """按 QQ 官方规则派生 Ed25519 密钥,验证请求及签署回调挑战。"""
32
+
33
+ def __init__(self, secret: str):
34
+ raw = secret.encode("utf-8")
35
+ if not raw:
36
+ raise ValueError("QQ App Secret is required")
37
+ self._seed = (raw * ((32 + len(raw) - 1) // len(raw)))[:32]
38
+ self._crypto = _load_crypto()
39
+ pointer, data, size = c.c_void_p, c.c_char_p, c.c_size_t
40
+ for name, result, args in (
41
+ ("OBJ_txt2nid", c.c_int, [data]),
42
+ ("EVP_PKEY_new_raw_private_key", pointer, [c.c_int, pointer, data, size]),
43
+ ("EVP_PKEY_free", None, [pointer]),
44
+ ("EVP_MD_CTX_new", pointer, []),
45
+ ("EVP_MD_CTX_free", None, [pointer]),
46
+ ("EVP_DigestSignInit", c.c_int, [pointer, pointer, pointer, pointer, pointer]),
47
+ ("EVP_DigestVerifyInit", c.c_int, [pointer, pointer, pointer, pointer, pointer]),
48
+ ("EVP_DigestSign", c.c_int, [pointer, pointer, c.POINTER(size), data, size]),
49
+ ("EVP_DigestVerify", c.c_int, [pointer, data, size, data, size]),
50
+ ):
51
+ func = getattr(self._crypto, name)
52
+ func.restype, func.argtypes = result, args
53
+ self._nid = self._crypto.OBJ_txt2nid(b"ED25519")
54
+ if not self._nid:
55
+ raise RuntimeError("OpenSSL does not expose Ed25519")
56
+
57
+ def sign(self, message: bytes) -> str:
58
+ """返回十六进制 Ed25519 签名。"""
59
+ return self._operate(message).hex()
60
+
61
+ def verify(self, message: bytes, signature: str) -> bool:
62
+ """验证十六进制 Ed25519 签名,并拒绝格式错误的输入。"""
63
+ return bool(re.fullmatch(r"[0-9a-fA-F]{128}", signature)) and self._operate(
64
+ message, bytes.fromhex(signature)
65
+ )
66
+
67
+ def _operate(self, message: bytes, signature: bytes | None = None):
68
+ """使用每次调用独立的 EVP 上下文,确保多线程中可以复用签名器。"""
69
+ lib = self._crypto
70
+ key = lib.EVP_PKEY_new_raw_private_key(self._nid, None, self._seed, len(self._seed))
71
+ ctx = lib.EVP_MD_CTX_new()
72
+ try:
73
+ if not key or not ctx:
74
+ raise RuntimeError("OpenSSL cannot initialize Ed25519")
75
+ if signature is not None:
76
+ if lib.EVP_DigestVerifyInit(ctx, None, None, None, key) != 1:
77
+ raise RuntimeError("OpenSSL cannot initialize signature verification")
78
+ return lib.EVP_DigestVerify(ctx, signature, len(signature), message, len(message)) == 1
79
+ if lib.EVP_DigestSignInit(ctx, None, None, None, key) != 1:
80
+ raise RuntimeError("OpenSSL cannot initialize signing")
81
+ output = c.create_string_buffer(64)
82
+ size = c.c_size_t(64)
83
+ if lib.EVP_DigestSign(ctx, output, c.byref(size), message, len(message)) != 1:
84
+ raise RuntimeError("OpenSSL cannot sign the QQ callback")
85
+ return output.raw[:size.value]
86
+ finally:
87
+ lib.EVP_MD_CTX_free(ctx)
88
+ lib.EVP_PKEY_free(key)
@@ -0,0 +1,58 @@
1
+ """测试官方签名示例和通过 FastAPI 分发的免 @ 命令。"""
2
+
3
+ import json
4
+ import time
5
+ import unittest
6
+
7
+ from qqpybot import Bot, CATALOG
8
+ from qqpybot.signing import WebhookSigner
9
+
10
+
11
+ class WebhookTest(unittest.IsolatedAsyncioTestCase):
12
+ def test_qq_signature_example(self):
13
+ signer = WebhookSigner("DG5g3B4j9X2KOErG")
14
+ message = b"1725442341Arq0D5A61EgUu4OxUvOp"
15
+ expected = ("87befc99c42c651b3aac0278e71ada338433ae26fcb24307bdc5ad38c1adc2d01bcf"
16
+ "cadc0842edac85e85205028a1132afe09280305f13aa6909ffc2d652c706")
17
+ self.assertEqual(signer.sign(message), expected)
18
+ self.assertTrue(signer.verify(message, expected))
19
+ self.assertFalse(signer.verify(message + b"x", expected))
20
+
21
+ async def test_signed_event_dispatch_and_reject_tampering(self):
22
+ bot = Bot("app-id", "demo-secret")
23
+ calls = []
24
+
25
+ @bot.command("活动日历")
26
+ async def calendar(ctx):
27
+ calls.append(ctx.args)
28
+
29
+ payload = {"op": 0, "t": "GROUP_MESSAGE_CREATE", "id": "event-id",
30
+ "d": {"id": "message-id", "group_openid": "group", "content": "活动日历 2026-11"}}
31
+ body = json.dumps(payload, ensure_ascii=False).encode()
32
+ timestamp = str(int(time.time())).encode()
33
+ signature = bot.signer.sign(timestamp + body).encode()
34
+ app = bot.create_app()
35
+
36
+ async def post(content):
37
+ responses = []
38
+
39
+ async def receive():
40
+ return {"type": "http.request", "body": content, "more_body": False}
41
+
42
+ async def send(message):
43
+ responses.append(message)
44
+
45
+ await app({
46
+ "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
47
+ "method": "POST", "scheme": "https", "path": "/qq/callback",
48
+ "root_path": "", "query_string": b"",
49
+ "headers": [(b"x-bot-appid", b"app-id"), (b"x-signature-timestamp", timestamp),
50
+ (b"x-signature-ed25519", signature)],
51
+ }, receive, send)
52
+ return responses[0]["status"], json.loads(responses[1]["body"])
53
+
54
+ self.assertEqual(await post(body + b" "), (401, {"detail": "Invalid QQ signature"}))
55
+ self.assertEqual(await post(body), (200, {"op": 12}))
56
+ self.assertEqual(await post(body), (200, {"op": 12}))
57
+ self.assertEqual(calls, ["2026-11"])
58
+ self.assertIn("GROUP_MESSAGE_CREATE", CATALOG["events"])