mbtk 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.
- mbtk-0.1.0/.editorconfig +15 -0
- mbtk-0.1.0/.github/workflows/ci.yml +45 -0
- mbtk-0.1.0/.github/workflows/release.yml +50 -0
- mbtk-0.1.0/.gitignore +22 -0
- mbtk-0.1.0/CHANGELOG.md +24 -0
- mbtk-0.1.0/CONTRIBUTING.md +41 -0
- mbtk-0.1.0/LICENSE +21 -0
- mbtk-0.1.0/PKG-INFO +190 -0
- mbtk-0.1.0/README.en.md +155 -0
- mbtk-0.1.0/README.md +157 -0
- mbtk-0.1.0/SECURITY.md +22 -0
- mbtk-0.1.0/examples/echo_bot/README.md +34 -0
- mbtk-0.1.0/examples/echo_bot/main.py +65 -0
- mbtk-0.1.0/pyproject.toml +74 -0
- mbtk-0.1.0/src/mbtk/__init__.py +39 -0
- mbtk-0.1.0/src/mbtk/bot.py +38 -0
- mbtk-0.1.0/src/mbtk/clock.py +15 -0
- mbtk-0.1.0/src/mbtk/di.py +28 -0
- mbtk-0.1.0/src/mbtk/dispatcher.py +168 -0
- mbtk-0.1.0/src/mbtk/errors.py +35 -0
- mbtk-0.1.0/src/mbtk/events.py +82 -0
- mbtk-0.1.0/src/mbtk/filters.py +210 -0
- mbtk-0.1.0/src/mbtk/fsm.py +160 -0
- mbtk-0.1.0/src/mbtk/max/__init__.py +21 -0
- mbtk-0.1.0/src/mbtk/max/client.py +266 -0
- mbtk-0.1.0/src/mbtk/max/keyboards.py +34 -0
- mbtk-0.1.0/src/mbtk/max/updates.py +149 -0
- mbtk-0.1.0/src/mbtk/middleware.py +6 -0
- mbtk-0.1.0/src/mbtk/py.typed +0 -0
- mbtk-0.1.0/src/mbtk/router.py +79 -0
- mbtk-0.1.0/src/mbtk/storage/__init__.py +1 -0
- mbtk-0.1.0/src/mbtk/storage/redis.py +139 -0
- mbtk-0.1.0/tests/test_framework.py +370 -0
- mbtk-0.1.0/tests/test_keyboards.py +43 -0
- mbtk-0.1.0/tests/test_max_client.py +170 -0
- mbtk-0.1.0/tests/test_redis_fsm.py +111 -0
- mbtk-0.1.0/uv.lock +981 -0
mbtk-0.1.0/.editorconfig
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
test:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
strategy:
|
|
15
|
+
fail-fast: false
|
|
16
|
+
matrix:
|
|
17
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@v4
|
|
20
|
+
- uses: astral-sh/setup-uv@v5
|
|
21
|
+
with:
|
|
22
|
+
enable-cache: true
|
|
23
|
+
- name: Install dependencies
|
|
24
|
+
run: uv sync --all-extras --python ${{ matrix.python-version }}
|
|
25
|
+
- name: Lint
|
|
26
|
+
run: uv run ruff check .
|
|
27
|
+
- name: Check formatting
|
|
28
|
+
run: uv run ruff format --check .
|
|
29
|
+
- name: Test
|
|
30
|
+
run: uv run pytest -q
|
|
31
|
+
|
|
32
|
+
build:
|
|
33
|
+
runs-on: ubuntu-latest
|
|
34
|
+
needs: test
|
|
35
|
+
steps:
|
|
36
|
+
- uses: actions/checkout@v4
|
|
37
|
+
- uses: astral-sh/setup-uv@v5
|
|
38
|
+
- name: Build
|
|
39
|
+
run: uv build
|
|
40
|
+
- name: Check metadata
|
|
41
|
+
run: uvx twine check dist/*
|
|
42
|
+
- uses: actions/upload-artifact@v4
|
|
43
|
+
with:
|
|
44
|
+
name: dist
|
|
45
|
+
path: dist/
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*"
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
build:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: astral-sh/setup-uv@v5
|
|
17
|
+
- name: Build
|
|
18
|
+
run: uv build
|
|
19
|
+
- name: Check metadata
|
|
20
|
+
run: uvx twine check dist/*
|
|
21
|
+
- uses: actions/upload-artifact@v4
|
|
22
|
+
with:
|
|
23
|
+
name: dist
|
|
24
|
+
path: dist/
|
|
25
|
+
|
|
26
|
+
publish:
|
|
27
|
+
runs-on: ubuntu-latest
|
|
28
|
+
needs: build
|
|
29
|
+
environment:
|
|
30
|
+
name: pypi
|
|
31
|
+
url: https://pypi.org/p/mbtk
|
|
32
|
+
permissions:
|
|
33
|
+
id-token: write
|
|
34
|
+
steps:
|
|
35
|
+
- uses: actions/download-artifact@v4
|
|
36
|
+
with:
|
|
37
|
+
name: dist
|
|
38
|
+
path: dist/
|
|
39
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
40
|
+
|
|
41
|
+
github-release:
|
|
42
|
+
runs-on: ubuntu-latest
|
|
43
|
+
needs: [build, publish]
|
|
44
|
+
permissions:
|
|
45
|
+
contents: write
|
|
46
|
+
steps:
|
|
47
|
+
- uses: actions/checkout@v4
|
|
48
|
+
- uses: softprops/action-gh-release@v2
|
|
49
|
+
with:
|
|
50
|
+
generate_release_notes: true
|
mbtk-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
.venv/
|
|
6
|
+
venv/
|
|
7
|
+
build/
|
|
8
|
+
dist/
|
|
9
|
+
.coverage
|
|
10
|
+
coverage.xml
|
|
11
|
+
htmlcov/
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
.ruff_cache/
|
|
14
|
+
.mypy_cache/
|
|
15
|
+
|
|
16
|
+
# Editors
|
|
17
|
+
.idea/
|
|
18
|
+
.vscode/
|
|
19
|
+
*.swp
|
|
20
|
+
|
|
21
|
+
# OS
|
|
22
|
+
.DS_Store
|
mbtk-0.1.0/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
5
|
+
and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.0] - 2026-11-10
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Core dispatcher, routers, observers, composable filters, middleware, and
|
|
14
|
+
dependency injection by argument name.
|
|
15
|
+
- Typed MAX events: messages, callback presses, and bot-started events.
|
|
16
|
+
- FSM: states, state groups, dialogue context, in-memory storage, and the
|
|
17
|
+
`FSMStorage` protocol.
|
|
18
|
+
- MAX update parsing, including double-encoded callback payloads.
|
|
19
|
+
- Optional `MaxApiClient` for the MAX Bot API (`mbtk[max]`).
|
|
20
|
+
- Optional `RedisFSMStorage` with atomic one-shot claims (`mbtk[redis]`).
|
|
21
|
+
- MAX keyboard and attachment builders.
|
|
22
|
+
|
|
23
|
+
[Unreleased]: https://github.com/VladimirKrokhin/mbtk/compare/v0.1.0...HEAD
|
|
24
|
+
[0.1.0]: https://github.com/VladimirKrokhin/mbtk/releases/tag/v0.1.0
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Issues and pull requests are welcome.
|
|
4
|
+
|
|
5
|
+
## Local setup
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
uv sync --all-extras
|
|
9
|
+
uv run pytest
|
|
10
|
+
uv run ruff check .
|
|
11
|
+
uv run ruff format --check .
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The `httpx` dependency is enough to run the client tests; the Redis tests use
|
|
15
|
+
an in-memory fake and do not need a running Redis server.
|
|
16
|
+
|
|
17
|
+
## Guidelines
|
|
18
|
+
|
|
19
|
+
- Keep the core free of runtime dependencies. Anything that needs a library
|
|
20
|
+
belongs in an extra.
|
|
21
|
+
- Add a test for every behavior change.
|
|
22
|
+
- Keep public names and docstrings in English.
|
|
23
|
+
- Use Conventional Commits, for example `feat: add TextRegexp filter`.
|
|
24
|
+
- Update `CHANGELOG.md` under `[Unreleased]` for user-visible changes.
|
|
25
|
+
|
|
26
|
+
## Pull requests
|
|
27
|
+
|
|
28
|
+
1. Fork the repository and create a branch.
|
|
29
|
+
2. Make the change and run the checks above.
|
|
30
|
+
3. Open a pull request with a short description and the motivation.
|
|
31
|
+
4. Wait for CI to pass.
|
|
32
|
+
|
|
33
|
+
## Release
|
|
34
|
+
|
|
35
|
+
Releases are cut from `main`:
|
|
36
|
+
|
|
37
|
+
1. Bump `version` in `pyproject.toml`.
|
|
38
|
+
2. Move the `[Unreleased]` section in `CHANGELOG.md` to the new version.
|
|
39
|
+
3. Commit, tag `vX.Y.Z`, and push the tag.
|
|
40
|
+
4. The `Release` workflow builds the package and publishes it to PyPI via
|
|
41
|
+
Trusted Publishing.
|
mbtk-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vladimir Krokhin
|
|
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.
|
mbtk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mbtk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A small async toolkit for MAX messenger bots, inspired by aiogram 3
|
|
5
|
+
Project-URL: Homepage, https://github.com/VladimirKrokhin/mbtk
|
|
6
|
+
Project-URL: Repository, https://github.com/VladimirKrokhin/mbtk
|
|
7
|
+
Project-URL: Issues, https://github.com/VladimirKrokhin/mbtk/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/VladimirKrokhin/mbtk/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Vladimir Krokhin <krokhinvladimir2004@gmail.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: aiogram,asyncio,bot,framework,max,messenger
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Provides-Extra: all
|
|
26
|
+
Requires-Dist: httpx<1,>=0.28; extra == 'all'
|
|
27
|
+
Requires-Dist: redis<7,>=5; extra == 'all'
|
|
28
|
+
Provides-Extra: max
|
|
29
|
+
Requires-Dist: httpx<1,>=0.28; extra == 'max'
|
|
30
|
+
Provides-Extra: redis
|
|
31
|
+
Requires-Dist: redis<7,>=5; extra == 'redis'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# mbtk — MAX Bot Toolkit
|
|
35
|
+
|
|
36
|
+
[](https://github.com/VladimirKrokhin/mbtk/actions/workflows/ci.yml)
|
|
37
|
+
[](https://pypi.org/project/mbtk/)
|
|
38
|
+
[](LICENSE)
|
|
39
|
+
|
|
40
|
+
Небольшой асинхронный тулкит для ботов в мессенджере **MAX**. Вдохновлён
|
|
41
|
+
[aiogram 3](https://github.com/aiogram/aiogram): типизированные события,
|
|
42
|
+
роутеры, композируемые фильтры, middleware, внедрение зависимостей по именам
|
|
43
|
+
аргументов и FSM.
|
|
44
|
+
|
|
45
|
+
Ядро не имеет runtime-зависимостей. HTTP-клиент MAX и Redis-хранилище FSM
|
|
46
|
+
подключаются как extras.
|
|
47
|
+
|
|
48
|
+
> Проект неофициальный и не связан с VK или командой MAX.
|
|
49
|
+
|
|
50
|
+
[English version](README.en.md)
|
|
51
|
+
|
|
52
|
+
## Возможности
|
|
53
|
+
|
|
54
|
+
- `Dispatcher.feed_update()` превращает raw update в типизированное событие.
|
|
55
|
+
- Роутеры-деревья: первый подходящий обработчик выигрывает, `SkipHandler`
|
|
56
|
+
передаёт событие следующему.
|
|
57
|
+
- Фильтры собираются через `&`, `|` и `~`: `Command`, `Payload`, `StateIs`,
|
|
58
|
+
`HasPhoto`, `TextRegexp` и другие.
|
|
59
|
+
- Middleware на уровне диспетчера, роутера и конкретного observer'а.
|
|
60
|
+
- DI: обработчик получает только те аргументы, которые объявил.
|
|
61
|
+
- FSM: `State`, `StatesGroup`, `FSMContext`, in-memory хранилище и контракт
|
|
62
|
+
`FSMStorage`.
|
|
63
|
+
- Атомарный `claim` для одноразовых действий (например, «фото обработано
|
|
64
|
+
один раз»).
|
|
65
|
+
- Обработчик всегда дожидается завершения: очередь может подтвердить событие
|
|
66
|
+
только после успеха.
|
|
67
|
+
|
|
68
|
+
## Установка
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
pip install mbtk # ядро
|
|
72
|
+
pip install "mbtk[max]" # + MaxApiClient
|
|
73
|
+
pip install "mbtk[redis]" # + RedisFSMStorage
|
|
74
|
+
pip install "mbtk[all]" # всё сразу
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Нужен Python 3.10+.
|
|
78
|
+
|
|
79
|
+
## Быстрый старт
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
import asyncio
|
|
83
|
+
|
|
84
|
+
from mbtk import Dispatcher, Router
|
|
85
|
+
from mbtk.filters import Command
|
|
86
|
+
|
|
87
|
+
router = Router("main")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@router.message(Command("start"))
|
|
91
|
+
async def start(event):
|
|
92
|
+
await event.answer("Привет! Отправь /echo <текст>.")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@router.message(Command("echo"))
|
|
96
|
+
async def echo(event):
|
|
97
|
+
await event.answer(event.arguments or "Нечего повторять")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
async def handle_update(bot, update):
|
|
101
|
+
dispatcher = Dispatcher(bot=bot)
|
|
102
|
+
dispatcher.include_router(router)
|
|
103
|
+
return await dispatcher.feed_update(update)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`update` — это JSON-тело вебхука MAX. `bot` — объект с методами из
|
|
107
|
+
`mbtk.bot.Bot`; в продакшене это `MaxApiClient`, в тестах — заглушка.
|
|
108
|
+
|
|
109
|
+
## Клиент MAX API
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
import os
|
|
113
|
+
|
|
114
|
+
from mbtk.max.client import MaxApiClient
|
|
115
|
+
|
|
116
|
+
bot = MaxApiClient(
|
|
117
|
+
"https://platform-api2.max.ru",
|
|
118
|
+
access_token=os.environ["MAX_ACCESS_TOKEN"],
|
|
119
|
+
ca_bundle=os.environ.get("MAX_CA_BUNDLE"), # None — системные CA
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
await bot.send_message(chat_id, "**Привет**")
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Клиент умеет отправлять и править сообщения, отвечать на callback и
|
|
126
|
+
скачивать изображения с проверкой хоста, схемы, размера и редиректов.
|
|
127
|
+
|
|
128
|
+
Строители клавиатур и вложений:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from mbtk.max.keyboards import button, keyboard, location_attachment
|
|
132
|
+
|
|
133
|
+
board = keyboard([[button("Меню", {"a": "menu"})]])
|
|
134
|
+
attachment = location_attachment(55.7558, 37.6173)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Redis FSM
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
import os
|
|
141
|
+
|
|
142
|
+
from redis import Redis
|
|
143
|
+
|
|
144
|
+
from mbtk import Dispatcher
|
|
145
|
+
from mbtk.storage.redis import RedisFSMStorage
|
|
146
|
+
|
|
147
|
+
storage = RedisFSMStorage(
|
|
148
|
+
Redis.from_url(os.environ["REDIS_URL"]),
|
|
149
|
+
prefix="myapp:fsm:",
|
|
150
|
+
ttl=24 * 3600,
|
|
151
|
+
)
|
|
152
|
+
dispatcher = Dispatcher(bot=bot, storage=storage)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Хранилище синхронное намеренно: это локальные вызовы Redis без блокирующих
|
|
156
|
+
чтений. Используйте `redis.Redis`, а не `redis.asyncio`.
|
|
157
|
+
|
|
158
|
+
Своё хранилище можно подключить, реализовав протокол `mbtk.fsm.FSMStorage`.
|
|
159
|
+
|
|
160
|
+
## Основные понятия
|
|
161
|
+
|
|
162
|
+
| Понятие | Модуль | Назначение |
|
|
163
|
+
| --- | --- | --- |
|
|
164
|
+
| `Dispatcher` | `mbtk` | Корневой роутер и точка входа `feed_update`. |
|
|
165
|
+
| `Router` | `mbtk` | Группа обработчиков и дочерних роутеров. |
|
|
166
|
+
| `Observer` | `mbtk.router` | `router.message`, `router.callback_query`, `router.bot_started`, `router.error`. |
|
|
167
|
+
| Фильтры | `mbtk.filters` | Условия выбора обработчика. |
|
|
168
|
+
| `BaseMiddleware` | `mbtk` | Обёртка вокруг обработчика. |
|
|
169
|
+
| `FSMContext` | `mbtk` | Состояние и данные диалога. |
|
|
170
|
+
| `MemoryStorage` | `mbtk` | Хранилище FSM в памяти для тестов. |
|
|
171
|
+
|
|
172
|
+
## Статус
|
|
173
|
+
|
|
174
|
+
Версия `0.1.x`: API может меняться до `1.0`. Ломающие изменения
|
|
175
|
+
фиксируются в [CHANGELOG](CHANGELOG.md).
|
|
176
|
+
|
|
177
|
+
## Разработка
|
|
178
|
+
|
|
179
|
+
```sh
|
|
180
|
+
uv sync --all-extras
|
|
181
|
+
uv run pytest
|
|
182
|
+
uv run ruff check .
|
|
183
|
+
uv run ruff format --check .
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Пример без сети — `examples/echo_bot/main.py`.
|
|
187
|
+
|
|
188
|
+
## Лицензия
|
|
189
|
+
|
|
190
|
+
MIT. См. [LICENSE](LICENSE).
|
mbtk-0.1.0/README.en.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# mbtk — MAX Bot Toolkit
|
|
2
|
+
|
|
3
|
+
[](https://github.com/VladimirKrokhin/mbtk/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/mbtk/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
A small async toolkit for bots in the **MAX** messenger. Inspired by
|
|
8
|
+
[aiogram 3](https://github.com/aiogram/aiogram): typed events, routers,
|
|
9
|
+
composable filters, middleware, dependency injection by argument name, and
|
|
10
|
+
finite state machines.
|
|
11
|
+
|
|
12
|
+
The core has no runtime dependencies. The MAX HTTP client and the Redis FSM
|
|
13
|
+
storage are available as extras.
|
|
14
|
+
|
|
15
|
+
> This project is unofficial and is not affiliated with VK or the MAX team.
|
|
16
|
+
|
|
17
|
+
[Русская версия](README.md)
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- `Dispatcher.feed_update()` turns a raw update into a typed event.
|
|
22
|
+
- Router trees: the first matching handler wins, and `SkipHandler` passes
|
|
23
|
+
the event to the next one.
|
|
24
|
+
- Filters compose with `&`, `|`, and `~`: `Command`, `Payload`, `StateIs`,
|
|
25
|
+
`HasPhoto`, `TextRegexp`, and more.
|
|
26
|
+
- Middleware at the dispatcher, router, and observer levels.
|
|
27
|
+
- DI: a handler receives only the arguments it declares.
|
|
28
|
+
- FSM: `State`, `StatesGroup`, `FSMContext`, an in-memory storage, and the
|
|
29
|
+
`FSMStorage` protocol.
|
|
30
|
+
- Atomic `claim` for one-shot actions (for example, "process this photo
|
|
31
|
+
once").
|
|
32
|
+
- Handlers are always awaited, so a queue can acknowledge an event only
|
|
33
|
+
after success.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install mbtk # core
|
|
39
|
+
pip install "mbtk[max]" # + MaxApiClient
|
|
40
|
+
pip install "mbtk[redis]" # + RedisFSMStorage
|
|
41
|
+
pip install "mbtk[all]" # everything
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Python 3.10+ is required.
|
|
45
|
+
|
|
46
|
+
## Quick start
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from mbtk import Dispatcher, Router
|
|
50
|
+
from mbtk.filters import Command
|
|
51
|
+
|
|
52
|
+
router = Router("main")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@router.message(Command("start"))
|
|
56
|
+
async def start(event):
|
|
57
|
+
await event.answer("Hello! Send /echo <text>.")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@router.message(Command("echo"))
|
|
61
|
+
async def echo(event):
|
|
62
|
+
await event.answer(event.arguments or "Nothing to echo")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def handle_update(bot, update):
|
|
66
|
+
dispatcher = Dispatcher(bot=bot)
|
|
67
|
+
dispatcher.include_router(router)
|
|
68
|
+
return await dispatcher.feed_update(update)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`update` is the JSON body of a MAX webhook. `bot` is any object that
|
|
72
|
+
implements `mbtk.bot.Bot`: `MaxApiClient` in production, a fake in tests.
|
|
73
|
+
|
|
74
|
+
## MAX API client
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import os
|
|
78
|
+
|
|
79
|
+
from mbtk.max.client import MaxApiClient
|
|
80
|
+
|
|
81
|
+
bot = MaxApiClient(
|
|
82
|
+
"https://platform-api2.max.ru",
|
|
83
|
+
access_token=os.environ["MAX_ACCESS_TOKEN"],
|
|
84
|
+
ca_bundle=os.environ.get("MAX_CA_BUNDLE"), # None uses system CAs
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
await bot.send_message(chat_id, "**Hello**")
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The client can send and edit messages, answer callbacks, and download images
|
|
91
|
+
with host, scheme, size, and redirect checks.
|
|
92
|
+
|
|
93
|
+
Keyboard and attachment builders:
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from mbtk.max.keyboards import button, keyboard, location_attachment
|
|
97
|
+
|
|
98
|
+
board = keyboard([[button("Menu", {"a": "menu"})]])
|
|
99
|
+
attachment = location_attachment(55.7558, 37.6173)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Redis FSM
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
import os
|
|
106
|
+
|
|
107
|
+
from redis import Redis
|
|
108
|
+
|
|
109
|
+
from mbtk import Dispatcher
|
|
110
|
+
from mbtk.storage.redis import RedisFSMStorage
|
|
111
|
+
|
|
112
|
+
storage = RedisFSMStorage(
|
|
113
|
+
Redis.from_url(os.environ["REDIS_URL"]),
|
|
114
|
+
prefix="myapp:fsm:",
|
|
115
|
+
ttl=24 * 3600,
|
|
116
|
+
)
|
|
117
|
+
dispatcher = Dispatcher(bot=bot, storage=storage)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The storage is synchronous on purpose: these are local Redis calls without
|
|
121
|
+
blocking reads. Use `redis.Redis`, not `redis.asyncio`.
|
|
122
|
+
|
|
123
|
+
To plug in another backend, implement the `mbtk.fsm.FSMStorage` protocol.
|
|
124
|
+
|
|
125
|
+
## Concepts
|
|
126
|
+
|
|
127
|
+
| Concept | Module | Purpose |
|
|
128
|
+
| --- | --- | --- |
|
|
129
|
+
| `Dispatcher` | `mbtk` | Root router and the `feed_update` entry point. |
|
|
130
|
+
| `Router` | `mbtk` | A group of handlers and child routers. |
|
|
131
|
+
| `Observer` | `mbtk.router` | `router.message`, `router.callback_query`, `router.bot_started`, `router.error`. |
|
|
132
|
+
| Filters | `mbtk.filters` | Conditions that select a handler. |
|
|
133
|
+
| `BaseMiddleware` | `mbtk` | A wrapper around a handler. |
|
|
134
|
+
| `FSMContext` | `mbtk` | Dialogue state and data. |
|
|
135
|
+
| `MemoryStorage` | `mbtk` | In-memory FSM storage for tests. |
|
|
136
|
+
|
|
137
|
+
## Status
|
|
138
|
+
|
|
139
|
+
Version `0.1.x`: the API may change before `1.0`. Breaking changes are
|
|
140
|
+
listed in [CHANGELOG](CHANGELOG.md).
|
|
141
|
+
|
|
142
|
+
## Development
|
|
143
|
+
|
|
144
|
+
```sh
|
|
145
|
+
uv sync --all-extras
|
|
146
|
+
uv run pytest
|
|
147
|
+
uv run ruff check .
|
|
148
|
+
uv run ruff format --check .
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
A network-free example lives in `examples/echo_bot/main.py`.
|
|
152
|
+
|
|
153
|
+
## License
|
|
154
|
+
|
|
155
|
+
MIT. See [LICENSE](LICENSE).
|