potehinsonnet 0.19.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.
- potehinsonnet-0.19.0/LICENSE +21 -0
- potehinsonnet-0.19.0/PKG-INFO +106 -0
- potehinsonnet-0.19.0/README.md +86 -0
- potehinsonnet-0.19.0/potehinsonnet/__init__.py +5 -0
- potehinsonnet-0.19.0/potehinsonnet/context.py +74 -0
- potehinsonnet-0.19.0/potehinsonnet/discord_provider.py +22 -0
- potehinsonnet-0.19.0/potehinsonnet/files.py +85 -0
- potehinsonnet-0.19.0/potehinsonnet/manifest.py +191 -0
- potehinsonnet-0.19.0/potehinsonnet/monitoring/__init__.py +0 -0
- potehinsonnet-0.19.0/potehinsonnet/monitoring/health.py +79 -0
- potehinsonnet-0.19.0/potehinsonnet/net.py +114 -0
- potehinsonnet-0.19.0/potehinsonnet/net_models/__init__.py +0 -0
- potehinsonnet-0.19.0/potehinsonnet/net_models/discord_models.py +543 -0
- potehinsonnet-0.19.0/potehinsonnet/net_models/panel_models.py +255 -0
- potehinsonnet-0.19.0/potehinsonnet/net_models/panel_ui.py +371 -0
- potehinsonnet-0.19.0/potehinsonnet/net_models/system_models.py +30 -0
- potehinsonnet-0.19.0/potehinsonnet/pack.py +97 -0
- potehinsonnet-0.19.0/potehinsonnet/panel_router.py +96 -0
- potehinsonnet-0.19.0/potehinsonnet/plugin.py +261 -0
- potehinsonnet-0.19.0/potehinsonnet/run.py +80 -0
- potehinsonnet-0.19.0/potehinsonnet/setup/button_registrator.py +107 -0
- potehinsonnet-0.19.0/potehinsonnet/setup/command_registrator.py +196 -0
- potehinsonnet-0.19.0/potehinsonnet/storage.py +210 -0
- potehinsonnet-0.19.0/potehinsonnet/testing.py +214 -0
- potehinsonnet-0.19.0/pyproject.toml +45 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Azhestkov
|
|
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,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: potehinsonnet
|
|
3
|
+
Version: 0.19.0
|
|
4
|
+
Summary: Плагины для Discord-бота Potehinson: команды, кнопки, веб-панель и данные через NATS
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: discord,bot,plugins,nats
|
|
8
|
+
Author: Azhestkov
|
|
9
|
+
Requires-Python: >=3.14
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Dist: nats-py (>=2.15.0,<3.0.0)
|
|
15
|
+
Requires-Dist: pydantic (>=2.13.5,<3.0.0)
|
|
16
|
+
Project-URL: Issues, https://github.com/uto4e4ka/poteninson_net/issues
|
|
17
|
+
Project-URL: Repository, https://github.com/uto4e4ka/poteninson_net
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# potehinsonnet
|
|
21
|
+
|
|
22
|
+
Библиотека для плагинов Discord-бота **Potehinson**. Плагин — отдельный процесс: бот держит соединение
|
|
23
|
+
с Discord, а плагин общается с ним через [NATS](https://nats.io) — регистрирует слэш-команды и кнопки,
|
|
24
|
+
отвечает на них, отдаёт страницы веб-панели и хранит свои данные.
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install potehinsonnet
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Нужен Python 3.14+.
|
|
31
|
+
|
|
32
|
+
## Плагин за минуту
|
|
33
|
+
|
|
34
|
+
`plugin.toml` в корне плагина:
|
|
35
|
+
|
|
36
|
+
```toml
|
|
37
|
+
[plugin]
|
|
38
|
+
name = "beer_plugin"
|
|
39
|
+
label = "🍺 Пивная биржа"
|
|
40
|
+
version = "1.0.0"
|
|
41
|
+
|
|
42
|
+
[runtime]
|
|
43
|
+
entry = "beer_plugin.main:create_plugin"
|
|
44
|
+
potehinsonnet = ">=0.19,<1.0"
|
|
45
|
+
|
|
46
|
+
[permissions]
|
|
47
|
+
discord = ["send_message"]
|
|
48
|
+
commands = true
|
|
49
|
+
panel = true
|
|
50
|
+
|
|
51
|
+
[settings.api_key]
|
|
52
|
+
label = "Ключ API"
|
|
53
|
+
secret = true
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`beer_plugin/main.py`:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from potehinsonnet import Plugin, PluginContext
|
|
60
|
+
from potehinsonnet.net_models.discord_models import Command, ExecutedCommand, ExecutedCommandResponse
|
|
61
|
+
from potehinsonnet.net_models.panel_ui import Button, PanelContext, PanelPage, Text
|
|
62
|
+
from pydantic import BaseModel
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Price(BaseModel):
|
|
66
|
+
beer: str
|
|
67
|
+
rub: int
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def create_plugin(ctx: PluginContext) -> Plugin:
|
|
71
|
+
plugin = Plugin.from_context(ctx)
|
|
72
|
+
prices = ctx.data.collection("prices.json", Price, key="beer") # файл в папке данных плагина
|
|
73
|
+
|
|
74
|
+
@plugin.command(Command(name="beer", description="Цена пива", tag="beer"))
|
|
75
|
+
async def beer(cmd: ExecutedCommand) -> ExecutedCommandResponse:
|
|
76
|
+
price = prices.get("лагер")
|
|
77
|
+
return ExecutedCommandResponse(message=f"{price.rub if price else '?'} ₽", is_final=True)
|
|
78
|
+
|
|
79
|
+
@plugin.panel_page("beer", title="Пиво", icon="🍺") # страница в веб-панели
|
|
80
|
+
async def beer_page(panel: PanelContext) -> PanelPage:
|
|
81
|
+
return PanelPage(blocks=[Text(f"Сортов: {len(prices.all())}"), Button(action="reset", label="Сбросить")])
|
|
82
|
+
|
|
83
|
+
@plugin.panel_action("reset")
|
|
84
|
+
async def reset(panel: PanelContext, values: dict) -> str:
|
|
85
|
+
prices.replace_all([])
|
|
86
|
+
return "Цены сброшены"
|
|
87
|
+
|
|
88
|
+
return plugin
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Запуск: хост бота ставит и запускает плагин сам (zip через панель). Для разработки —
|
|
92
|
+
`python -m potehinsonnet.run .` из папки плагина (нужен NATS на `localhost:4222`).
|
|
93
|
+
|
|
94
|
+
## Что внутри
|
|
95
|
+
|
|
96
|
+
| Модуль | Для чего |
|
|
97
|
+
|---|---|
|
|
98
|
+
| `Plugin`, `PluginContext` | плагин, его настройки (`ctx.settings`), папка данных, адрес NATS — всё от хоста |
|
|
99
|
+
| `@plugin.command`, `@plugin.button` | слэш-команды и кнопки Discord; ответ — один или поток кадров (анимация) |
|
|
100
|
+
| `plugin.discord` | отправить, изменить, удалить сообщение; голосовые каналы |
|
|
101
|
+
| `@plugin.panel_page`, `panel_action` | страницы веб-панели из блоков (`net_models.panel_ui`): текст, таблицы, формы, кнопки, разделы, загрузка файлов |
|
|
102
|
+
| `ctx.data` (`storage`) | данные плагина в JSON: `collection`, `document`, `file` — проверка моделью pydantic, атомарная запись, битые файлы откладываются, а не затираются |
|
|
103
|
+
| `plugin.files` (`files`) | большие файлы через NATS Object Store: загрузка из панели и выдача на скачивание |
|
|
104
|
+
| `python -m potehinsonnet.pack` | собрать zip плагина для установки через панель (`--bump patch`, `--no-data`) |
|
|
105
|
+
| `potehinsonnet.testing` | `FakeNats` — NATS в памяти для тестов плагина |
|
|
106
|
+
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# potehinsonnet
|
|
2
|
+
|
|
3
|
+
Библиотека для плагинов Discord-бота **Potehinson**. Плагин — отдельный процесс: бот держит соединение
|
|
4
|
+
с Discord, а плагин общается с ним через [NATS](https://nats.io) — регистрирует слэш-команды и кнопки,
|
|
5
|
+
отвечает на них, отдаёт страницы веб-панели и хранит свои данные.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install potehinsonnet
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Нужен Python 3.14+.
|
|
12
|
+
|
|
13
|
+
## Плагин за минуту
|
|
14
|
+
|
|
15
|
+
`plugin.toml` в корне плагина:
|
|
16
|
+
|
|
17
|
+
```toml
|
|
18
|
+
[plugin]
|
|
19
|
+
name = "beer_plugin"
|
|
20
|
+
label = "🍺 Пивная биржа"
|
|
21
|
+
version = "1.0.0"
|
|
22
|
+
|
|
23
|
+
[runtime]
|
|
24
|
+
entry = "beer_plugin.main:create_plugin"
|
|
25
|
+
potehinsonnet = ">=0.19,<1.0"
|
|
26
|
+
|
|
27
|
+
[permissions]
|
|
28
|
+
discord = ["send_message"]
|
|
29
|
+
commands = true
|
|
30
|
+
panel = true
|
|
31
|
+
|
|
32
|
+
[settings.api_key]
|
|
33
|
+
label = "Ключ API"
|
|
34
|
+
secret = true
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`beer_plugin/main.py`:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from potehinsonnet import Plugin, PluginContext
|
|
41
|
+
from potehinsonnet.net_models.discord_models import Command, ExecutedCommand, ExecutedCommandResponse
|
|
42
|
+
from potehinsonnet.net_models.panel_ui import Button, PanelContext, PanelPage, Text
|
|
43
|
+
from pydantic import BaseModel
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Price(BaseModel):
|
|
47
|
+
beer: str
|
|
48
|
+
rub: int
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def create_plugin(ctx: PluginContext) -> Plugin:
|
|
52
|
+
plugin = Plugin.from_context(ctx)
|
|
53
|
+
prices = ctx.data.collection("prices.json", Price, key="beer") # файл в папке данных плагина
|
|
54
|
+
|
|
55
|
+
@plugin.command(Command(name="beer", description="Цена пива", tag="beer"))
|
|
56
|
+
async def beer(cmd: ExecutedCommand) -> ExecutedCommandResponse:
|
|
57
|
+
price = prices.get("лагер")
|
|
58
|
+
return ExecutedCommandResponse(message=f"{price.rub if price else '?'} ₽", is_final=True)
|
|
59
|
+
|
|
60
|
+
@plugin.panel_page("beer", title="Пиво", icon="🍺") # страница в веб-панели
|
|
61
|
+
async def beer_page(panel: PanelContext) -> PanelPage:
|
|
62
|
+
return PanelPage(blocks=[Text(f"Сортов: {len(prices.all())}"), Button(action="reset", label="Сбросить")])
|
|
63
|
+
|
|
64
|
+
@plugin.panel_action("reset")
|
|
65
|
+
async def reset(panel: PanelContext, values: dict) -> str:
|
|
66
|
+
prices.replace_all([])
|
|
67
|
+
return "Цены сброшены"
|
|
68
|
+
|
|
69
|
+
return plugin
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Запуск: хост бота ставит и запускает плагин сам (zip через панель). Для разработки —
|
|
73
|
+
`python -m potehinsonnet.run .` из папки плагина (нужен NATS на `localhost:4222`).
|
|
74
|
+
|
|
75
|
+
## Что внутри
|
|
76
|
+
|
|
77
|
+
| Модуль | Для чего |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `Plugin`, `PluginContext` | плагин, его настройки (`ctx.settings`), папка данных, адрес NATS — всё от хоста |
|
|
80
|
+
| `@plugin.command`, `@plugin.button` | слэш-команды и кнопки Discord; ответ — один или поток кадров (анимация) |
|
|
81
|
+
| `plugin.discord` | отправить, изменить, удалить сообщение; голосовые каналы |
|
|
82
|
+
| `@plugin.panel_page`, `panel_action` | страницы веб-панели из блоков (`net_models.panel_ui`): текст, таблицы, формы, кнопки, разделы, загрузка файлов |
|
|
83
|
+
| `ctx.data` (`storage`) | данные плагина в JSON: `collection`, `document`, `file` — проверка моделью pydantic, атомарная запись, битые файлы откладываются, а не затираются |
|
|
84
|
+
| `plugin.files` (`files`) | большие файлы через NATS Object Store: загрузка из панели и выдача на скачивание |
|
|
85
|
+
| `python -m potehinsonnet.pack` | собрать zip плагина для установки через панель (`--bump patch`, `--no-data`) |
|
|
86
|
+
| `potehinsonnet.testing` | `FakeNats` — NATS в памяти для тестов плагина |
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Что хост даёт плагину при запуске: папку данных, настройки, адрес NATS, токен.
|
|
2
|
+
|
|
3
|
+
Хост передаёт всё переменными окружения. Без хоста (разработка) работают значения по умолчанию:
|
|
4
|
+
данные — ./data рядом с плагином, настройки — ./settings.json, NATS — localhost.
|
|
5
|
+
|
|
6
|
+
PLUGIN_DATA_DIR папка данных: переживает обновления и откаты плагина
|
|
7
|
+
PLUGIN_SETTINGS_FILE JSON с настройками, которые владелец задал в панели
|
|
8
|
+
PLUGIN_TOKEN токен плагина: им плагин представляется боту
|
|
9
|
+
NATS_URL адрес NATS
|
|
10
|
+
"""
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from functools import cached_property
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from potehinsonnet.manifest import ManifestError, PluginManifest, load_manifest
|
|
19
|
+
from potehinsonnet.storage import DataDir
|
|
20
|
+
|
|
21
|
+
DEFAULT_NATS_URL = "nats://localhost:4222"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class PluginContext:
|
|
26
|
+
root: Path # корень плагина (там plugin.toml)
|
|
27
|
+
manifest: PluginManifest
|
|
28
|
+
data_dir: Path
|
|
29
|
+
settings: dict[str, Any] = field(default_factory=dict)
|
|
30
|
+
nats_url: str = DEFAULT_NATS_URL
|
|
31
|
+
token: str = ""
|
|
32
|
+
|
|
33
|
+
@cached_property
|
|
34
|
+
def data(self) -> DataDir:
|
|
35
|
+
"""Файлы данных плагина: ctx.data.collection("pets.json", Pet, key="pet_id"), ctx.data.document(...)."""
|
|
36
|
+
return DataDir(self.data_dir)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def assets_dir(self) -> Path:
|
|
40
|
+
"""Файлы, которые едут вместе с кодом (стандартные картинки, звуки) — только для чтения."""
|
|
41
|
+
return self.root / "assets"
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def load(cls, root: str | Path, env: dict[str, str] | None = None) -> "PluginContext":
|
|
45
|
+
"""Собрать контекст: манифест из root, остальное — из окружения (env) или значения для разработки."""
|
|
46
|
+
env = os.environ if env is None else env
|
|
47
|
+
root = Path(root).resolve()
|
|
48
|
+
manifest = load_manifest(root)
|
|
49
|
+
data_dir = Path(env.get("PLUGIN_DATA_DIR") or root / "data")
|
|
50
|
+
data_dir.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
settings_file = Path(env.get("PLUGIN_SETTINGS_FILE") or root / "settings.json")
|
|
52
|
+
return cls(
|
|
53
|
+
root=root, manifest=manifest, data_dir=data_dir,
|
|
54
|
+
settings=read_settings(manifest, settings_file),
|
|
55
|
+
nats_url=env.get("NATS_URL") or DEFAULT_NATS_URL,
|
|
56
|
+
token=env.get("PLUGIN_TOKEN", ""),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def read_settings(manifest: PluginManifest, path: Path) -> dict[str, Any]:
|
|
61
|
+
"""Настройки из файла поверх значений по умолчанию из манифеста. Обязательной нет — ManifestError."""
|
|
62
|
+
saved: dict[str, Any] = {}
|
|
63
|
+
if path.is_file():
|
|
64
|
+
try:
|
|
65
|
+
saved = json.loads(path.read_text(encoding="utf-8"))
|
|
66
|
+
except json.JSONDecodeError as e:
|
|
67
|
+
raise ManifestError(f"{path}: ошибка в JSON — {e}") from e
|
|
68
|
+
settings = {}
|
|
69
|
+
for key, spec in manifest.settings.items():
|
|
70
|
+
value = saved.get(key, spec.default)
|
|
71
|
+
if value in (None, "") and spec.required:
|
|
72
|
+
raise ManifestError(f"{manifest.name}: не задана обязательная настройка «{spec.label}» ({key})")
|
|
73
|
+
settings[key] = value
|
|
74
|
+
return settings
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from potehinsonnet.net import NatsClient
|
|
2
|
+
from potehinsonnet.net_models.discord_models import NatsMessage, DiscordMessageResponse, DiscordMessageRemove, \
|
|
3
|
+
DiscordMessageEdit
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class DiscordProvider:
|
|
7
|
+
def __init__(self,nats_client:NatsClient):
|
|
8
|
+
self.nats_client = nats_client
|
|
9
|
+
|
|
10
|
+
async def send_message(self, message: NatsMessage)->DiscordMessageResponse:
|
|
11
|
+
response = await self.nats_client.request("discord.message.send", message.model_dump(mode="json"))
|
|
12
|
+
return DiscordMessageResponse.model_validate(response)
|
|
13
|
+
|
|
14
|
+
async def remove_message(self,channel_id:int,message_id:int):
|
|
15
|
+
await self.nats_client.publish("discord.message.remove", DiscordMessageRemove(
|
|
16
|
+
channel_id=channel_id,
|
|
17
|
+
message_id=message_id
|
|
18
|
+
).model_dump(mode="json"))
|
|
19
|
+
|
|
20
|
+
async def update_message(self, message: DiscordMessageEdit) -> DiscordMessageResponse:
|
|
21
|
+
response = await self.nats_client.request("discord.message.edit", message.model_dump(mode="json"))
|
|
22
|
+
return DiscordMessageResponse.model_validate(response)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Большие файлы через NATS Object Store (JetStream): zip с плагином, звуки, архивы — любого размера.
|
|
2
|
+
|
|
3
|
+
Обычное сообщение NATS — до 1 МБ, поэтому большой файл не передают в теле запроса, а кладут
|
|
4
|
+
в хранилище и передают ссылку (FileRef). Хранилище само режет файл на куски и собирает обратно.
|
|
5
|
+
|
|
6
|
+
ref = await files.put(open("plugin.zip", "rb"), "plugin.zip") # панель
|
|
7
|
+
await files.save(ref, Path("/tmp/plugin.zip")) # плагин или бот
|
|
8
|
+
|
|
9
|
+
Загрузки из панели лежат в ведре panel-uploads и сами удаляются через час: кто забрал — тот забрал.
|
|
10
|
+
На сервере NATS должен быть запущен с JetStream (`nats-server -js`).
|
|
11
|
+
"""
|
|
12
|
+
import io
|
|
13
|
+
import uuid
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import BinaryIO
|
|
16
|
+
|
|
17
|
+
from nats.js.api import ObjectStoreConfig, StorageType
|
|
18
|
+
from nats.js.errors import BucketNotFoundError, NotFoundError, ObjectNotFoundError
|
|
19
|
+
|
|
20
|
+
from potehinsonnet.net import NatsClient
|
|
21
|
+
from potehinsonnet.net_models.panel_ui import FileRef
|
|
22
|
+
|
|
23
|
+
UPLOADS_BUCKET = "panel-uploads"
|
|
24
|
+
UPLOADS_TTL = 3600.0 # секунд: забытые загрузки не копятся на диске
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class FileStore:
|
|
28
|
+
|
|
29
|
+
def __init__(self, nats: NatsClient, bucket: str = UPLOADS_BUCKET, ttl: float | None = UPLOADS_TTL):
|
|
30
|
+
self.nats = nats
|
|
31
|
+
self.bucket = bucket
|
|
32
|
+
self.ttl = ttl
|
|
33
|
+
self._store = None
|
|
34
|
+
|
|
35
|
+
async def _get_store(self, bucket: str | None = None):
|
|
36
|
+
bucket = bucket or self.bucket
|
|
37
|
+
if bucket == self.bucket and self._store is not None:
|
|
38
|
+
return self._store
|
|
39
|
+
js = self.nats._client.jetstream()
|
|
40
|
+
try:
|
|
41
|
+
store = await js.object_store(bucket)
|
|
42
|
+
except (BucketNotFoundError, NotFoundError):
|
|
43
|
+
if bucket != self.bucket:
|
|
44
|
+
raise FileNotFoundError(f"Нет хранилища {bucket}")
|
|
45
|
+
config = ObjectStoreConfig(bucket=bucket, ttl=self.ttl, storage=StorageType.FILE)
|
|
46
|
+
store = await js.create_object_store(bucket, config=config)
|
|
47
|
+
if bucket == self.bucket:
|
|
48
|
+
self._store = store
|
|
49
|
+
return store
|
|
50
|
+
|
|
51
|
+
async def put(self, source: bytes | BinaryIO, filename: str) -> FileRef:
|
|
52
|
+
"""Положить файл (байты или открытый файл — читается кусками, целиком в память не грузится)."""
|
|
53
|
+
store = await self._get_store()
|
|
54
|
+
data = io.BytesIO(source) if isinstance(source, bytes) else source
|
|
55
|
+
name = uuid.uuid4().hex
|
|
56
|
+
info = await store.put(name, data)
|
|
57
|
+
return FileRef(bucket=self.bucket, name=name, filename=Path(filename).name or name, size=info.size)
|
|
58
|
+
|
|
59
|
+
async def read(self, ref: FileRef) -> bytes:
|
|
60
|
+
"""Весь файл в память — для небольших. Большие лучше save()."""
|
|
61
|
+
store = await self._get_store(ref.bucket)
|
|
62
|
+
try:
|
|
63
|
+
return (await store.get(ref.name)).data
|
|
64
|
+
except ObjectNotFoundError:
|
|
65
|
+
raise FileNotFoundError(f"Файл {ref.filename} не найден — загрузка устарела, загрузите ещё раз")
|
|
66
|
+
|
|
67
|
+
async def save(self, ref: FileRef, path: Path) -> Path:
|
|
68
|
+
"""Сохранить файл на диск потоком."""
|
|
69
|
+
store = await self._get_store(ref.bucket)
|
|
70
|
+
path = Path(path)
|
|
71
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
try:
|
|
73
|
+
with path.open("wb") as out:
|
|
74
|
+
await store.get(ref.name, writeinto=out)
|
|
75
|
+
except ObjectNotFoundError:
|
|
76
|
+
path.unlink(missing_ok=True)
|
|
77
|
+
raise FileNotFoundError(f"Файл {ref.filename} не найден — загрузка устарела, загрузите ещё раз")
|
|
78
|
+
return path
|
|
79
|
+
|
|
80
|
+
async def delete(self, ref: FileRef) -> None:
|
|
81
|
+
store = await self._get_store(ref.bucket)
|
|
82
|
+
try:
|
|
83
|
+
await store.delete(ref.name)
|
|
84
|
+
except ObjectNotFoundError:
|
|
85
|
+
pass
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Манифест плагина — plugin.toml в корне плагина. Единственное место, где записаны имя, версия и права.
|
|
2
|
+
|
|
3
|
+
[plugin]
|
|
4
|
+
name = "potehinson_tamagochi" # id: латиница, цифры, _
|
|
5
|
+
label = "Potehinson Tamagochi"
|
|
6
|
+
description = "Вырасти своего потешку"
|
|
7
|
+
version = "0.4.2"
|
|
8
|
+
author = "Uto4ka404"
|
|
9
|
+
icon = "icon.png" # путь от корня плагина, необязательно
|
|
10
|
+
|
|
11
|
+
[runtime]
|
|
12
|
+
entry = "potehinson_tamagochi.main:create_plugin" # модуль:функция, получает PluginContext
|
|
13
|
+
python = ">=3.14"
|
|
14
|
+
potehinsonnet = ">=0.10,<0.11"
|
|
15
|
+
|
|
16
|
+
[permissions] # что плагин просит у бота; владелец подтверждает при установке
|
|
17
|
+
discord = ["send_message", "edit_message", "members"]
|
|
18
|
+
commands = true
|
|
19
|
+
panel = true
|
|
20
|
+
|
|
21
|
+
[settings.api_key] # что владелец заполняет в панели при установке
|
|
22
|
+
label = "Ключ API"
|
|
23
|
+
secret = true
|
|
24
|
+
"""
|
|
25
|
+
import re
|
|
26
|
+
import sys
|
|
27
|
+
import tomllib
|
|
28
|
+
from importlib.metadata import PackageNotFoundError, version as installed_version
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Literal
|
|
31
|
+
|
|
32
|
+
from pydantic import BaseModel, Field, field_validator
|
|
33
|
+
|
|
34
|
+
from potehinsonnet.net_models.system_models import Service
|
|
35
|
+
|
|
36
|
+
MANIFEST_FILE = "plugin.toml"
|
|
37
|
+
NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]{1,63}$")
|
|
38
|
+
|
|
39
|
+
# Что плагин может попросить у бота. Бот проверяет это на каждом запросе
|
|
40
|
+
DISCORD_PERMISSIONS = {
|
|
41
|
+
"send_message", # писать в каналы
|
|
42
|
+
"edit_message", # править и удалять свои сообщения
|
|
43
|
+
"members", # видеть участников сервера
|
|
44
|
+
"roles", # видеть роли
|
|
45
|
+
"channels", # видеть каналы
|
|
46
|
+
"voice", # голосовые каналы: подключаться, играть звук
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ManifestError(ValueError):
|
|
51
|
+
"""plugin.toml не найден или заполнен неправильно."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class PluginInfo(BaseModel):
|
|
55
|
+
name: str
|
|
56
|
+
label: str
|
|
57
|
+
description: str = ""
|
|
58
|
+
version: str
|
|
59
|
+
author: str = ""
|
|
60
|
+
icon: str = ""
|
|
61
|
+
site: str = ""
|
|
62
|
+
|
|
63
|
+
@field_validator("name")
|
|
64
|
+
@classmethod
|
|
65
|
+
def _name(cls, value: str) -> str:
|
|
66
|
+
if not NAME_PATTERN.match(value):
|
|
67
|
+
raise ValueError("name — латиница в нижнем регистре, цифры и _, начинается с буквы, до 64 символов")
|
|
68
|
+
return value
|
|
69
|
+
|
|
70
|
+
@field_validator("version")
|
|
71
|
+
@classmethod
|
|
72
|
+
def _version(cls, value: str) -> str:
|
|
73
|
+
if not re.fullmatch(r"\d+(\.\d+){0,2}([-+.].*)?", value):
|
|
74
|
+
raise ValueError("version — как 1.2.3")
|
|
75
|
+
return value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Runtime(BaseModel):
|
|
79
|
+
entry: str # «пакет.модуль:функция»
|
|
80
|
+
python: str = "" # «>=3.14»
|
|
81
|
+
potehinsonnet: str = "" # «>=0.10,<0.11»
|
|
82
|
+
|
|
83
|
+
@field_validator("entry")
|
|
84
|
+
@classmethod
|
|
85
|
+
def _entry(cls, value: str) -> str:
|
|
86
|
+
module, _, func = value.partition(":")
|
|
87
|
+
if not module or not func or not all(part.isidentifier() for part in [*module.split("."), func]):
|
|
88
|
+
raise ValueError("entry — «пакет.модуль:функция», например my_plugin.main:create_plugin")
|
|
89
|
+
if "." not in module:
|
|
90
|
+
raise ValueError("код плагина — пакетом: entry = «my_plugin.main:create_plugin», а не «main:…»")
|
|
91
|
+
return value
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class Permissions(BaseModel):
|
|
95
|
+
discord: list[str] = Field(default_factory=list)
|
|
96
|
+
commands: bool = False # регистрировать слэш-команды
|
|
97
|
+
panel: bool = False # свои страницы в веб-панели
|
|
98
|
+
|
|
99
|
+
@field_validator("discord")
|
|
100
|
+
@classmethod
|
|
101
|
+
def _discord(cls, value: list[str]) -> list[str]:
|
|
102
|
+
unknown = sorted(set(value) - DISCORD_PERMISSIONS)
|
|
103
|
+
if unknown:
|
|
104
|
+
raise ValueError(f"неизвестные права: {', '.join(unknown)}; есть: {', '.join(sorted(DISCORD_PERMISSIONS))}")
|
|
105
|
+
return sorted(set(value))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class SettingSpec(BaseModel):
|
|
109
|
+
"""Одна настройка, которую владелец задаёт в панели при установке."""
|
|
110
|
+
label: str
|
|
111
|
+
description: str = ""
|
|
112
|
+
type: Literal["text", "number", "bool"] = "text"
|
|
113
|
+
secret: bool = False # ключи и токены: в панели не показываются после сохранения
|
|
114
|
+
required: bool = False
|
|
115
|
+
default: str | float | bool | None = None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class PluginManifest(BaseModel):
|
|
119
|
+
plugin: PluginInfo
|
|
120
|
+
runtime: Runtime
|
|
121
|
+
permissions: Permissions = Field(default_factory=Permissions)
|
|
122
|
+
settings: dict[str, SettingSpec] = Field(default_factory=dict)
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def name(self) -> str:
|
|
126
|
+
return self.plugin.name
|
|
127
|
+
|
|
128
|
+
def service(self) -> Service:
|
|
129
|
+
"""Описание для бота и панели — то, что раньше писали в коде как Service(...)."""
|
|
130
|
+
info = self.plugin
|
|
131
|
+
return Service(type="plugin", name=info.name, label=info.label, description=info.description,
|
|
132
|
+
author=info.author, version=info.version, icon=info.icon, site=info.site)
|
|
133
|
+
|
|
134
|
+
def check_compatible(self) -> None:
|
|
135
|
+
"""Подходит ли плагину этот Python и эта версия potehinsonnet. Нет — ManifestError."""
|
|
136
|
+
python = ".".join(map(str, sys.version_info[:3]))
|
|
137
|
+
if self.runtime.python and not version_matches(python, self.runtime.python):
|
|
138
|
+
raise ManifestError(f"{self.name}: нужен Python {self.runtime.python}, а запущен {python}")
|
|
139
|
+
if self.runtime.potehinsonnet:
|
|
140
|
+
try:
|
|
141
|
+
library = installed_version("potehinsonnet")
|
|
142
|
+
except PackageNotFoundError:
|
|
143
|
+
return # запуск из исходников библиотеки — версию не проверить
|
|
144
|
+
if not version_matches(library, self.runtime.potehinsonnet):
|
|
145
|
+
raise ManifestError(
|
|
146
|
+
f"{self.name}: нужна potehinsonnet {self.runtime.potehinsonnet}, а стоит {library}")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def load_manifest(root: str | Path) -> PluginManifest:
|
|
150
|
+
"""Прочитать plugin.toml из корня плагина."""
|
|
151
|
+
path = Path(root) / MANIFEST_FILE
|
|
152
|
+
if not path.is_file():
|
|
153
|
+
raise ManifestError(f"Нет {MANIFEST_FILE} в {Path(root).resolve()}")
|
|
154
|
+
try:
|
|
155
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
156
|
+
except tomllib.TOMLDecodeError as e:
|
|
157
|
+
raise ManifestError(f"{path}: ошибка в TOML — {e}") from e
|
|
158
|
+
try:
|
|
159
|
+
return PluginManifest.model_validate(data)
|
|
160
|
+
except ValueError as e:
|
|
161
|
+
raise ManifestError(f"{path}: {e}") from e
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ----------------------------------------------------------------------
|
|
165
|
+
# Версии: «>=0.10,<0.11» — без лишних зависимостей
|
|
166
|
+
# ----------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
def _parse(value: str) -> tuple[int, ...]:
|
|
169
|
+
numbers = re.match(r"\d+(\.\d+)*", value.strip())
|
|
170
|
+
if not numbers:
|
|
171
|
+
raise ManifestError(f"Не понимаю версию «{value}»")
|
|
172
|
+
return tuple(int(n) for n in numbers.group(0).split("."))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _compare(a: tuple[int, ...], b: tuple[int, ...]) -> int:
|
|
176
|
+
width = max(len(a), len(b))
|
|
177
|
+
a, b = a + (0,) * (width - len(a)), b + (0,) * (width - len(b))
|
|
178
|
+
return (a > b) - (a < b)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def version_matches(version: str, spec: str) -> bool:
|
|
182
|
+
"""Подходит ли версия под условия через запятую: >=, <=, >, <, ==, !=."""
|
|
183
|
+
current = _parse(version)
|
|
184
|
+
checks = {">=": lambda c: c >= 0, "<=": lambda c: c <= 0, "==": lambda c: c == 0,
|
|
185
|
+
"!=": lambda c: c != 0, ">": lambda c: c > 0, "<": lambda c: c < 0}
|
|
186
|
+
for part in filter(None, (p.strip() for p in spec.split(","))):
|
|
187
|
+
operator = next((op for op in (">=", "<=", "==", "!=", ">", "<") if part.startswith(op)), "==")
|
|
188
|
+
target = part.removeprefix(operator) if part.startswith(operator) else part
|
|
189
|
+
if not checks[operator](_compare(current, _parse(target))):
|
|
190
|
+
return False
|
|
191
|
+
return True
|
|
File without changes
|