Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Maxo
https://github.com/k1rl3s/maxo
Admin
Maxo is an asynchronous framework for developing bots for max.ru.
Tokens:
46,710
Snippets:
538
Trust Score:
8.9
License:
Apache-2.0
Update:
2 months ago
Context
Chat
Benchmark
71
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Create a start link with encoded payload Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Example of creating a start link with encode=True to allow payloads with characters outside the allowed set. Requires bot.state.info.username (bot must be started). ```python from maxo.utils import deeplink link = deeplink.create_start_link(bot, "promo_code", encode=True) ``` -------------------------------- ### Complete dialog setup example with setup_dialogs Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialogs.md Shows a full minimal dialog: define a `StatesGroup`, build a `Dialog` with a `Window` containing a `Const` widget, create a bot and dispatcher with `DefaultKeyBuilder(with_destiny=True)`, start the dialog on `/start`, include the dialog, call `setup_dialogs(dp)`, and run polling. The comment notes that dialogs require a key builder with destiny. ```python from maxo import Bot, Dispatcher from maxo.dialogs import Dialog, Window, setup_dialogs from maxo.dialogs.widgets.text import Const from maxo.dialogs.widgets.kbd import Button from maxo.fsm import State, StatesGroup from maxo.fsm.key_builder import DefaultKeyBuilder from maxo.routing.filters import CommandStart class Main(StatesGroup): root = State() dialog = Dialog( Window( Const("Главное меню"), state=Main.root, ), ) bot = Bot("TOKEN") # диалогам нужен key builder с destiny: dp = Dispatcher(key_builder=DefaultKeyBuilder(with_destiny=True)) @dp.message_created(CommandStart()) async def start(message, dialog_manager: DialogManager) -> None: await dialog_manager.start(Main.root) dp.include(dialog) setup_dialogs(dp) dp.run_polling(bot) ``` -------------------------------- ### Bot usage example Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/bot.md Shows typical async context manager usage to start the bot and access its state info. ```python bot = Bot("TOKEN") async with bot: info = bot.state.info # RunningBotState -> BotInfo ``` -------------------------------- ### Bot.start Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/bot.md Starts the bot by creating a MaxApiClient and calling get_my_info() to confirm the token and obtain BotInfo. No-op if already started. ```APIDOC ## Bot.start ### Description Starts the bot by creating a MaxApiClient and calling get_my_info() to confirm the token and obtain BotInfo. No-op if already started. ### Method Async method ### Parameters None ### Request Example ```python await bot.start() ``` ### Response None ``` -------------------------------- ### RedisStorage and RedisEventIsolation usage example Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/fsm.md Shows how to configure a Dispatcher with RedisStorage and RedisEventIsolation using a shared Redis client and DefaultKeyBuilder with bot ID. The example then runs polling with a Bot. ```python from redis.asyncio import Redis from maxo import Bot, Dispatcher from maxo.fsm.storages.redis import RedisStorage, RedisEventIsolation from maxo.fsm.key_builder import DefaultKeyBuilder redis = Redis.from_url("redis://localhost:6379/0") key_builder = DefaultKeyBuilder(with_bot_id=True) dp = Dispatcher( storage=RedisStorage(redis, key_builder=key_builder), events_isolation=RedisEventIsolation(redis, key_builder=key_builder), ) dp.run_polling(Bot("TOKEN")) ``` -------------------------------- ### Bot.__aenter__ Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/bot.md Async context manager entry point that starts the bot. ```APIDOC ## Bot.__aenter__ ### Description Async context manager entry point that starts the bot. ### Method Async context manager ### Parameters None ### Request Example ```python async with bot: pass ``` ### Response - **Self** - The bot instance. ``` -------------------------------- ### Message facade usage example Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/facades.md Example handler using MessageMethodsFacade methods: answer, reply_text, and send_media with auto-upload and wait. ```python @dp.message_created() async def echo(message: MessageCreated) -> None: await message.answer(message.text or "пусто") await message.reply_text("Это ответ (reply) на твоё сообщение") await message.send_media(FSInputFile("cats.png")) # auto-upload + wait ``` -------------------------------- ### Using ChatActionMiddleware with flags or globally Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Shows two ways to apply ChatActionMiddleware: via a handler flag or as a global outer middleware. The flag example sets chat_action to SenderAction.TYPING_ON on a message_created handler; the global example registers the middleware directly. ```python from maxo.enums import SenderAction from maxo.utils.chat_action import ChatActionMiddleware @dp.message_created(flags={"chat_action": SenderAction.TYPING_ON}) async def slow_handler(message): ... # or globally: dp.message_created.outer_middleware(ChatActionMiddleware(SenderAction.TYPING_ON)) ``` -------------------------------- ### Routing usage examples Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/webhook.md Instantiate routing classes with example URLs. StaticRouting uses a constant URL, PathRouting requires a {bot_token} placeholder, and QueryRouting uses a query parameter named bot_token. ```python from maxo.transport.webhook.routing import StaticRouting, PathRouting, QueryRouting StaticRouting("https://example.com/webhook") PathRouting("https://example.com/webhook/{bot_token}") QueryRouting("https://example.com/webhook?bot_token=...") ``` -------------------------------- ### create_start_link Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Creates a Telegram start deep link for a bot. The payload can be encoded using base64url if encode=True. ```APIDOC ## create_start_link ### Description Creates a Telegram start deep link for a bot. The payload can be encoded using base64url if encode=True. ### Signature ```python def create_start_link( bot: "Bot", payload: str, encode: bool = False, encoder: Callable[[bytes], bytes] | None = None, ) -> str ``` ### Parameters - **bot** (Bot) - Required - The bot instance. - **payload** (str) - Required - The payload string. - **encode** (bool) - Optional - Whether to encode the payload. - **encoder** (Callable[[bytes], bytes] | None) - Optional - Custom encoder function. ### Returns - **str** - The generated deep link. ### Example ```python from maxo.utils import deeplink link = deeplink.create_start_link(bot, "promo_code", encode=True) ``` ``` -------------------------------- ### Logic combinators usage with Command and ChatAdminPermissionFilter Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/filters.md Shows how to combine filters using the & operator and ~ inversion. The example uses Command("start") and ChatAdminPermissionFilter(...) to create a handler condition. ```python @dp.message_created(Command("start") & ~ChatAdminPermissionFilter(...)) async def handler(message): ... ``` -------------------------------- ### Example test flow with BotClient Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/integrations.md Framework-internal scenario mirroring examples/dialogs_testing.py. Sets up a Dispatcher with DefaultKeyBuilder and setup_dialogs, then tests sending /start and clicking a button by payload locator. ```python import pytest from maxo import Dispatcher from maxo.dialogs import Dialog, Window, setup_dialogs from maxo.dialogs.test_tools import BotClient from maxo.fsm import State, StatesGroup from maxo.fsm.key_builder import DefaultKeyBuilder # NOTE: framework-internal scenario — this mirrors examples/dialogs_testing.py class S(StatesGroup): main = State() dp = Dispatcher(key_builder=DefaultKeyBuilder(with_destiny=True)) setup_dialogs(dp) # dp.include(dialog) -- your dialog async def test_flow(): client = BotClient(dp) await client.send("/start") await client.click("close") # payload locator # assert dialog closed ``` -------------------------------- ### KeyboardBuilder fluent usage example Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Shows how to build a keyboard using KeyboardBuilder with add_callback, add_link, add_clipboard, and adjust. The builder methods return self for chaining. The resulting keyboard is passed to message.answer with the keyboard parameter. ```python from maxo.utils.builders import KeyboardBuilder keyboard = ( KeyboardBuilder() .add_callback(text="Колбэк", payload="click_me") .add_link(text="Ссылка", url="https://github.com/K1rL3s/maxo") .add_clipboard(text="Скопировать", payload="maxo") .adjust(2, 1) .build() ) await message.answer("Кнопки", keyboard=keyboard) ``` -------------------------------- ### Dishka DI usage example with setup_dishka Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/integrations.md Shows how to wire dishka with maxo: create an async container with MaxoProvider and your own providers, register a handler, then call setup_dishka(container, dp, auto_inject=True) before run_polling. The handler receives Greeter via injection by parameter name. ```python from dataclasses import dataclass from dishka import make_async_container from maxo import Bot, Dispatcher from maxo.integrations.dishka import MaxoProvider, setup_dishka from maxo.types import MessageCreated @dataclass class Greeter: greeting: str = "Привет!" async def handler(message: MessageCreated, greeter: Greeter) -> None: await message.answer(f"{greeter.greeting}, {message.message.sender.first_name}") dp = Dispatcher() dp.message_created()(handler) # handler is resolved via injection container = make_async_container(MaxoProvider(), Greeter()) setup_dishka(container, dp, auto_inject=True) dp.run_polling(Bot("TOKEN")) ``` -------------------------------- ### Example usage of callback_answer Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/facades.md Example handler using MessageCallback to answer a callback with the text "Нажато!". The callback_answer method is called on the callback object. ```python @dp.message_callback() async def on_callback(callback: MessageCallback) -> None: await callback.callback_answer("Нажато!") ``` -------------------------------- ### Dishka DI integration API signatures Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/integrations.md Public API of src/maxo/integrations/dishka.py. Requires pip install maxo[dishka]. setup_dishka installs DishkaMiddleware on the dispatcher's update observer, opening a request-scoped container per update exposed as ctx["dishka_container"]. With auto_inject=True, before_startup hooks inject_router(dispatcher) to re-wrap handlers with inject. MaxoProvider declares request-scope context bindings. ```python CONTAINER_NAME = "dishka_container" def inject( func: _UpdateHandlerFn[_UpdateT, _ParamsP, _ReturnT] | _SignalHandlerFn[_ParamsP, _ReturnT], ) -> Any def setup_dishka( container: AsyncContainer, dispatcher: Dispatcher, auto_inject: bool, extra_context: dict[Any, Any] | None = None, ) -> None def inject_router(router: BaseRouter) -> None def inject_handler(handler: _Handler) -> _Handler class DishkaMiddleware(BaseMiddleware[MaxoUpdate[Any]]): ... class MaxoProvider(Provider): scope = Scope.REQUEST context = ( from_context(provides=Bot) + from_context(provides=Dispatcher) + from_context(provides=UpdateContext) + from_context(provides=BaseStorage) + from_context(provides=FSMContext) + from_context(provides=RawState) + from_context(provides=MaxoUpdate[Any]) + from_context(provides=MaxoUpdate[_UpdateT]) + from_context(provides=Ctx) ) ``` -------------------------------- ### as_numbered_list(*items, start=1, fmt="{}. ") Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Builds a numbered list with the given start number and format. This is a builder function for formatting helpers. ```APIDOC ## as_numbered_list(*items, start=1, fmt="{}. ") ### Description Builds a numbered list with the given start number and format. This is a builder function for formatting helpers. ### Parameters - **items** - The items to include in the list. - **start** (integer) - The starting number. Default is 1. - **fmt** (string) - The format string for the number prefix. Default is "{}. ". ### Returns - The formatted numbered list. ``` -------------------------------- ### Example: Window with Multi, Const, and Format Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialog-widgets.md Shows how to compose text widgets in a Window. Multi joins Const and Format with a separator; Format uses placeholders like {event.user.first_name} from window data. ```python from maxo.dialogs.widgets.text import Const, Format, Multi, Jinja Window( Multi( Const("Настройки"), Format("Привет, {event.user.first_name}!"), sep="\n\n", ), state=..., # your State ) ``` -------------------------------- ### StaticMedia usage example Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialog-widgets.md Creates a StaticMedia widget for a local image file. Requires importing StaticMedia and AttachmentType. ```python from maxo.dialogs.widgets.media import StaticMedia from maxo.enums import AttachmentType StaticMedia(Path("assets/cat.png"), AttachmentType.IMAGE) ``` -------------------------------- ### CommandStart Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/filters.md A specialized Command filter that matches the /start command. It inherits all behavior from Command but is pre-configured for the start command. ```APIDOC ## CommandStart ### Description A specialized Command filter that matches the /start command. It inherits all behavior from Command but is pre-configured for the start command. ### Constructor `CommandStart(ignore_case: bool = False, ignore_mention: bool = False) -> None` ### Parameters - `ignore_case` (bool) - Optional - If True, case-folds the command and incoming text. - `ignore_mention` (bool) - Optional - If False, requires the bot mention in the command. ### Usage ```python from maxo.routing.filters import CommandStart @dp.message_created(CommandStart()) async def on_start(message: MessageCreated, command) -> None: # command: CommandObject pass ``` ``` -------------------------------- ### Basic polling usage with Dispatcher Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dispatcher.md Shows how to create a Bot and Dispatcher, register a message handler, and start polling with clear_subscriptions enabled. ```python from maxo import Bot, Dispatcher bot = Bot("TOKEN") dp = Dispatcher() @dp.message_created() async def echo(message): ... dp.run_polling(bot, clear_subscriptions=True) ``` -------------------------------- ### setup_dishka Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/integrations.md Installs DishkaMiddleware on the dispatcher's update observer. The middleware opens a request-scoped container per update and exposes it as 'dishka_container' in the context, providing MaxoUpdate, Ctx, and extra_context values. ```APIDOC ## setup_dishka ### Description Installs DishkaMiddleware on the dispatcher's update observer. The middleware opens a request-scoped container per update and exposes it as 'dishka_container' in the context, providing MaxoUpdate, Ctx, and extra_context values. ### Function Signature ```python def setup_dishka( container: AsyncContainer, dispatcher: Dispatcher, auto_inject: bool, extra_context: dict[Any, Any] | None = None, ) -> None ``` ### Parameters - **container** (AsyncContainer) - Required - The Dishka container to use. - **dispatcher** (Dispatcher) - Required - The dispatcher to install the middleware on. - **auto_inject** (bool) - Required - If True, hooks inject_router on before_startup to re-wrap handlers. - **extra_context** (dict[Any, Any] | None) - Optional - Additional context values to expose. ### Returns - None ``` -------------------------------- ### start_polling/run_polling/LongPolling.start Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/configuration.md Starts the polling loop with configurable parameters for timeout, limit, marker, types, and more. These methods are used to begin receiving updates from the bot. ```APIDOC ## start_polling/run_polling/LongPolling.start ### Description Starts the polling loop with configurable parameters for timeout, limit, marker, types, and more. These methods are used to begin receiving updates from the bot. ### Method Start ### Parameters #### Keyword Arguments - **timeout** (int) - Optional - Timeout for polling. Defaults to `30`. - **limit** (int) - Optional - Maximum number of updates per request. Defaults to `100`. - **marker** (Omitted) - Optional - Marker for polling. - **types** (Omitted) - Optional - Types of updates to receive. - **auto_close_bot** (bool) - Optional - Automatically close the bot session. Defaults to `True`. - **drop_pending_updates** (bool) - Optional - Drop pending updates before polling. Defaults to `False`. - **clear_subscriptions** (bool) - Optional - Clear subscriptions before polling. Defaults to `False`. - **workflow_data** (dict) - Optional - Additional workflow data. ### Response Starts the polling loop. ``` -------------------------------- ### GET videos/{video_token} Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/methods.md Retrieves details for a video attachment by its token. ```APIDOC ## GET videos/{video_token} ### Description Retrieves details for a video attachment by its token. ### Method GET ### Endpoint videos/{video_token} ### Parameters #### Path Parameters - **video_token** (str) - Required - Token identifying the video. ### Response #### Success Response (200) - **VideoAttachmentDetails** - Details of the video attachment. ``` -------------------------------- ### LongPolling.start Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dispatcher.md Starts the long-polling loop asynchronously. It runs the same lifecycle as `run` but is awaitable, allowing non-blocking polling. ```APIDOC ## [ASYNC] LongPolling.start ### Description Starts the long-polling loop asynchronously. It runs the same lifecycle as `run` but is awaitable, allowing non-blocking polling. ### Method start ### Signature ```python async def start(self, ...) -> None # same signature as run ``` ### Parameters Same as `run`. ### Returns None ``` -------------------------------- ### Common usage example with Bot Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/methods.md Shows typical usage of the Bot class: sending messages with transparent query/body placement, long polling, and admin-only operations. Requires a valid bot token. ```python from maxo import Bot bot = Bot("TOKEN") async with bot: # Query + Body placement is transparent: result = await bot.send_message( user_id=123, # query: ?user_id=123 text="hello", # body format="html", # body, mapped to TextFormat.HTML disable_link_preview=True, # query ) msg = result.message print(msg.body.mid, msg.body.text) # Long polling updates = await bot.get_updates(limit=10, timeout=30) # Admin-only operations members = await bot.get_members(chat_id=7, count=100) await bot.add_members(chat_id=7, user_ids=[1, 2, 3]) ``` -------------------------------- ### Bot.context Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/bot.md Async context manager that enters the started state and optionally closes on exit. Typical for script-style usage. ```APIDOC ## Bot.context ### Description Async context manager that enters the started state and optionally closes on exit. Typical for script-style usage. ### Method Async context manager ### Parameters - **auto_close** (bool) - Optional - Whether to close the bot on exit. Default: `True` ### Request Example ```python async with bot.context(auto_close=False): info = bot.state.info ``` ### Response - **AsyncIterator[Self]** - Async iterator yielding the bot instance. ``` -------------------------------- ### GET me Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/methods.md Retrieves information about the current bot. This endpoint returns the bot's profile details. ```APIDOC ## GET me ### Description Retrieves information about the current bot. ### Method GET ### Endpoint `me` ### Response #### Success Response (200) - **BotInfo** - Bot profile information #### Response Example ```json { "id": 123456789, "first_name": "BotName", "username": "bot_username" } ``` ``` -------------------------------- ### RedisStorage(redis, key_builder=None, state_ttl=None, data_ttl=None, json_loads=json.loads, json_dumps=json.dumps) Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/configuration.md Creates a Redis-backed storage for FSM and data with optional TTL and custom JSON serialization. Use RedisStorage.from_url for connection setup. ```APIDOC ## RedisStorage(redis, key_builder=None, state_ttl=None, data_ttl=None, json_loads=json.loads, json_dumps=json.dumps) ### Description Creates a Redis-backed storage for FSM and data with optional TTL and custom JSON serialization. Use RedisStorage.from_url for connection setup. ### Method Constructor ### Parameters #### Positional Arguments - **redis** (Redis) - Required - Redis client instance. #### Keyword Arguments - **key_builder** (BaseKeyBuilder | None) - Optional - Key builder for storage keys. - **state_ttl** (int | None) - Optional - Time-to-live for state data. - **data_ttl** (int | None) - Optional - Time-to-live for data. - **json_loads** (callable) - Optional - JSON deserializer. Defaults to `json.loads`. - **json_dumps** (callable) - Optional - JSON serializer. Defaults to `json.dumps`. ### Response Returns a RedisStorage instance. ``` -------------------------------- ### TimingMiddleware example with outer_middleware registration Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/observers.md Shows a custom middleware that measures execution time and prints it. Registered via dp.message_created.outer_middleware(TimingMiddleware()). ```python import time from maxo.routing.interfaces import BaseMiddleware, NextMiddleware class TimingMiddleware(BaseMiddleware): async def __call__(self, update, ctx, next_: NextMiddleware) -> Any: start = time.perf_counter() result = await next_(ctx) print(f"{update.__class__.__name__}: {time.perf_counter() - start:.3f}s") return result dp.message_created.outer_middleware(TimingMiddleware()) ``` -------------------------------- ### Custom getter example with Window Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialog-widgets.md Shows how to define a custom getter that receives middleware_data as keyword arguments and use it in a Window with a static dict. The getter accesses the event user from kwargs. ```python async def my_getter(**kwargs) -> dict: return {"user": kwargs["event"].user} Window(..., state=..., getter=[my_getter, {"static": 1}]) ``` -------------------------------- ### Typical Router usage with Dispatcher Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dispatcher.md Shows how to create a Router, register a handler for the `message_created` update using the `CommandStart` filter, include the router in a Dispatcher, and start polling with a Bot token. ```python from maxo import Bot, Dispatcher, Router from maxo.routing.filters import CommandStart router = Router(name="handlers") @router.message_created(CommandStart()) async def start_handler(message): ... dp = Dispatcher() dp.include(router) dp.run_polling(Bot("TOKEN")) ``` -------------------------------- ### Dialog.process_start Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialogs.md Processes the start of the dialog with the given manager and start data. ```APIDOC ## Dialog.process_start ### Description Processes the start of the dialog with the given manager and start data. ### Method Async Method ### Signature ```python async def process_start(self, manager: DialogManager, start_data: Data, state: State | None = None) -> None ``` ### Parameters - **manager** (DialogManager) - Required - The dialog manager. - **start_data** (Data) - Required - Data to start the dialog. - **state** (State | None) - Optional - Initial state. ``` -------------------------------- ### Signature-driven injection example with @dp.message_created() Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/observers.md Shows how handler parameters are injected based on their names: message is passed positionally, while bot, fsm_context, and state are pulled from ctx. Requires the FSM middleware to provide fsm_context. ```python @dp.message_created() # signature-driven injection async def handler( message: MessageCreated, # positional: the update bot: Bot, # from ctx fsm_context: FSMContext, # from ctx (FSM middleware) state: State, # from ctx ) -> None: ... ``` -------------------------------- ### FSM usage example with StatesGroup and StateFilter Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/fsm.md Shows a complete FSM workflow: defines a Form StatesGroup with name and age states, uses StateFilter to handle messages per state, updates data and sets state, then clears after collecting age. Requires a Bot token and runs polling. ```python from maxo import Bot, Dispatcher from maxo.fsm import FSMContext, State, StatesGroup from maxo.routing.filters import StateFilter from maxo.types import MessageCreated class Form(StatesGroup): name = State() age = State() dp = Dispatcher() @dp.message_created(StateFilter(Form.name)) async def collect_name(message: MessageCreated, fsm_context: FSMContext) -> None: await message.answer("Сколько тебе лет?") await fsm_context.update_data(name=message.text) await fsm_context.set_state(Form.age) @dp.message_created(StateFilter(Form.age)) async def collect_age(message: MessageCreated, fsm_context: FSMContext) -> None: data = await fsm_context.get_data() print(data["name"], message.text) await fsm_context.clear() dp.run_polling(Bot("TOKEN")) ``` -------------------------------- ### aiohttp webhook setup with SimpleEngine and StaticRouting Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/webhook.md Complete aiohttp integration: creates a Bot and Dispatcher, configures SimpleEngine with AiohttpWebAdapter, StaticRouting, and StaticSecretToken security, sets the webhook on startup, and runs the aiohttp app on port 8080. ```python import logging from aiohttp import web from maxo import Bot, Dispatcher from maxo.transport.webhook.adapters.aiohttp import AiohttpWebAdapter from maxo.transport.webhook.engines import SimpleEngine, WebhookEngine from maxo.transport.webhook.routing import StaticRouting from maxo.transport.webhook.security import Security, StaticSecretToken bot = Bot("TOKEN") dispatcher = Dispatcher() engine = SimpleEngine( dispatcher, bot, web_adapter=AiohttpWebAdapter(), routing=StaticRouting(url="https://example.com/webhook"), security=Security(secret_token=StaticSecretToken("pepa_pig")), ) @dispatcher.after_startup() async def startup(webhook_engine: WebhookEngine) -> None: await webhook_engine.set_webhook() app = web.Application() engine.register(app) web.run_app(app, host="127.0.0.1", port=8080) ``` -------------------------------- ### FastAPI webhook setup with lifespan and SimpleEngine Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/webhook.md Complete FastAPI integration: creates a Bot and Dispatcher, configures SimpleEngine with FastApiWebAdapter and StaticRouting, defines a lifespan that calls engine.on_startup/on_shutdown, and registers the engine on the FastAPI app. ```python from contextlib import asynccontextmanager from fastapi import FastAPI from maxo import Bot, Dispatcher from maxo.transport.webhook.adapters.fastapi import FastApiWebAdapter from maxo.transport.webhook.engines import SimpleEngine from maxo.transport.webhook.routing import StaticRouting bot = Bot("TOKEN") dispatcher = Dispatcher() engine = SimpleEngine( dispatcher, bot, web_adapter=FastApiWebAdapter(), routing=StaticRouting(url="https://example.com/webhook"), ) @asynccontextmanager async def lifespan(app: FastAPI): await engine.on_startup(app) yield await engine.on_shutdown(app) app = FastAPI(lifespan=lifespan) engine.register(app) ``` -------------------------------- ### Dispatcher.start_polling Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dispatcher.md Starts long polling for the dispatcher. Creates a LongPolling instance and delegates to its start method. This is an async method that runs until cancelled. ```APIDOC ## Dispatcher.start_polling ### Description Starts long polling for the dispatcher. Creates a LongPolling instance and delegates to its start method. This is an async method that runs until cancelled. ### Method async ### Signature ```python async def start_polling( self, bot: Bot, backoff_config: BackoffConfig | None = None, timeout: Omittable[int] = 30, limit: Omittable[int] = 100, marker: Omittable[int | None] = Omitted(), types: Omittable[Sequence[str]] = Omitted(), auto_close_bot: bool = True, drop_pending_updates: bool = False, clear_subscriptions: bool = False, **workflow_data: Any, ) -> None ``` ### Parameters - **bot** (Bot) - Required - The bot instance to use for polling. - **backoff_config** (BackoffConfig | None) - Optional - Backoff configuration for polling. If not given, uses LongPolling's default. - **timeout** (Omittable[int]) - Optional - Timeout in seconds. Defaults to 30. - **limit** (Omittable[int]) - Optional - Maximum number of updates to fetch. Defaults to 100. - **marker** (Omittable[int | None]) - Optional - Marker for polling. Defaults to Omitted(). - **types** (Omittable[Sequence[str]]) - Optional - Types of updates to poll. Defaults to Omitted(). - **auto_close_bot** (bool) - Optional - Whether to auto-close the bot. Defaults to True. - **drop_pending_updates** (bool) - Optional - Whether to drop pending updates. Defaults to False. - **clear_subscriptions** (bool) - Optional - Whether to clear subscriptions. Defaults to False. - **workflow_data** (Any) - Optional - Additional workflow data. ### Example ```python from maxo import Bot, Dispatcher bot = Bot("TOKEN") dp = Dispatcher() @dp.message_created() async def echo(message): ... await dp.start_polling(bot, clear_subscriptions=True) ``` ``` -------------------------------- ### Sending media with FSInputFile and BufferedInputFile Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Shows how to send media using FSInputFile for a video file and BufferedInputFile for raw bytes. Requires importing UploadType and the input file classes. ```python from maxo.enums import UploadType from maxo.utils.upload_media import FSInputFile, BufferedInputFile await message.send_media(FSInputFile("video.mp4", type=UploadType.VIDEO)) await message.send_media(BufferedInputFile(b"...", "data.txt")) ``` -------------------------------- ### Deeplink function signatures (create_start_link, create_startapp_link, create_deep_link, etc.) Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Signatures for deeplink utilities in src/maxo/utils/deeplink.py. create_deep_link raises ValueError for forbidden characters (only A-Z a-z 0-9 _ -) unless encode=True (base64url via encode_payload) and for payloads longer than 128 chars. Requires bot.state.info.username (bot must be started). ```python PAYLOAD_MAX_LEN = 128 def create_start_link( bot: "Bot", payload: str, encode: bool = False, encoder: Callable[[bytes], bytes] | None = None, ) -> str def create_startapp_link( bot: "Bot", payload: str, encode: bool = False, app_name: str | None = None, encoder: Callable[[bytes], bytes] | None = None, ) -> str def create_deep_link( username: str, link_type: Literal["start", "startgroup", "startapp"], payload: str, app_name: str | None = None, encode: bool = False, encoder: Callable[[bytes], bytes] | None = None, ) -> str def create_max_http_link(...) -> str # src/maxo/utils/link.py def encode_payload(payload: str, encoder: Callable[[bytes], bytes] | None = None) -> str def decode_payload(payload: str) -> str ``` -------------------------------- ### KeyboardBuilder.__init__(keyboard: MutableSequence[MutableSequence[InlineButtons]] | None = None) -> None Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Initializes a KeyboardBuilder with an optional initial keyboard layout. ```APIDOC ## KeyboardBuilder.__init__(keyboard: MutableSequence[MutableSequence[InlineButtons]] | None = None) -> None ### Description Initializes a KeyboardBuilder with an optional initial keyboard layout. ### Parameters - **keyboard** (MutableSequence[MutableSequence[InlineButtons]] | None) - Optional - Initial keyboard layout. ``` -------------------------------- ### BaseDialogManager.start Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialogs.md Starts a new dialog with the given state, optionally providing initial data, start mode, show mode, and access settings. ```APIDOC ## BaseDialogManager.start ### Description Starts a new dialog with the given state, optionally providing initial data, start mode, show mode, and access settings. ### Method async ### Signature `async def start(self, state: State, data: Data = None, mode: StartMode = StartMode.NORMAL, show_mode: ShowMode | None = None, access_settings: AccessSettings | None = None) -> None` ### Parameters - **state** (State) - Required - The state to start the dialog with. - **data** (Data) - Optional - Initial data for the dialog. - **mode** (StartMode) - Optional - Start mode: NORMAL, RESET_STACK, or NEW_STACK. - **show_mode** (ShowMode | None) - Optional - Determines how the dialog is shown. - **access_settings** (AccessSettings | None) - Optional - Access settings for the dialog. ### Returns None ``` -------------------------------- ### SyncFilter usage example Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/filters.md Example of using SyncFilter with a custom predicate. The predicate is_even checks if the message text length is even. The filter is applied via dp.message_created(SyncFilter(is_even)). ```python from maxo.routing.filters import SyncFilter def is_even(message) -> bool: return message.text is not None and len(message.text) % 2 == 0 @dp.message_created(SyncFilter(is_even)) async def on_even_len(message): ... ``` -------------------------------- ### InputFile types Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Base and concrete classes for representing input files for media uploads. Provides methods to read, stream, and get file size. ```APIDOC ## InputFile types ### Description Base and concrete classes for representing input files for media uploads. Provides methods to read, stream, and get file size. ### Classes #### InputFile (base) - **Attributes**: `type: UploadType`, `file_name: str` - **Methods**: - `async size(self) -> int` - Returns the file size in bytes. - `async read(self) -> bytes` - Reads the entire file content. - `async stream(self, chunk_size: int) -> AsyncIterator[bytes]` - Streams the file in chunks. #### BufferedInputFile(InputFile) - **Constructor**: `__init__(self, data: bytes, filename: str, type: UploadType = UploadType.FILE) -> None` - **Description**: Represents an input file from in-memory bytes. #### FSInputFile(InputFile) - **Constructor**: `__init__(self, path: str | Path, type: UploadType = UploadType.FILE, filename: str | None = None) -> None` - **Description**: Represents an input file from a filesystem path. ### Example ```python from maxo.enums import UploadType from maxo.utils.upload_media import FSInputFile, BufferedInputFile await message.send_media(FSInputFile("video.mp4", type=UploadType.VIDEO)) await message.send_media(BufferedInputFile(b"...", "data.txt")) ``` ``` -------------------------------- ### setup_jinja Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialog-widgets.md Configures a Jinja2 environment for use with Jinja widgets. ```APIDOC ## setup_jinja ### Description Configures a Jinja2 environment for use with Jinja widgets. ### Method Function ### Signature ```python def setup_jinja(env: Environment) -> None ``` ### Parameters - **env** (Environment) - Required - The Jinja2 environment to configure. ``` -------------------------------- ### safe_parse_webapp_init_data Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/utils.md Runs the signature check first and returns None when verification fails. ```APIDOC ## safe_parse_webapp_init_data ### Description Runs the signature check first and returns None when verification fails. ### Signature ```python async def safe_parse_webapp_init_data(token: str, init_data: str, *, loads: Callable[..., Any] = json.loads) -> WebAppInitData | None ``` ### Parameters - **token** (str) - Required - The token used for verification. - **init_data** (str) - Required - The init-data query string. - **loads** (Callable) - Optional - JSON decoder function. ### Returns - **WebAppInitData | None** - Parsed init data or None if verification fails. ``` -------------------------------- ### RedisStorage and RedisEventIsolation class definitions Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/fsm.md Redis-backed storage and event isolation. Requires pip install maxo[redis] (redis[hiredis]>=5.0.1,<9.0.0). Both accept a configured redis.asyncio.Redis client. set_state(None) or empty set_data delete the key; data is JSON-serialized; state_ttl/data_ttl apply Redis EX expiry. RedisStorage.close() closes the underlying Redis client. from_url builds its own ConnectionPool and Redis instance. ```python class RedisStorage(BaseStorage): def __init__( self, redis: Redis, key_builder: BaseKeyBuilder | None = None, state_ttl: ExpiryT | None = None, data_ttl: ExpiryT | None = None, json_loads: Callable[[Any], Any] = json.loads, json_dumps: Callable[[Any], str] = json.dumps, ) -> None # set_state / get_state / set_data / get_data / close @classmethod def from_url( cls, url: str, connection_kwargs: dict[str, Any] | None = None, **kwargs: Any, ) -> "RedisStorage": ... def create_isolation(self, **kwargs: Any) -> "RedisEventIsolation": ... DEFAULT_REDIS_LOCK_KWARGS = {"timeout": 60} class RedisEventIsolation(BaseEventIsolation): def __init__( self, redis: Redis, key_builder: BaseKeyBuilder | None = None, lock_kwargs: dict[str, Any] | None = None, ) -> None # lock() acquires redis.asyncio.lock.Lock with lock_kwargs (default timeout=60) ``` -------------------------------- ### GET /chats Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/endpoints.md Retrieves a list of chats. ```APIDOC ## GET /chats ### Description Retrieves a list of chats. ### Method GET ### Endpoint /chats ### Parameters #### Query Parameters - **count** (int) - Optional - Number of chats to return. - **marker** (int) - Optional - Pagination marker. ### Response #### Success Response (200) - **ChatList** - Contains list of chats and marker. #### Response Example ```json { "chats": [], "marker": null } ``` ``` -------------------------------- ### StaticMedia.__init__ Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialog-widgets.md Initializes a StaticMedia widget that renders a local file path as an attachment. ```APIDOC ## StaticMedia.__init__ ### Description Initializes a StaticMedia widget that renders a local file path as an attachment. ### Method Constructor ### Signature `StaticMedia(path: Path | str, type: AttachmentType, when: WhenCondition = None)` ### Parameters - **path** (Path | str) - Required - Local file path to the media file. - **type** (AttachmentType) - Required - Type of the attachment (e.g., image, video). - **when** (WhenCondition) - Optional - Condition for when the widget is active. ### Example ```python from maxo.dialogs.widgets.media import StaticMedia from maxo.enums import AttachmentType StaticMedia(Path("assets/cat.png"), AttachmentType.IMAGE) ``` ``` -------------------------------- ### Polling entry points: start_polling and run_polling Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dispatcher.md Defines the async start_polling and synchronous run_polling methods for starting long polling. run_polling wraps start_polling with asyncio.run and blocks until cancelled. ```python async def start_polling( self, bot: Bot, backoff_config: BackoffConfig | None = None, timeout: Omittable[int] = 30, limit: Omittable[int] = 100, marker: Omittable[int | None] = Omitted(), types: Omittable[Sequence[str]] = Omitted(), auto_close_bot: bool = True, drop_pending_updates: bool = False, clear_subscriptions: bool = False, **workflow_data: Any, ) -> None ``` ```python def run_polling( self, bot: Bot, backoff_config: BackoffConfig | None = None, timeout: Omittable[int] = 30, limit: Omittable[int] = 100, marker: Omittable[int | None] = Omitted(), types: Omittable[Sequence[str]] = Omitted(), auto_close_bot: bool = True, drop_pending_updates: bool = False, clear_subscriptions: bool = False, **workflow_data: Any, ) -> None ``` -------------------------------- ### Run maxo-dialog-preview CLI Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/integrations.md Invokes the CLI command to generate an HTML preview of dialog windows. Requires the `preview` extra; `diagrams` extra needed for transitions. ```console maxo-dialog-preview --app-module examples.bot --dialogs-router bot_dialog ``` -------------------------------- ### LongPolling(dispatcher, backoff_config=BackoffConfig(min_delay=1.0, max_delay=5.0, factor=1.3, jitter=0.1)) Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/configuration.md Creates a LongPolling instance for polling updates from the dispatcher with configurable backoff settings. This is the main entry point for starting the bot's polling loop. ```APIDOC ## LongPolling(dispatcher, backoff_config=BackoffConfig(min_delay=1.0, max_delay=5.0, factor=1.3, jitter=0.1)) ### Description Creates a LongPolling instance for polling updates from the dispatcher with configurable backoff settings. This is the main entry point for starting the bot's polling loop. ### Method Constructor ### Parameters #### Positional Arguments - **dispatcher** (Dispatcher) - Required - The dispatcher instance. #### Keyword Arguments - **backoff_config** (BackoffConfig) - Optional - Backoff configuration for polling. Defaults to `BackoffConfig(min_delay=1.0, max_delay=5.0, factor=1.3, jitter=0.1)`. ### Response Returns a LongPolling instance. ``` -------------------------------- ### GET /subscriptions Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/endpoints.md Retrieves the list of active subscriptions. ```APIDOC ## GET /subscriptions ### Description Retrieves the list of active subscriptions. ### Method GET ### Endpoint /subscriptions ### Response #### Success Response (200) - **subscriptions** (list[Subscription]) - List of subscriptions. #### Response Example ```json { "subscriptions": [] } ``` ``` -------------------------------- ### GET /chats/{chat_link} Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/endpoints.md Retrieves a chat by its link. ```APIDOC ## GET /chats/{chat_link} ### Description Retrieves a chat by its link. ### Method GET ### Endpoint /chats/{chat_link} ### Parameters #### Path Parameters - **chat_link** (string) - Required - The chat link. ### Response #### Success Response (200) - **Chat** - The chat object. #### Response Example ```json { "Chat": {} } ``` ``` -------------------------------- ### LinkPreview.__init__ Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/api-reference/dialog-widgets.md Initializes a LinkPreview widget that renders a link preview for a URL. ```APIDOC ## LinkPreview.__init__ ### Description Initializes a LinkPreview widget that renders a link preview for a URL. ### Method Constructor ### Signature `LinkPreview(url: TextWidget | None = None, disabled: bool = False, when=None)` ### Parameters - **url** (TextWidget | None) - Optional - The URL to preview. - **disabled** (bool) - Optional - Whether the preview is disabled. - **when** - Optional - Condition for when the widget is active. ``` -------------------------------- ### GET /chats/{chatId} Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/endpoints.md Retrieves a chat by its ID. ```APIDOC ## GET /chats/{chatId} ### Description Retrieves a chat by its ID. ### Method GET ### Endpoint /chats/{chatId} ### Parameters #### Path Parameters - **chatId** (int) - Required - The chat ID. ### Response #### Success Response (200) - **Chat** - The chat object. #### Response Example ```json { "Chat": {} } ``` ``` -------------------------------- ### GET /chats/{chatId}/members/admins Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/endpoints.md Retrieves admins of a chat. ```APIDOC ## GET /chats/{chatId}/members/admins ### Description Retrieves admins of a chat. ### Method GET ### Endpoint /chats/{chatId}/members/admins ### Parameters #### Path Parameters - **chatId** (int) - Required - The chat ID. ### Response #### Success Response (200) - **ChatMembersList** - Contains members and marker. #### Response Example ```json { "members": [], "marker": null } ``` ``` -------------------------------- ### GET /me Source: https://github.com/k1rl3s/maxo/blob/master/_autodocs/endpoints.md Returns the bot's profile and commands. ```APIDOC ## GET /me ### Description Returns the bot's profile and commands. ### Method GET ### Endpoint /me ### Response #### Success Response (200) - **BotInfo** - Bot profile and commands. #### Response Example ```json { "BotInfo": {} } ``` ```