OiBot 2025.5.20__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.
@@ -0,0 +1,18 @@
1
+ name: pypi
2
+
3
+ on: push
4
+
5
+ jobs:
6
+ pypi:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@master
10
+ - uses: actions/setup-python@master
11
+ with:
12
+ python-version: 3.x
13
+ - run: |
14
+ python -m pip install build --user
15
+ python -m build --sdist --wheel --outdir dist
16
+ - uses: pypa/gh-action-pypi-publish@master
17
+ with:
18
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 OrganRemoved
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: OiBot
3
+ Version: 2025.5.20
4
+ Summary: a lightweight bot framework
5
+ License: MIT License
6
+ License-File: LICENSE
7
+ Requires-Python: >=3
8
+ Requires-Dist: aiohttp
9
+ Requires-Dist: cryptography
10
+ Description-Content-Type: text/markdown
11
+
12
+ # OiBot
13
+
14
+ A lightweight bot framework built on [aiohttp](https://github.com/aio-libs/aiohttp) and the official protocol.
15
+
16
+ ## Quick Start
17
+
18
+ ### Installation
19
+
20
+ #### Install from GitHub (for development or bleeding-edge features):
21
+
22
+ ```sh
23
+ pip install --no-cache --upgrade git+https://github.com/OrganRemoved/oibot.git
24
+ ```
25
+
26
+ or
27
+
28
+ ```sh
29
+ pip install --no-cache --upgrade https://github.com/OrganRemoved/oibot/archive/refs/heads/main.zip
30
+ ```
31
+
32
+ #### Install from PyPI (recommended for stable versions):
33
+
34
+ ```sh
35
+ pip install --no-cache --upgrade oibot
36
+ ```
37
+
38
+ ### Example
39
+
40
+ The recommended project structure is as follows:
41
+
42
+ ```sh
43
+ awesome_oibot
44
+ | __init__.py
45
+ | bot.py
46
+ |
47
+ \---plugins
48
+ __init__.py
49
+ echo.py
50
+ ```
51
+
52
+ #### bot.py
53
+
54
+ ```python
55
+ import logging
56
+ from os import environ
57
+
58
+ from oibot.bot import OiBot
59
+
60
+ logging.basicConfig(
61
+ level=logging.INFO,
62
+ format="[%(asctime)s][%(levelname)s][%(module)s:%(funcName)s:%(lineno)d]: %(message)s",
63
+ )
64
+
65
+ if __name__ == "__main__":
66
+ (
67
+ OiBot
68
+ # `plugins`: path(s) to plugin directories, passed to `oibot.plugin.PluginManager.import_from(...)`.
69
+ .build(plugins="plugins")
70
+ # arguments: pass directly to `aiohttp.web.run(...)`
71
+ .run(host=environ["OIBOT_HOST"], port=int(environ["OIBOT_PORT"]))
72
+ )
73
+ ```
74
+
75
+ #### echo.py
76
+
77
+ ```python
78
+ from contextvars import ContextVar
79
+ from os import environ
80
+ from types import GenericAlias
81
+ from typing import Any, AsyncGenerator, ClassVar
82
+ from weakref import WeakKeyDictionary
83
+
84
+ from redis.asyncio.client import Pipeline, Redis
85
+
86
+ from oibot.event.c2c_message_create import C2CMessageCreate
87
+ from oibot.event.group_at_message_create import GroupAtMessageCreateEvent
88
+ from oibot.matcher import Matcher
89
+ from oibot.plugin import Dependency, on
90
+
91
+
92
+ class ContextVarDescriptor:
93
+ __class_getitem__ = classmethod(GenericAlias)
94
+
95
+ def __init__(self, *, default: Any = None) -> None:
96
+ self.default = default
97
+
98
+ def __set_name__(self, owner: Any, name: str) -> None:
99
+ self.context_var = ContextVar(name, default=self.default)
100
+
101
+ def __get__(self, instance: Any, owner: Any) -> Any:
102
+ if instance is None:
103
+ return self
104
+
105
+ return self.context_var.get()
106
+
107
+ def __set__(self, instance: Any, value: Any) -> None:
108
+ self.context_var.set(value)
109
+
110
+
111
+ class Command(Matcher):
112
+ __slots__ = ("command", "separator")
113
+
114
+ cache: ClassVar[
115
+ WeakKeyDictionary[C2CMessageCreate | GroupAtMessageCreateEvent, list[str]]
116
+ ] = WeakKeyDictionary()
117
+
118
+ argv: ClassVar[ContextVarDescriptor[list[str]]] = ContextVarDescriptor(default=[])
119
+ content: ClassVar[ContextVarDescriptor[str]] = ContextVarDescriptor(default=None)
120
+
121
+ def __init__(self, command: str, *, separator: str = " ") -> None:
122
+ super().__init__()
123
+
124
+ self.command = command
125
+ self.separator = separator
126
+
127
+ def __call__(self, event: C2CMessageCreate | GroupAtMessageCreateEvent) -> bool:
128
+ if self.separator != " ":
129
+ argv = [arg for arg in event.content.strip().split(self.separator) if arg]
130
+
131
+ elif not (argv := self.__class__.cache.get(event)):
132
+ self.__class__.cache[event] = argv = [
133
+ arg for arg in event.content.split(self.separator) if arg
134
+ ]
135
+
136
+ if matched := self.command in argv:
137
+ self.__class__.argv = [arg for arg in argv if arg != self.command]
138
+
139
+ self.__class__.content = self.separator.join(
140
+ arg
141
+ for arg in event.content.split(self.separator)
142
+ if arg != self.command
143
+ )
144
+
145
+ elif matched := (command_with_prefix := f"/{self.command}") in argv:
146
+ self.__class__.argv = [arg for arg in argv if arg != command_with_prefix]
147
+
148
+ self.__class__.content = self.separator.join(
149
+ arg
150
+ for arg in event.content.split(self.separator)
151
+ if arg != command_with_prefix
152
+ )
153
+
154
+ return matched
155
+
156
+
157
+ # Dependency Injection examples:
158
+
159
+
160
+ # Define an async generator for Redis, handling connection creation and cleanup.
161
+ async def get_redis(*args, **kwargs) -> AsyncGenerator[Redis, None]:
162
+ if "url" in kwargs:
163
+ redis = Redis.from_url(decode_responses=True, *args, **kwargs)
164
+
165
+ elif "connection_pool" in kwargs:
166
+ redis = Redis.from_pool(*args, **kwargs)
167
+
168
+ else:
169
+ redis = Redis(
170
+ host=kwargs.pop("host", environ.get("REDIS_HOST", "localhost")),
171
+ port=kwargs.pop("port", int(environ.get("REDIS_PORT", 6379))),
172
+ db=kwargs.pop("db", environ.get("REDIS_DB", 0)),
173
+ password=kwargs.pop("password", environ.get("REDIS_PASSWORD", None)),
174
+ decode_responses=kwargs.pop("decode_responses", True),
175
+ **kwargs,
176
+ )
177
+
178
+ async with redis as r:
179
+ yield r
180
+
181
+
182
+ # Chaining Dependency Injection: Define an async generator that depends on another (Redis connection).
183
+ async def get_pipeline(
184
+ redis: Redis = Dependency.provide(dependency=get_redis), *args, **kwargs
185
+ ) -> AsyncGenerator[Pipeline, None]:
186
+ async with redis.pipeline(*args, **kwargs) as pipeline:
187
+ yield pipeline
188
+
189
+ await pipeline.execute()
190
+
191
+
192
+ # Event Handler example:
193
+
194
+
195
+ # Combining multiple rules using `&(and)`, `|(or)`, and `~(not)`.
196
+ @on(matcher=Command("repeat"))
197
+ # For maximum performance, consider using a callable (e.g., a lambda function) directly in the `matcher`.
198
+ # Example: `lambda event: event.group_openid in (...)`
199
+ async def echo(
200
+ # Specify the event type(s) this handler should process using type hints. Use `|` or `typing.Union` for multiple types.
201
+ event: GroupAtMessageCreateEvent,
202
+ *,
203
+ redis: Redis = Dependency.provide(dependency=get_redis),
204
+ pipeline: Pipeline = Dependency.provide(dependency=get_pipeline),
205
+ ) -> None:
206
+ if await redis.get(f"blacklist:group:{event.group_openid}"):
207
+ pipeline.delete(f"config:group:{event.group_openid}")
208
+ pipeline.delete(f"config:user:{event.author.member_openid}")
209
+
210
+ if Command.content == "me" or Command.argv == ["me"]:
211
+ event, send_message_response = await event.defer("go !")
212
+
213
+ for i in range(10):
214
+ if event.content.strip() == "repeat break":
215
+ await event.reply("repeater stopped")
216
+ return
217
+
218
+ event, _ = await event.defer(f"repeat {i}: {event.content.strip()}")
219
+
220
+ await event.reply("repeater stopped")
221
+ ```
@@ -0,0 +1,210 @@
1
+ # OiBot
2
+
3
+ A lightweight bot framework built on [aiohttp](https://github.com/aio-libs/aiohttp) and the official protocol.
4
+
5
+ ## Quick Start
6
+
7
+ ### Installation
8
+
9
+ #### Install from GitHub (for development or bleeding-edge features):
10
+
11
+ ```sh
12
+ pip install --no-cache --upgrade git+https://github.com/OrganRemoved/oibot.git
13
+ ```
14
+
15
+ or
16
+
17
+ ```sh
18
+ pip install --no-cache --upgrade https://github.com/OrganRemoved/oibot/archive/refs/heads/main.zip
19
+ ```
20
+
21
+ #### Install from PyPI (recommended for stable versions):
22
+
23
+ ```sh
24
+ pip install --no-cache --upgrade oibot
25
+ ```
26
+
27
+ ### Example
28
+
29
+ The recommended project structure is as follows:
30
+
31
+ ```sh
32
+ awesome_oibot
33
+ | __init__.py
34
+ | bot.py
35
+ |
36
+ \---plugins
37
+ __init__.py
38
+ echo.py
39
+ ```
40
+
41
+ #### bot.py
42
+
43
+ ```python
44
+ import logging
45
+ from os import environ
46
+
47
+ from oibot.bot import OiBot
48
+
49
+ logging.basicConfig(
50
+ level=logging.INFO,
51
+ format="[%(asctime)s][%(levelname)s][%(module)s:%(funcName)s:%(lineno)d]: %(message)s",
52
+ )
53
+
54
+ if __name__ == "__main__":
55
+ (
56
+ OiBot
57
+ # `plugins`: path(s) to plugin directories, passed to `oibot.plugin.PluginManager.import_from(...)`.
58
+ .build(plugins="plugins")
59
+ # arguments: pass directly to `aiohttp.web.run(...)`
60
+ .run(host=environ["OIBOT_HOST"], port=int(environ["OIBOT_PORT"]))
61
+ )
62
+ ```
63
+
64
+ #### echo.py
65
+
66
+ ```python
67
+ from contextvars import ContextVar
68
+ from os import environ
69
+ from types import GenericAlias
70
+ from typing import Any, AsyncGenerator, ClassVar
71
+ from weakref import WeakKeyDictionary
72
+
73
+ from redis.asyncio.client import Pipeline, Redis
74
+
75
+ from oibot.event.c2c_message_create import C2CMessageCreate
76
+ from oibot.event.group_at_message_create import GroupAtMessageCreateEvent
77
+ from oibot.matcher import Matcher
78
+ from oibot.plugin import Dependency, on
79
+
80
+
81
+ class ContextVarDescriptor:
82
+ __class_getitem__ = classmethod(GenericAlias)
83
+
84
+ def __init__(self, *, default: Any = None) -> None:
85
+ self.default = default
86
+
87
+ def __set_name__(self, owner: Any, name: str) -> None:
88
+ self.context_var = ContextVar(name, default=self.default)
89
+
90
+ def __get__(self, instance: Any, owner: Any) -> Any:
91
+ if instance is None:
92
+ return self
93
+
94
+ return self.context_var.get()
95
+
96
+ def __set__(self, instance: Any, value: Any) -> None:
97
+ self.context_var.set(value)
98
+
99
+
100
+ class Command(Matcher):
101
+ __slots__ = ("command", "separator")
102
+
103
+ cache: ClassVar[
104
+ WeakKeyDictionary[C2CMessageCreate | GroupAtMessageCreateEvent, list[str]]
105
+ ] = WeakKeyDictionary()
106
+
107
+ argv: ClassVar[ContextVarDescriptor[list[str]]] = ContextVarDescriptor(default=[])
108
+ content: ClassVar[ContextVarDescriptor[str]] = ContextVarDescriptor(default=None)
109
+
110
+ def __init__(self, command: str, *, separator: str = " ") -> None:
111
+ super().__init__()
112
+
113
+ self.command = command
114
+ self.separator = separator
115
+
116
+ def __call__(self, event: C2CMessageCreate | GroupAtMessageCreateEvent) -> bool:
117
+ if self.separator != " ":
118
+ argv = [arg for arg in event.content.strip().split(self.separator) if arg]
119
+
120
+ elif not (argv := self.__class__.cache.get(event)):
121
+ self.__class__.cache[event] = argv = [
122
+ arg for arg in event.content.split(self.separator) if arg
123
+ ]
124
+
125
+ if matched := self.command in argv:
126
+ self.__class__.argv = [arg for arg in argv if arg != self.command]
127
+
128
+ self.__class__.content = self.separator.join(
129
+ arg
130
+ for arg in event.content.split(self.separator)
131
+ if arg != self.command
132
+ )
133
+
134
+ elif matched := (command_with_prefix := f"/{self.command}") in argv:
135
+ self.__class__.argv = [arg for arg in argv if arg != command_with_prefix]
136
+
137
+ self.__class__.content = self.separator.join(
138
+ arg
139
+ for arg in event.content.split(self.separator)
140
+ if arg != command_with_prefix
141
+ )
142
+
143
+ return matched
144
+
145
+
146
+ # Dependency Injection examples:
147
+
148
+
149
+ # Define an async generator for Redis, handling connection creation and cleanup.
150
+ async def get_redis(*args, **kwargs) -> AsyncGenerator[Redis, None]:
151
+ if "url" in kwargs:
152
+ redis = Redis.from_url(decode_responses=True, *args, **kwargs)
153
+
154
+ elif "connection_pool" in kwargs:
155
+ redis = Redis.from_pool(*args, **kwargs)
156
+
157
+ else:
158
+ redis = Redis(
159
+ host=kwargs.pop("host", environ.get("REDIS_HOST", "localhost")),
160
+ port=kwargs.pop("port", int(environ.get("REDIS_PORT", 6379))),
161
+ db=kwargs.pop("db", environ.get("REDIS_DB", 0)),
162
+ password=kwargs.pop("password", environ.get("REDIS_PASSWORD", None)),
163
+ decode_responses=kwargs.pop("decode_responses", True),
164
+ **kwargs,
165
+ )
166
+
167
+ async with redis as r:
168
+ yield r
169
+
170
+
171
+ # Chaining Dependency Injection: Define an async generator that depends on another (Redis connection).
172
+ async def get_pipeline(
173
+ redis: Redis = Dependency.provide(dependency=get_redis), *args, **kwargs
174
+ ) -> AsyncGenerator[Pipeline, None]:
175
+ async with redis.pipeline(*args, **kwargs) as pipeline:
176
+ yield pipeline
177
+
178
+ await pipeline.execute()
179
+
180
+
181
+ # Event Handler example:
182
+
183
+
184
+ # Combining multiple rules using `&(and)`, `|(or)`, and `~(not)`.
185
+ @on(matcher=Command("repeat"))
186
+ # For maximum performance, consider using a callable (e.g., a lambda function) directly in the `matcher`.
187
+ # Example: `lambda event: event.group_openid in (...)`
188
+ async def echo(
189
+ # Specify the event type(s) this handler should process using type hints. Use `|` or `typing.Union` for multiple types.
190
+ event: GroupAtMessageCreateEvent,
191
+ *,
192
+ redis: Redis = Dependency.provide(dependency=get_redis),
193
+ pipeline: Pipeline = Dependency.provide(dependency=get_pipeline),
194
+ ) -> None:
195
+ if await redis.get(f"blacklist:group:{event.group_openid}"):
196
+ pipeline.delete(f"config:group:{event.group_openid}")
197
+ pipeline.delete(f"config:user:{event.author.member_openid}")
198
+
199
+ if Command.content == "me" or Command.argv == ["me"]:
200
+ event, send_message_response = await event.defer("go !")
201
+
202
+ for i in range(10):
203
+ if event.content.strip() == "repeat break":
204
+ await event.reply("repeater stopped")
205
+ return
206
+
207
+ event, _ = await event.defer(f"repeat {i}: {event.content.strip()}")
208
+
209
+ await event.reply("repeater stopped")
210
+ ```
File without changes
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
+ )