qbotsdk 0.6.0__py3-none-any.whl
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.
- qbotsdk/__init__.py +76 -0
- qbotsdk/adapter/__init__.py +9 -0
- qbotsdk/adapter/base.py +35 -0
- qbotsdk/adapter/webhook.py +78 -0
- qbotsdk/adapter/websocket.py +65 -0
- qbotsdk/api/__init__.py +46 -0
- qbotsdk/api/_parse.py +29 -0
- qbotsdk/api/channel.py +136 -0
- qbotsdk/api/group.py +184 -0
- qbotsdk/api/guild.py +73 -0
- qbotsdk/api/interaction.py +34 -0
- qbotsdk/api/message.py +55 -0
- qbotsdk/api/reaction.py +125 -0
- qbotsdk/api/user.py +57 -0
- qbotsdk/api/user_message.py +115 -0
- qbotsdk/bot.py +136 -0
- qbotsdk/constant.py +10 -0
- qbotsdk/exceptions.py +195 -0
- qbotsdk/gateway/__init__.py +61 -0
- qbotsdk/gateway/connection.py +316 -0
- qbotsdk/gateway/dispatcher.py +142 -0
- qbotsdk/gateway/handler.py +81 -0
- qbotsdk/gateway/payload.py +198 -0
- qbotsdk/gateway/session.py +59 -0
- qbotsdk/gateway/webhook.py +66 -0
- qbotsdk/gateway/webhook_server.py +171 -0
- qbotsdk/model/__init__.py +145 -0
- qbotsdk/model/base.py +9 -0
- qbotsdk/model/channel.py +74 -0
- qbotsdk/model/draft.py +234 -0
- qbotsdk/model/event.py +410 -0
- qbotsdk/model/group.py +119 -0
- qbotsdk/model/guild.py +29 -0
- qbotsdk/model/keyboard.py +112 -0
- qbotsdk/model/media.py +43 -0
- qbotsdk/model/member.py +27 -0
- qbotsdk/model/message.py +79 -0
- qbotsdk/model/reaction.py +65 -0
- qbotsdk/model/role.py +31 -0
- qbotsdk/model/scene.py +98 -0
- qbotsdk/model/token.py +9 -0
- qbotsdk/model/user.py +63 -0
- qbotsdk/module/__init__.py +1 -0
- qbotsdk/module/http_client.py +372 -0
- qbotsdk/module/pagination.py +74 -0
- qbotsdk/module/rate_limit.py +101 -0
- qbotsdk/module/token_manager.py +151 -0
- qbotsdk/options.py +43 -0
- qbotsdk/py.typed +1 -0
- qbotsdk/storage/__init__.py +28 -0
- qbotsdk/storage/base.py +42 -0
- qbotsdk/storage/file.py +142 -0
- qbotsdk/storage/memory.py +25 -0
- qbotsdk/storage/redis.py +219 -0
- qbotsdk-0.6.0.dist-info/METADATA +250 -0
- qbotsdk-0.6.0.dist-info/RECORD +59 -0
- qbotsdk-0.6.0.dist-info/WHEEL +4 -0
- qbotsdk-0.6.0.dist-info/entry_points.txt +4 -0
- qbotsdk-0.6.0.dist-info/licenses/LICENSE +201 -0
qbotsdk/api/guild.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
"""频道(guild)域接口。"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import AsyncIterator
|
|
8
|
+
|
|
9
|
+
from qbotsdk.model.channel import Channel
|
|
10
|
+
from qbotsdk.model.guild import Guild
|
|
11
|
+
from qbotsdk.model.member import Member
|
|
12
|
+
from qbotsdk.model.role import RolesResult
|
|
13
|
+
from qbotsdk.module.http_client import HTTPClient
|
|
14
|
+
from qbotsdk.module.pagination import paginate
|
|
15
|
+
|
|
16
|
+
from ._parse import expect_list, expect_object
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class GuildResource:
|
|
20
|
+
def __init__(self, http: HTTPClient) -> None:
|
|
21
|
+
self._http = http
|
|
22
|
+
|
|
23
|
+
async def get(self, guild_id: str) -> Guild:
|
|
24
|
+
"""频道详情。"""
|
|
25
|
+
|
|
26
|
+
path = f"/guilds/{guild_id}"
|
|
27
|
+
return Guild.model_validate(expect_object(await self._http.get(path), path))
|
|
28
|
+
|
|
29
|
+
async def channels(self, guild_id: str) -> list[Channel]:
|
|
30
|
+
"""子频道列表。"""
|
|
31
|
+
|
|
32
|
+
path = f"/guilds/{guild_id}/channels"
|
|
33
|
+
payload = expect_list(await self._http.get(path), path)
|
|
34
|
+
return [Channel.model_validate(item) for item in payload]
|
|
35
|
+
|
|
36
|
+
async def members(
|
|
37
|
+
self,
|
|
38
|
+
guild_id: str,
|
|
39
|
+
*,
|
|
40
|
+
after: str = "0",
|
|
41
|
+
limit: int = 100,
|
|
42
|
+
) -> list[Member]:
|
|
43
|
+
"""
|
|
44
|
+
成员列表,游标翻页
|
|
45
|
+
after 传上一页最后一个成员的 user.id,limit 上限 400。
|
|
46
|
+
平台可能重复返回已给过的成员,翻页时需按 `user.id` 去重。
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
path = f"/guilds/{guild_id}/members"
|
|
50
|
+
params: dict[str, str | int] = {"after": after, "limit": limit}
|
|
51
|
+
payload = expect_list(await self._http.get(path, params=params), path)
|
|
52
|
+
return [Member.model_validate(item) for item in payload]
|
|
53
|
+
|
|
54
|
+
async def iter_members(self, guild_id: str, *, limit: int = 100) -> AsyncIterator[Member]:
|
|
55
|
+
"""自动翻页遍历频道成员,按 `user.id` 去重,空页结束。"""
|
|
56
|
+
|
|
57
|
+
async def fetch_page(cursor: str | None) -> list[Member]:
|
|
58
|
+
return await self.members(guild_id, after=cursor or "0", limit=limit)
|
|
59
|
+
|
|
60
|
+
def cursor_of(page: list[Member]) -> str | None:
|
|
61
|
+
return page[-1].user.id
|
|
62
|
+
|
|
63
|
+
def key_of(member: Member) -> str:
|
|
64
|
+
return member.user.id
|
|
65
|
+
|
|
66
|
+
async for member in paginate(fetch_page, cursor_of=cursor_of, key_of=key_of):
|
|
67
|
+
yield member
|
|
68
|
+
|
|
69
|
+
async def roles(self, guild_id: str) -> RolesResult:
|
|
70
|
+
"""身份组列表。"""
|
|
71
|
+
|
|
72
|
+
path = f"/guilds/{guild_id}/roles"
|
|
73
|
+
return RolesResult.model_validate(expect_object(await self._http.get(path), path))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
"""互动回调接口。
|
|
4
|
+
|
|
5
|
+
- 互动事件: https://bot.q.qq.com/wiki/develop/api-v2/autogen/event/interaction_create.html
|
|
6
|
+
- 互动事件响应: https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/interactions_interaction_id.put.html
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from qbotsdk.module.http_client import HTTPClient
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InteractionResource:
|
|
15
|
+
"""`PUT /interactions/{interaction_id}` 的薄封装。"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, http: HTTPClient) -> None:
|
|
18
|
+
self._http = http
|
|
19
|
+
|
|
20
|
+
async def respond(self, interaction_id: str, *, code: int = 0) -> None:
|
|
21
|
+
"""回应互动事件,让客户端停止 loading。
|
|
22
|
+
|
|
23
|
+
官方只要求 type=11 与 type=12 回应,
|
|
24
|
+
其余类型调用也不会报错, 同一个 interaction_id 只能回应一次。
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
interaction_id: INTERACTION_CREATE 事件的 d.id
|
|
28
|
+
code: 0 成功 / 1 操作失败 / 2 操作频繁 / 3 重复操作 / 4 没有权限 / 5 仅管理员操作
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
if not 0 <= code <= 5:
|
|
32
|
+
raise ValueError("interaction code must be between 0 and 5")
|
|
33
|
+
path = f"/interactions/{interaction_id}"
|
|
34
|
+
await self._http.put(path, json={"code": code})
|
qbotsdk/api/message.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
"""消息域。
|
|
4
|
+
|
|
5
|
+
群消息的「回复」并不是单独接口, 就是往群里发一条带 `msg_id` 的消息。
|
|
6
|
+
事件层 (`event.reply()`) 会自动填 `msg_id` 与递增的 `msg_seq`, 这一层留给
|
|
7
|
+
拿到 `msg_id` 但手上没有事件对象的场景。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
from .group import GroupResource
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from qbotsdk.model.draft import MessageMarkdown
|
|
18
|
+
from qbotsdk.model.keyboard import Keyboard
|
|
19
|
+
from qbotsdk.model.media import MediaInfo
|
|
20
|
+
from qbotsdk.model.message import GroupMessageReceipt
|
|
21
|
+
from qbotsdk.module.http_client import HTTPClient
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MessageResource:
|
|
25
|
+
def __init__(self, http: HTTPClient) -> None:
|
|
26
|
+
self._http = http
|
|
27
|
+
self._group = GroupResource(http)
|
|
28
|
+
|
|
29
|
+
async def reply(
|
|
30
|
+
self,
|
|
31
|
+
group_openid: str,
|
|
32
|
+
/,
|
|
33
|
+
*,
|
|
34
|
+
msg_id: str,
|
|
35
|
+
content: str | None = None,
|
|
36
|
+
markdown: MessageMarkdown | None = None,
|
|
37
|
+
media: MediaInfo | None = None,
|
|
38
|
+
keyboard: Keyboard | None = None,
|
|
39
|
+
msg_seq: int | None = None,
|
|
40
|
+
) -> GroupMessageReceipt:
|
|
41
|
+
"""回复群消息。
|
|
42
|
+
|
|
43
|
+
被动回复有效期为 5 分钟, 每条消息最多回 5 次
|
|
44
|
+
回第二次要显式给 msg_seq=2
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
return await self._group.send_message(
|
|
48
|
+
group_openid,
|
|
49
|
+
content=content,
|
|
50
|
+
markdown=markdown,
|
|
51
|
+
media=media,
|
|
52
|
+
keyboard=keyboard,
|
|
53
|
+
reply_to=msg_id,
|
|
54
|
+
msg_seq=msg_seq,
|
|
55
|
+
)
|
qbotsdk/api/reaction.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
"""表情表态接口。
|
|
4
|
+
|
|
5
|
+
- 发表 / 删除: https://bot.q.qq.com/wiki/develop/pythonsdk/api/reaction/post_reaction.html
|
|
6
|
+
- 用户列表: https://bot.q.qq.com/wiki/develop/pythonsdk/api/reaction/get_reaction_users.html
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import AsyncIterator
|
|
12
|
+
|
|
13
|
+
from qbotsdk.model.reaction import ReactionUsers
|
|
14
|
+
from qbotsdk.model.user import GuildUser
|
|
15
|
+
from qbotsdk.module.http_client import HTTPClient
|
|
16
|
+
from qbotsdk.module.pagination import paginate
|
|
17
|
+
|
|
18
|
+
_MAX_LIMIT = 100
|
|
19
|
+
_DEFAULT_LIMIT = 20
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ReactionResource:
|
|
23
|
+
"""子频道消息上的表情表态。"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, http: HTTPClient) -> None:
|
|
26
|
+
self._http = http
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def _path(channel_id: str, message_id: str, emoji_type: int) -> str:
|
|
30
|
+
return f"/channels/{channel_id}/messages/{message_id}/reactions/{emoji_type}"
|
|
31
|
+
|
|
32
|
+
async def add(
|
|
33
|
+
self,
|
|
34
|
+
channel_id: str,
|
|
35
|
+
message_id: str,
|
|
36
|
+
emoji_type: int,
|
|
37
|
+
emoji_id: str,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""给消息发表表情表态。
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
channel_id: 子频道 ID
|
|
43
|
+
message_id: 消息 ID
|
|
44
|
+
emoji_type: 表情类型, 参考 EmojiType
|
|
45
|
+
emoji_id: 表情 ID, 系统表情是数字, emoji 表情是 emoji 本身
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
path = f"{self._path(channel_id, message_id, emoji_type)}/{emoji_id}"
|
|
49
|
+
await self._http.put(path)
|
|
50
|
+
|
|
51
|
+
async def remove(
|
|
52
|
+
self,
|
|
53
|
+
channel_id: str,
|
|
54
|
+
message_id: str,
|
|
55
|
+
emoji_type: int,
|
|
56
|
+
emoji_id: str,
|
|
57
|
+
) -> None:
|
|
58
|
+
"""删除机器人自己发表的表态。"""
|
|
59
|
+
|
|
60
|
+
path = f"{self._path(channel_id, message_id, emoji_type)}/{emoji_id}"
|
|
61
|
+
await self._http.request("DELETE", path)
|
|
62
|
+
|
|
63
|
+
async def users(
|
|
64
|
+
self,
|
|
65
|
+
channel_id: str,
|
|
66
|
+
message_id: str,
|
|
67
|
+
emoji_type: int,
|
|
68
|
+
*,
|
|
69
|
+
emoji_id: str | None = None,
|
|
70
|
+
cookie: str = "",
|
|
71
|
+
limit: int = _DEFAULT_LIMIT,
|
|
72
|
+
) -> ReactionUsers:
|
|
73
|
+
"""拉取某个表情表态的用户列表。
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
channel_id: 子频道 ID
|
|
77
|
+
message_id: 消息 ID
|
|
78
|
+
emoji_type: 表情类型, 参考 EmojiType
|
|
79
|
+
emoji_id: 表情 ID, 同一种类型下要区分具体表情时传
|
|
80
|
+
cookie: 上一页返回的 cookie, 第一页留空
|
|
81
|
+
limit: 本页最多返回多少用户, 1-100
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
if not 1 <= limit <= _MAX_LIMIT:
|
|
85
|
+
raise ValueError("limit must be between 1 and 100")
|
|
86
|
+
params: dict[str, str] = {"cookie": cookie, "limit": str(limit)}
|
|
87
|
+
if emoji_id is not None:
|
|
88
|
+
params["emoji_id"] = emoji_id
|
|
89
|
+
path = self._path(channel_id, message_id, emoji_type)
|
|
90
|
+
payload = await self._http.get(path, params=params)
|
|
91
|
+
return ReactionUsers.model_validate(payload)
|
|
92
|
+
|
|
93
|
+
async def iter_users(
|
|
94
|
+
self,
|
|
95
|
+
channel_id: str,
|
|
96
|
+
message_id: str,
|
|
97
|
+
emoji_type: int,
|
|
98
|
+
*,
|
|
99
|
+
emoji_id: str | None = None,
|
|
100
|
+
limit: int = _DEFAULT_LIMIT,
|
|
101
|
+
) -> AsyncIterator[GuildUser]:
|
|
102
|
+
"""逐条产出该表情下的用户, 按 user.id 去重。"""
|
|
103
|
+
|
|
104
|
+
next_cookie = ""
|
|
105
|
+
is_end = False
|
|
106
|
+
|
|
107
|
+
async def fetch_page(cursor: str | None) -> list[GuildUser]:
|
|
108
|
+
nonlocal next_cookie, is_end
|
|
109
|
+
page = await self.users(
|
|
110
|
+
channel_id,
|
|
111
|
+
message_id,
|
|
112
|
+
emoji_type,
|
|
113
|
+
emoji_id=emoji_id,
|
|
114
|
+
cookie=cursor or "",
|
|
115
|
+
limit=limit,
|
|
116
|
+
)
|
|
117
|
+
next_cookie = page.cookie
|
|
118
|
+
is_end = page.is_end
|
|
119
|
+
return page.users
|
|
120
|
+
|
|
121
|
+
def cursor_of(_: list[GuildUser]) -> str | None:
|
|
122
|
+
return None if is_end else next_cookie
|
|
123
|
+
|
|
124
|
+
async for user in paginate(fetch_page, cursor_of=cursor_of, key_of=lambda user: user.id):
|
|
125
|
+
yield user
|
qbotsdk/api/user.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
"""用户域接口。"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import AsyncIterator
|
|
8
|
+
|
|
9
|
+
from qbotsdk.model.guild import Guild
|
|
10
|
+
from qbotsdk.model.user import GuildUser
|
|
11
|
+
from qbotsdk.module.http_client import HTTPClient
|
|
12
|
+
from qbotsdk.module.pagination import paginate
|
|
13
|
+
|
|
14
|
+
from ._parse import expect_list, expect_object
|
|
15
|
+
|
|
16
|
+
_ME_PATH = "/users/@me"
|
|
17
|
+
_GUILDS_PATH = "/users/@me/guilds"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UserResource:
|
|
21
|
+
def __init__(self, http: HTTPClient) -> None:
|
|
22
|
+
self._http = http
|
|
23
|
+
|
|
24
|
+
async def me(self) -> GuildUser:
|
|
25
|
+
"""当前机器人自身信息。"""
|
|
26
|
+
|
|
27
|
+
payload = expect_object(await self._http.get(_ME_PATH), _ME_PATH)
|
|
28
|
+
return GuildUser.model_validate(payload)
|
|
29
|
+
|
|
30
|
+
async def guilds(
|
|
31
|
+
self,
|
|
32
|
+
*,
|
|
33
|
+
before: str | None = None,
|
|
34
|
+
after: str | None = None,
|
|
35
|
+
limit: int = 100,
|
|
36
|
+
) -> list[Guild]:
|
|
37
|
+
"""机器人加入的频道列表,limit 上限 100;before 与 after 同给时 after 失效。"""
|
|
38
|
+
|
|
39
|
+
params: dict[str, str | int] = {"limit": limit}
|
|
40
|
+
if before is not None:
|
|
41
|
+
params["before"] = before
|
|
42
|
+
if after is not None:
|
|
43
|
+
params["after"] = after
|
|
44
|
+
payload = expect_list(await self._http.get(_GUILDS_PATH, params=params), _GUILDS_PATH)
|
|
45
|
+
return [Guild.model_validate(item) for item in payload]
|
|
46
|
+
|
|
47
|
+
async def iter_guilds(self, *, limit: int = 100) -> AsyncIterator[Guild]:
|
|
48
|
+
"""自动翻页遍历全部频道,某页不足 limit 即结束。"""
|
|
49
|
+
|
|
50
|
+
async def fetch_page(cursor: str | None) -> list[Guild]:
|
|
51
|
+
return await self.guilds(after=cursor, limit=limit)
|
|
52
|
+
|
|
53
|
+
def cursor_of(page: list[Guild]) -> str | None:
|
|
54
|
+
return page[-1].id
|
|
55
|
+
|
|
56
|
+
async for guild in paginate(fetch_page, cursor_of=cursor_of, page_size=limit):
|
|
57
|
+
yield guild
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
"""单聊消息域接口。
|
|
4
|
+
|
|
5
|
+
接口文档: https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_openid_messages.post.html
|
|
6
|
+
被动回复有效期 60 分钟, 每条消息最多回 4 次。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from qbotsdk.model.draft import InputNotify, MessageMarkdown, UserMessageDraft
|
|
12
|
+
from qbotsdk.model.keyboard import Keyboard
|
|
13
|
+
from qbotsdk.model.media import FileType, MediaInfo, UploadedFile
|
|
14
|
+
from qbotsdk.model.message import UserMessageReceipt
|
|
15
|
+
from qbotsdk.module.http_client import HTTPClient
|
|
16
|
+
from qbotsdk.module.rate_limit import RateLimiter
|
|
17
|
+
|
|
18
|
+
from ._parse import expect_object
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UserMessageResource:
|
|
22
|
+
def __init__(self, http: HTTPClient, *, limiter: RateLimiter | None = None) -> None:
|
|
23
|
+
self._http = http
|
|
24
|
+
self._limiter = limiter
|
|
25
|
+
|
|
26
|
+
async def send_message(
|
|
27
|
+
self,
|
|
28
|
+
user_openid: str,
|
|
29
|
+
*,
|
|
30
|
+
content: str | None = None,
|
|
31
|
+
markdown: MessageMarkdown | None = None,
|
|
32
|
+
media: MediaInfo | None = None,
|
|
33
|
+
keyboard: Keyboard | None = None,
|
|
34
|
+
reply_to: str | None = None,
|
|
35
|
+
event_id: str | None = None,
|
|
36
|
+
msg_seq: int | None = None,
|
|
37
|
+
is_wakeup: bool = False,
|
|
38
|
+
) -> UserMessageReceipt:
|
|
39
|
+
"""发单聊消息。
|
|
40
|
+
|
|
41
|
+
被动回复需带 reply_to,有效期 60 分钟
|
|
42
|
+
同一个 msg_id + msg_seq 重复发送会被拒,要回第二次请显式传 msg_seq=2
|
|
43
|
+
is_wakeup=True 是互动召回消息,与 reply_to / event_id 互斥。
|
|
44
|
+
|
|
45
|
+
keyboard 只在 Markdown 消息上渲染: 只传 content + keyboard 时,
|
|
46
|
+
content 会被自动搬进 markdown 并把 msg_type 置 2。
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
path = f"/v2/users/{user_openid}/messages"
|
|
50
|
+
if self._limiter is not None:
|
|
51
|
+
self._limiter.check("c2c", user_openid)
|
|
52
|
+
if reply_to is not None and msg_seq is None:
|
|
53
|
+
msg_seq = 1
|
|
54
|
+
draft = UserMessageDraft(
|
|
55
|
+
content=content,
|
|
56
|
+
markdown=markdown,
|
|
57
|
+
media=media,
|
|
58
|
+
keyboard=keyboard,
|
|
59
|
+
msg_id=reply_to,
|
|
60
|
+
event_id=event_id,
|
|
61
|
+
msg_seq=msg_seq,
|
|
62
|
+
is_wakeup=is_wakeup or None,
|
|
63
|
+
)
|
|
64
|
+
payload = await self._http.post(
|
|
65
|
+
path,
|
|
66
|
+
json=draft.model_dump(by_alias=True, exclude_none=True, mode="json"),
|
|
67
|
+
)
|
|
68
|
+
return UserMessageReceipt.model_validate(expect_object(payload, path))
|
|
69
|
+
|
|
70
|
+
async def notify_input(self, user_openid: str, *, seconds: int = 60) -> UserMessageReceipt:
|
|
71
|
+
"""给用户展示「机器人正在输入」,最多 60 秒。
|
|
72
|
+
|
|
73
|
+
这是独立的 msg_type=6 消息,不承载正文。
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
path = f"/v2/users/{user_openid}/messages"
|
|
77
|
+
draft = UserMessageDraft(input_notify=InputNotify(input_second=seconds))
|
|
78
|
+
payload = await self._http.post(
|
|
79
|
+
path,
|
|
80
|
+
json=draft.model_dump(by_alias=True, exclude_none=True, mode="json"),
|
|
81
|
+
)
|
|
82
|
+
return UserMessageReceipt.model_validate(expect_object(payload, path))
|
|
83
|
+
|
|
84
|
+
async def recall_message(self, user_openid: str, message_id: str) -> None:
|
|
85
|
+
"""撤回单聊消息, 发送后 2 分钟内有效。"""
|
|
86
|
+
|
|
87
|
+
path = f"/v2/users/{user_openid}/messages/{message_id}"
|
|
88
|
+
await self._http.request("DELETE", path)
|
|
89
|
+
|
|
90
|
+
async def upload_file(
|
|
91
|
+
self,
|
|
92
|
+
user_openid: str,
|
|
93
|
+
file_type: FileType,
|
|
94
|
+
/,
|
|
95
|
+
*,
|
|
96
|
+
url: str,
|
|
97
|
+
srv_send_msg: bool = False,
|
|
98
|
+
) -> UploadedFile:
|
|
99
|
+
"""上传单聊富媒体。
|
|
100
|
+
|
|
101
|
+
只实现 url 方式:单聊的二进制直传官方文档没有给字段表
|
|
102
|
+
返回的 file_info 填进 send_message 的 media。
|
|
103
|
+
srv_send_msg=True 时服务端上传后立即发送,会占用主动消息频次。
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
path = f"/v2/users/{user_openid}/files"
|
|
107
|
+
payload = await self._http.post(
|
|
108
|
+
path,
|
|
109
|
+
json={
|
|
110
|
+
"file_type": int(file_type),
|
|
111
|
+
"url": url,
|
|
112
|
+
"srv_send_msg": srv_send_msg,
|
|
113
|
+
},
|
|
114
|
+
)
|
|
115
|
+
return UploadedFile.model_validate(expect_object(payload, path))
|
qbotsdk/bot.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
"""机器人门面:把 HTTP 资源层与事件分发串起来, 接入方式由适配器决定。"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
|
|
10
|
+
from async_event_bus import EventContext
|
|
11
|
+
|
|
12
|
+
from .adapter.base import Adapter, AdapterContext
|
|
13
|
+
from .adapter.websocket import WebSocketAdapter
|
|
14
|
+
from .api import ApiClient
|
|
15
|
+
from .gateway.dispatcher import Dispatcher
|
|
16
|
+
from .model.event import EventModel, UnknownEvent
|
|
17
|
+
from .model.user import GuildUser
|
|
18
|
+
from .module.http_client import HTTPClient
|
|
19
|
+
from .options import ClientOptions
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Bot:
|
|
23
|
+
"""默认用 WebSocket 长连接收事件,换接入方式就传 `adapter=`。
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
bot = Bot(app_id, app_secret) # 等价于 adapter=WebSocketAdapter()
|
|
27
|
+
bot = Bot(app_id, app_secret, adapter=WebhookAdapter(...))
|
|
28
|
+
```
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
app_id: str,
|
|
34
|
+
app_secret: str,
|
|
35
|
+
*,
|
|
36
|
+
adapter: Adapter | None = None,
|
|
37
|
+
options: ClientOptions | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""创建门面, 不做任何网络操作。
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
app_id: 机器人 AppID。
|
|
43
|
+
app_secret: 机器人 AppSecret。
|
|
44
|
+
adapter: 接入方式, 不传用 WebSocketAdapter()。
|
|
45
|
+
options: 客户端配置, 见 ClientOptions。
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
self._http = HTTPClient(app_id, app_secret, options=options)
|
|
49
|
+
self._api = ApiClient(self._http)
|
|
50
|
+
self._adapter: Adapter = adapter if adapter is not None else WebSocketAdapter()
|
|
51
|
+
self._dispatcher = Dispatcher(api=self._api)
|
|
52
|
+
self._started = False
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def api(self) -> ApiClient:
|
|
56
|
+
return self._api
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def adapter(self) -> Adapter:
|
|
60
|
+
return self._adapter
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def dispatcher(self) -> Dispatcher:
|
|
64
|
+
"""事件分发器, `on()` 只是它的转发。"""
|
|
65
|
+
|
|
66
|
+
return self._dispatcher
|
|
67
|
+
|
|
68
|
+
def on[E: EventModel](
|
|
69
|
+
self, event_type: type[E]
|
|
70
|
+
) -> Callable[
|
|
71
|
+
[Callable[[EventContext[E]], Awaitable[None]]],
|
|
72
|
+
Callable[[EventContext[E]], Awaitable[None]],
|
|
73
|
+
]:
|
|
74
|
+
"""注册事件处理器, 只接受 `async def`。
|
|
75
|
+
|
|
76
|
+
事件对象在 `ctx.event` 上; 能回复的事件类型直接提供 `reply()` 方法
|
|
77
|
+
(`GroupAtMessageCreate`/`C2CMessageCreate`/`ChannelMessageCreate`),
|
|
78
|
+
互动事件用 `respond()`,没有这些方法的事件就是不支持回复。
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
return self._dispatcher.on(event_type)
|
|
82
|
+
|
|
83
|
+
def on_unknown(
|
|
84
|
+
self,
|
|
85
|
+
) -> Callable[
|
|
86
|
+
[Callable[[EventContext[UnknownEvent]], Awaitable[None]]],
|
|
87
|
+
Callable[[EventContext[UnknownEvent]], Awaitable[None]],
|
|
88
|
+
]:
|
|
89
|
+
"""注册认不出来的事件的处理器。"""
|
|
90
|
+
|
|
91
|
+
return self._dispatcher.on_unknown()
|
|
92
|
+
|
|
93
|
+
async def start(self) -> None:
|
|
94
|
+
"""让适配器开始收事件, 立即返回。
|
|
95
|
+
|
|
96
|
+
处理器的注册可以放在 start() 前后;重复调用抛 `RuntimeError`。
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
if self._started:
|
|
100
|
+
raise RuntimeError("bot is already started")
|
|
101
|
+
|
|
102
|
+
await self._adapter.start(
|
|
103
|
+
AdapterContext(http=self._http, api=self._api, dispatcher=self._dispatcher)
|
|
104
|
+
)
|
|
105
|
+
self._started = True
|
|
106
|
+
|
|
107
|
+
async def stop(self) -> None:
|
|
108
|
+
"""停掉适配器并清空事件订阅。
|
|
109
|
+
|
|
110
|
+
停止后订阅会被清空, 再次 start() 需要重新注册处理器。
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
if self._started:
|
|
114
|
+
await self._adapter.stop()
|
|
115
|
+
self._started = False
|
|
116
|
+
await self._dispatcher.close()
|
|
117
|
+
|
|
118
|
+
async def get_me(self) -> GuildUser:
|
|
119
|
+
"""已弃用:请改用 `bot.api.user.me()`,v0.3 移除。"""
|
|
120
|
+
|
|
121
|
+
return await self._api.user.me()
|
|
122
|
+
|
|
123
|
+
async def close(self) -> None:
|
|
124
|
+
await self.stop()
|
|
125
|
+
await self._http.close()
|
|
126
|
+
|
|
127
|
+
async def __aenter__(self) -> Bot:
|
|
128
|
+
return self
|
|
129
|
+
|
|
130
|
+
async def __aexit__(
|
|
131
|
+
self,
|
|
132
|
+
exc_type: type[BaseException] | None,
|
|
133
|
+
exc_value: BaseException | None,
|
|
134
|
+
traceback: TracebackType | None,
|
|
135
|
+
) -> None:
|
|
136
|
+
await self.close()
|
qbotsdk/constant.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Copyright (c) 2026-present Half_nothing.
|
|
2
|
+
|
|
3
|
+
# OpenAPI 根地址
|
|
4
|
+
BASE_URL: str = "https://api.bot.qq.com"
|
|
5
|
+
# 用 AppID/AppSecret 换取 access_token 的凭证接口
|
|
6
|
+
TOKEN_URL: str = f"{BASE_URL}/app/getAppAccessToken"
|
|
7
|
+
# 鉴权头固定前缀, 格式为 "QQBot <token>"
|
|
8
|
+
AUTHORIZATION_SCHEME: str = "QQBot"
|
|
9
|
+
# 响应头里的全链路追踪 ID
|
|
10
|
+
TRACE_ID_HEADER: str = "X-Tps-trace-ID"
|