OiBot 2025.5.20__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.
oibot/__init__.py ADDED
File without changes
oibot/api/__init__.py ADDED
File without changes
@@ -0,0 +1,33 @@
1
+ from oibot.bot import OiBot
2
+
3
+
4
+ async def recall_private_message(*, openid: str, message_id: str) -> None:
5
+ return await OiBot.request(
6
+ method="DELETE", url=f"/v2/users/{openid}/messages/{message_id}"
7
+ )
8
+
9
+
10
+ async def recall_group_message(*, group_openid: str, message_id: str) -> None:
11
+ return await OiBot.request(
12
+ method="DELETE", url=f"/v2/groups/{group_openid}/messages/{message_id}"
13
+ )
14
+
15
+
16
+ async def recall_channel_message(
17
+ *, channel_id: str, message_id: str, hide_tip: bool = False
18
+ ) -> None:
19
+ return await OiBot.request(
20
+ method="DELETE",
21
+ url=f"/channels/{channel_id}/messages/{message_id}",
22
+ params={"htdetip": hide_tip},
23
+ )
24
+
25
+
26
+ async def recall_guild_message(
27
+ *, guild_id: str, message_id, hide_tip: bool = False
28
+ ) -> None:
29
+ return await OiBot.request(
30
+ method="DELETE",
31
+ url=f"/dms/{guild_id}/messages/{message_id}",
32
+ params={"htdetip": hide_tip},
33
+ )
@@ -0,0 +1,356 @@
1
+ from base64 import b64encode
2
+ from enum import IntEnum
3
+ from time import time
4
+ from typing import Literal, NotRequired, TypedDict
5
+
6
+ from oibot.api.upload_file import FileType, upload_group_file, upload_private_file
7
+ from oibot.bot import OiBot
8
+
9
+
10
+ class MsgType(IntEnum):
11
+ PLAINTEXT = 0
12
+ MIX = 1
13
+ MARKDOWN = 2
14
+ ARK = 3
15
+ EMBED = 4
16
+ MEDIA = 7
17
+
18
+
19
+ class MarkdownParam(TypedDict):
20
+ key: str
21
+ value: list[str]
22
+
23
+
24
+ class Markdown(TypedDict):
25
+ content: NotRequired[str]
26
+ custom_template_id: NotRequired[str]
27
+ params: NotRequired[MarkdownParam]
28
+
29
+
30
+ class ButtonRenderData(TypedDict):
31
+ label: str
32
+ visited_label: str
33
+ style: Literal[0, 1]
34
+
35
+
36
+ class ButtonActionPermission(TypedDict):
37
+ type: Literal[0, 1, 2, 3]
38
+ specify_user_ids: NotRequired[list[str]]
39
+ specify_role_ids: NotRequired[list[str]]
40
+
41
+
42
+ class ButtonAction(TypedDict):
43
+ type: Literal[0, 1, 2]
44
+ data: str
45
+ reply: NotRequired[bool]
46
+ enter: NotRequired[bool]
47
+ anchor: NotRequired[Literal[1]]
48
+ click_limit: NotRequired[int]
49
+ at_bot_show_channel_list: NotRequired[bool]
50
+ unsupport_tips: str
51
+
52
+
53
+ class Button(TypedDict):
54
+ id: NotRequired[str]
55
+ render_data: ButtonRenderData
56
+ action: ButtonAction
57
+
58
+
59
+ class Buttons(TypedDict):
60
+ buttons: list[Button]
61
+
62
+
63
+ class Rows(TypedDict):
64
+ rows: list
65
+
66
+
67
+ class Content(TypedDict):
68
+ content: Rows
69
+
70
+
71
+ class Keyboard(TypedDict):
72
+ id: NotRequired[str]
73
+ content: NotRequired[str]
74
+
75
+
76
+ class Thumbnail(TypedDict):
77
+ url: str
78
+
79
+
80
+ class EmbedField(TypedDict):
81
+ name: str
82
+
83
+
84
+ class Embed(TypedDict, total=False):
85
+ title: str
86
+ prompt: str
87
+ thumbnail: Thumbnail
88
+ fields: list[EmbedField]
89
+
90
+
91
+ class ArkObjKV(TypedDict):
92
+ key: str
93
+ value: str
94
+
95
+
96
+ class ArkObj(TypedDict):
97
+ obj_kv: list[ArkObjKV]
98
+
99
+
100
+ class ArkKV(TypedDict):
101
+ key: str
102
+ value: NotRequired[str]
103
+ obj: NotRequired[list[ArkObj]]
104
+
105
+
106
+ class Ark(TypedDict):
107
+ template_id: int
108
+ kv: list
109
+
110
+
111
+ class Media(TypedDict):
112
+ file_uuid: str
113
+ file_info: str
114
+ ttl: int
115
+ id: NotRequired[str]
116
+
117
+
118
+ class MessageReference(TypedDict): ...
119
+
120
+
121
+ class SendMessageResponse(TypedDict):
122
+ id: str
123
+ timestamp: int
124
+
125
+
126
+ async def send_private_message(
127
+ *,
128
+ openid: str,
129
+ msg_type: MsgType,
130
+ content: str | None = None,
131
+ markdown: Markdown | None = None,
132
+ keyboard: Keyboard | None = None,
133
+ embed: Embed | None = None,
134
+ ark: Ark | None = None,
135
+ media: Media | None = None,
136
+ message_reference: MessageReference | None = None,
137
+ event_id: str | None = None,
138
+ msg_id: str | None = None,
139
+ msg_seq: int = 0,
140
+ ) -> SendMessageResponse:
141
+ return await OiBot.request(
142
+ method="POST",
143
+ url=f"/v2/users/{openid}/messages",
144
+ json={
145
+ "content": content,
146
+ "msg_type": msg_type,
147
+ "markdown": markdown,
148
+ "keyboard": keyboard,
149
+ "embed": embed,
150
+ "ark": ark,
151
+ "media": media,
152
+ "message_reference": message_reference,
153
+ "event_id": event_id,
154
+ "msg_id": msg_id,
155
+ "msg_seq": msg_seq,
156
+ },
157
+ )
158
+
159
+
160
+ async def send_group_message(
161
+ *,
162
+ group_openid: str,
163
+ msg_type: MsgType,
164
+ content: str | None = None,
165
+ markdown: Markdown | None = None,
166
+ keyboard: Keyboard | None = None,
167
+ embed: Embed | None = None,
168
+ ark: Ark | None = None,
169
+ media: Media | None = None,
170
+ message_reference: MessageReference | None = None,
171
+ event_id: str | None = None,
172
+ msg_id: str | None = None,
173
+ msg_seq: int = 0,
174
+ ) -> SendMessageResponse:
175
+ return await OiBot.request(
176
+ method="POST",
177
+ url=f"/v2/groups/{group_openid}/messages",
178
+ json={
179
+ "content": content,
180
+ "msg_type": msg_type,
181
+ "markdown": markdown,
182
+ "keyboard": keyboard,
183
+ "embed": embed,
184
+ "ark": ark,
185
+ "media": media,
186
+ "message_reference": message_reference,
187
+ "event_id": event_id,
188
+ "msg_id": msg_id,
189
+ "msg_seq": msg_seq,
190
+ },
191
+ )
192
+
193
+
194
+ async def send_message(
195
+ *,
196
+ openid: str | None = None,
197
+ group_openid: str | None = None,
198
+ content: str | None = None,
199
+ markdown: Markdown | None = None,
200
+ keyboard: Keyboard | None = None,
201
+ embed: Embed | None = None,
202
+ ark: Ark | None = None,
203
+ image: bytes | str | None = None,
204
+ video: bytes | str | None = None,
205
+ voice: bytes | str | None = None,
206
+ message_reference: MessageReference | None = None,
207
+ event_id: str | None = None,
208
+ msg_id: str | None = None,
209
+ ) -> SendMessageResponse:
210
+ file = None
211
+
212
+ if markdown:
213
+ msg_type = MsgType.MARKDOWN
214
+ elif ark:
215
+ msg_type = MsgType.ARK
216
+ elif any((image, video, voice)):
217
+ msg_type = MsgType.MEDIA
218
+ else:
219
+ msg_type = MsgType.PLAINTEXT
220
+
221
+ if openid:
222
+ if image:
223
+ if isinstance(image, bytes):
224
+ file = await upload_private_file(
225
+ openid=openid,
226
+ file_type=FileType.IMAGE,
227
+ file_data=b64encode(image).decode("utf-8"),
228
+ )
229
+
230
+ elif isinstance(image, str) and image.startswith("http"):
231
+ file = await upload_private_file(
232
+ openid=openid, file_type=FileType.IMAGE, url=image
233
+ )
234
+
235
+ else:
236
+ raise ValueError("invalid file type")
237
+
238
+ elif video:
239
+ if isinstance(video, bytes):
240
+ file = await upload_private_file(
241
+ openid=openid,
242
+ file_type=FileType.VIDEO,
243
+ file_data=b64encode(video).decode("utf-8"),
244
+ )
245
+
246
+ elif isinstance(video, str) and video.startswith("http"):
247
+ file = await upload_private_file(
248
+ openid=openid, file_type=FileType.VIDEO, url=video
249
+ )
250
+
251
+ else:
252
+ raise ValueError("invalid file type")
253
+
254
+ elif voice:
255
+ if isinstance(voice, bytes):
256
+ file = await upload_private_file(
257
+ openid=openid,
258
+ file_type=FileType.VOICE,
259
+ file_data=b64encode(voice).decode("utf-8"),
260
+ )
261
+
262
+ elif isinstance(voice, str) and voice.startswith("http"):
263
+ file = await upload_private_file(
264
+ openid=openid, file_type=FileType.VOICE, url=voice
265
+ )
266
+
267
+ else:
268
+ raise ValueError("invalid file type")
269
+
270
+ return await send_private_message(
271
+ openid=openid,
272
+ msg_type=msg_type,
273
+ content=content,
274
+ markdown=markdown,
275
+ keyboard=keyboard,
276
+ embed=embed,
277
+ ark=ark,
278
+ media=file,
279
+ message_reference=message_reference,
280
+ event_id=event_id,
281
+ msg_id=msg_id,
282
+ msg_seq=int(time()),
283
+ )
284
+
285
+ elif group_openid:
286
+ if image:
287
+ if isinstance(image, bytes):
288
+ file = await upload_group_file(
289
+ group_openid=group_openid,
290
+ file_type=FileType.IMAGE,
291
+ file_data=b64encode(image).decode("utf-8"),
292
+ )
293
+
294
+ elif isinstance(image, str) and image.startswith("http"):
295
+ file = await upload_group_file(
296
+ group_openid=group_openid,
297
+ file_type=FileType.IMAGE,
298
+ url=image,
299
+ )
300
+
301
+ else:
302
+ raise ValueError("invalid file type")
303
+
304
+ elif video:
305
+ if isinstance(video, bytes):
306
+ file = await upload_group_file(
307
+ group_openid=group_openid,
308
+ file_type=FileType.VIDEO,
309
+ file_data=b64encode(video).decode("utf-8"),
310
+ )
311
+
312
+ elif isinstance(video, str) and video.startswith("http"):
313
+ file = await upload_group_file(
314
+ group_openid=group_openid,
315
+ file_type=FileType.VIDEO,
316
+ url=video,
317
+ )
318
+
319
+ else:
320
+ raise ValueError("invalid file type")
321
+
322
+ elif voice:
323
+ if isinstance(voice, bytes):
324
+ file = await upload_group_file(
325
+ group_openid=group_openid,
326
+ file_type=FileType.VOICE,
327
+ file_data=b64encode(voice).decode("utf-8"),
328
+ )
329
+
330
+ elif isinstance(voice, str) and voice.startswith("http"):
331
+ file = await upload_group_file(
332
+ group_openid=group_openid,
333
+ file_type=FileType.VOICE,
334
+ url=voice,
335
+ )
336
+
337
+ else:
338
+ raise ValueError("invalid file type")
339
+
340
+ return await send_group_message(
341
+ group_openid=group_openid,
342
+ msg_type=msg_type,
343
+ content=content,
344
+ markdown=markdown,
345
+ keyboard=keyboard,
346
+ embed=embed,
347
+ ark=ark,
348
+ media=file,
349
+ message_reference=message_reference,
350
+ event_id=event_id,
351
+ msg_id=msg_id,
352
+ msg_seq=int(time()),
353
+ )
354
+
355
+ else:
356
+ raise ValueError("parameter `openid` or `group_openid` must be specified")
@@ -0,0 +1,58 @@
1
+ from enum import IntEnum
2
+ from typing import NotRequired, TypedDict
3
+
4
+ from oibot.bot import OiBot
5
+
6
+
7
+ class FileType(IntEnum):
8
+ IMAGE = 1
9
+ VIDEO = 2
10
+ VOICE = 3
11
+ FILE = 4
12
+
13
+
14
+ class UploadFileResponse(TypedDict):
15
+ file_uuid: str
16
+ file_info: str
17
+ ttl: int
18
+ id: NotRequired[str]
19
+
20
+
21
+ async def upload_private_file(
22
+ *,
23
+ openid: str,
24
+ file_type: FileType,
25
+ url: str | None = None,
26
+ srv_send_msg: bool = False,
27
+ file_data: bytes | str | None = None,
28
+ ) -> UploadFileResponse:
29
+ return await OiBot.request(
30
+ method="POST",
31
+ url=f"/v2/users/{openid}/files",
32
+ json={
33
+ "file_type": file_type,
34
+ "url": url,
35
+ "srv_send_msg": srv_send_msg,
36
+ "file_data": file_data,
37
+ },
38
+ )
39
+
40
+
41
+ async def upload_group_file(
42
+ *,
43
+ group_openid: str,
44
+ file_type: FileType,
45
+ url: str | None = None,
46
+ srv_send_msg: bool = False,
47
+ file_data: bytes | str | None = None,
48
+ ) -> UploadFileResponse:
49
+ return await OiBot.request(
50
+ method="POST",
51
+ url=f"/v2/groups/{group_openid}/files",
52
+ json={
53
+ "file_type": file_type,
54
+ "url": url,
55
+ "srv_send_msg": srv_send_msg,
56
+ "file_data": file_data,
57
+ },
58
+ )
oibot/bot.py ADDED
@@ -0,0 +1,213 @@
1
+ import asyncio
2
+ import logging
3
+ from contextvars import ContextVar
4
+ from functools import _make_key, wraps
5
+ from os import environ
6
+ from typing import (
7
+ Any,
8
+ Awaitable,
9
+ Callable,
10
+ ClassVar,
11
+ Hashable,
12
+ Iterable,
13
+ Literal,
14
+ Self,
15
+ TypedDict,
16
+ )
17
+ from weakref import WeakValueDictionary
18
+
19
+ from aiohttp import ClientSession, web
20
+ from aiohttp.web_request import Request
21
+ from aiohttp.web_response import Response
22
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
23
+
24
+ from oibot.event import Context
25
+ from oibot.plugin import PluginManager
26
+
27
+
28
+ class AccessToken(TypedDict):
29
+ access_token: str
30
+ expires_in: int
31
+
32
+
33
+ def singleflight(typed: bool = False) -> Callable[..., Callable[..., Awaitable[Any]]]:
34
+ def decorator(func: Callable[..., Awaitable[Any]]) -> Callable[..., Awaitable[Any]]:
35
+ futures: WeakValueDictionary[Hashable, asyncio.Future] = WeakValueDictionary()
36
+
37
+ @wraps(func)
38
+ async def warpper(*args, **kwargs) -> Any:
39
+ key = _make_key(args, kwargs, typed=typed)
40
+
41
+ if future := futures.get(key):
42
+ result = await future
43
+
44
+ if exception := future.exception():
45
+ raise exception
46
+
47
+ return result
48
+
49
+ futures[key] = future = asyncio.Future()
50
+
51
+ try:
52
+ result = await func(*args, **kwargs)
53
+ future.set_result(result)
54
+ return result
55
+
56
+ except Exception as e:
57
+ future.set_exception(e)
58
+ raise e
59
+
60
+ return warpper
61
+
62
+ return decorator
63
+
64
+
65
+ def keep_alive(
66
+ func: Callable[[str, str], Awaitable[AccessToken]],
67
+ ) -> Callable[[str, str], Awaitable[AccessToken]]:
68
+ cache: dict[tuple[str, str], AccessToken] = {}
69
+
70
+ async def decorator(app_id: str, client_secret: str) -> AccessToken:
71
+ key = (app_id, client_secret)
72
+
73
+ if not (access_token := cache.get(key)):
74
+ cache[key] = access_token = await func(app_id, client_secret)
75
+
76
+ asyncio.get_running_loop().call_later(
77
+ int(access_token["expires_in"]) - 30, cache.pop, key, None
78
+ )
79
+
80
+ return access_token
81
+
82
+ return decorator
83
+
84
+
85
+ @singleflight(typed=False)
86
+ @keep_alive
87
+ async def get_app_access_token(app_id: str, client_secret: str) -> AccessToken:
88
+ async with ClientSession() as session:
89
+ async with session.post(
90
+ "https://bots.qq.com/app/getAppAccessToken",
91
+ json={"appId": app_id, "clientSecret": client_secret},
92
+ ) as response:
93
+ response.raise_for_status()
94
+ return await response.json()
95
+
96
+
97
+ async def handler(
98
+ request: Request, *, background_tasks: set[asyncio.Task] = set()
99
+ ) -> Response:
100
+ ctx: Context = await request.json()
101
+
102
+ logging.debug(ctx)
103
+
104
+ OiBot.app_id.set(request.query.get("id", environ.get("OIBOT_APP_ID")))
105
+ OiBot.app_token.set(request.query.get("token", environ.get("OIBOT_APP_TOKEN")))
106
+ OiBot.app_secret.set(request.query.get("secret", environ.get("OIBOT_APP_SECRET")))
107
+
108
+ match ctx["op"]:
109
+ case 0:
110
+ task = asyncio.create_task(PluginManager.run(ctx=ctx))
111
+ background_tasks.add(task)
112
+ task.add_done_callback(background_tasks.discard)
113
+
114
+ case 13:
115
+ logging.info("webhook verification request received")
116
+
117
+ if not (secret := OiBot.app_secret.get()):
118
+ raise ValueError("parameter `app_secret` must be specified")
119
+
120
+ secret = secret.encode("utf-8")
121
+
122
+ while len(secret) < 32:
123
+ secret *= 2
124
+
125
+ d = ctx["d"]
126
+
127
+ return web.json_response(
128
+ {
129
+ "plain_token": d["plain_token"],
130
+ "signature": (
131
+ Ed25519PrivateKey.from_private_bytes(secret[:32])
132
+ .sign(f"{d['event_ts']}{d['plain_token']}".encode("utf-8"))
133
+ .hex()
134
+ ),
135
+ }
136
+ )
137
+
138
+ case _:
139
+ logging.warning(f"invalid type received {ctx=}")
140
+
141
+ return web.Response(body=None, status=200)
142
+
143
+
144
+ class OiBot:
145
+ __slots__ = ()
146
+
147
+ app: ClassVar[web.Application]
148
+
149
+ app_id: ClassVar[ContextVar[str | None]] = ContextVar(
150
+ "app_id", default=environ.get("OIBOT_APP_ID")
151
+ )
152
+ app_token: ClassVar[ContextVar[str | None]] = ContextVar(
153
+ "app_token", default=environ.get("OIBOT_APP_TOKEN")
154
+ )
155
+ app_secret: ClassVar[ContextVar[str | None]] = ContextVar(
156
+ "app_secret", default=environ.get("OIBOT_APP_SECRET")
157
+ )
158
+
159
+ @classmethod
160
+ async def request(
161
+ cls,
162
+ *,
163
+ method: Literal[
164
+ "GET",
165
+ "POST",
166
+ "PUT",
167
+ "DELETE",
168
+ "PATCH",
169
+ "HEAD",
170
+ "OPTIONS",
171
+ "TRACE",
172
+ "CONNECT",
173
+ ],
174
+ url: str,
175
+ **kwargs,
176
+ ) -> Any:
177
+ logging.debug(f"{method=} {url=} {kwargs=}")
178
+
179
+ async with ClientSession(
180
+ base_url=f"https://{'sandbox.' if environ.get('OIBOT_SANDBOX') else ''}api.sgroup.qq.com",
181
+ headers={
182
+ "Authorization": f"QQBot {
183
+ (
184
+ await get_app_access_token(
185
+ app_id=cls.app_id.get(),
186
+ client_secret=cls.app_secret.get(),
187
+ )
188
+ )['access_token']
189
+ }"
190
+ },
191
+ ) as session:
192
+ async with session.request(method, url, **kwargs) as resp:
193
+ resp.raise_for_status()
194
+ return await resp.json()
195
+
196
+ @classmethod
197
+ def build(cls, plugins: str | Iterable[str] | None = None, **kwargs) -> Self:
198
+ cls.app = app = web.Application(**kwargs)
199
+
200
+ app.router.add_post(path="/", handler=handler)
201
+
202
+ if isinstance(plugins, str):
203
+ PluginManager.import_from(plugins)
204
+
205
+ elif isinstance(plugins, Iterable):
206
+ for plugin in plugins:
207
+ PluginManager.import_from(plugin)
208
+
209
+ return cls()
210
+
211
+ @classmethod
212
+ def run(cls, *args, **kwargs) -> None:
213
+ web.run_app(app=cls.app, *args, **kwargs)
@@ -0,0 +1,51 @@
1
+ import logging
2
+ from typing import ClassVar, TypedDict
3
+
4
+
5
+ class Context(TypedDict):
6
+ d: dict
7
+ id: str
8
+ op: int
9
+ s: int
10
+ t: str
11
+
12
+
13
+ class Event:
14
+ __slots__ = ("_d", "_id", "_op", "_s", "_t")
15
+
16
+ _d: dict
17
+ _id: str
18
+ _op: int
19
+ _s: int
20
+ _t: str
21
+
22
+ event_type: ClassVar[str]
23
+
24
+ event: ClassVar[dict[str, type["Event"]]] = {}
25
+
26
+ def __init__(self, *, ctx: Context) -> None:
27
+ self._d = ctx["d"]
28
+ self._id = ctx["id"]
29
+ self._op = ctx["op"]
30
+ # self._s = ctx["s"]
31
+ self._t = ctx["t"]
32
+
33
+ logging.info(self.__repr__())
34
+
35
+ def __init_subclass__(cls, *args, **kwargs) -> None:
36
+ logging.debug(f"registered {cls} as type {cls._t}")
37
+
38
+ Event.event[cls.event_type] = cls
39
+
40
+ def __repr__(self) -> str:
41
+ return f"""{self.__class__.__name__}({
42
+ ", ".join(
43
+ f"{item}={value}"
44
+ for item in self.__slots__
45
+ if (not item.startswith("__")) and (value := getattr(self, item, None))
46
+ )
47
+ })"""
48
+
49
+ @classmethod
50
+ def dispatch(cls, *, ctx: Context) -> "Event":
51
+ return event(ctx=ctx) if (event := cls.event.get(ctx["t"])) else cls(ctx=ctx)