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:
3 months ago
Context
Chat
Benchmark
71
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Minimal bot usage Source: https://github.com/k1rl3s/maxo Basic usage example showing how to create a Bot, start it, access the bot info after start, and close it. The bot.info property is only available after start() has been called. ```python # Minimal bot from maxo import Bot bot = Bot("TOKEN") await bot.start() print(bot.state.info.username) # BotInfo, available only after start await bot.close() ``` -------------------------------- ### Full setup_dialogs usage example Source: https://github.com/k1rl3s/maxo Complete example showing how to set up a dialog with setup_dialogs. Includes a dialog with a close button, a start handler using StartMode.RESET_STACK, and includes the dialog in the dispatcher before calling setup_dialogs and run_polling. ```python from maxo import Bot, Dispatcher from maxo.dialogs import Dialog, DialogManager, StartMode, Window, setup_dialogs from maxo.dialogs.widgets.kbd import Button from maxo.dialogs.widgets.text import Const from maxo.fsm import State, StatesGroup from maxo.routing.filters import CommandStart from maxo.types import MessageCreated class Main(StatesGroup): main = State() bot = Bot("TOKEN") dp = Dispatcher() async def close_dialog(callback, button, manager: DialogManager) -> None: await manager.done() dialog = Dialog( Window(Const("Меню"), Button(Const("Закрыть"), id="close", on_click=close_dialog), state=Main.main), ) @dp.message_created(CommandStart()) async def start(message: MessageCreated, dialog_manager: DialogManager) -> None: await dialog_manager.start(Main.main, mode=StartMode.RESET_STACK) dp.include(dialog) setup_dialogs(dp) dp.run_polling(bot) ``` -------------------------------- ### Aiohttp webhook setup example Source: https://github.com/k1rl3s/maxo Complete example of setting up a webhook with AiohttpWebAdapter, SimpleEngine, StaticRouting, and StaticSecretToken. Registers the engine with an aiohttp web.Application and runs it on 127.0.0.1:8080. ```python from aiohttp import web from maxo import Bot, Dispatcher from maxo.transport.webhook.adapters.aiohttp import AiohttpWebAdapter from maxo.transport.webhook.engines import SimpleEngine from maxo.transport.webhook.routing import StaticRouting from maxo.transport.webhook.security import Security, StaticSecretToken engine = SimpleEngine( dp, bot, web_adapter=AiohttpWebAdapter(), routing=StaticRouting(url="https://example.com/webhook"), security=Security(secret_token=StaticSecretToken("pepa_pig")), ) app = web.Application() engine.register(app) web.run_app(app, host="127.0.0.1", port=8080) ``` -------------------------------- ### Usage example Source: https://github.com/k1rl3s/maxo Example showing how to use Text, Bold, Link, Mention, and as_marked_section to build a message and send it via the MAX API. ```APIDOC ## Usage example ### Description Example showing how to use Text, Bold, Link, Mention, and as_marked_section to build a message and send it via the MAX API. ### Example ```python from maxo.utils.formatting import Bold, Link, Mention, as_marked_section, Text msg = Text(Bold("Заголовок"), "\n", Mention("ты", user_id=42), " ", Link("сайт", url="https://example.com"), sep="") await message.answer_text(**msg.as_kwargs()) # or await message.answer(text=msg.as_html(), format=TextFormat.HTML) ``` ``` -------------------------------- ### FastAPI webhook example Source: https://github.com/k1rl3s/maxo Shows how to set up a FastAPI app with Maxo's webhook engine using PathRouting. The lifespan context registers the engine and handles startup/shutdown. After setup, POST /webhook/<token> delivers updates to the dispatcher. ```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, PathRouting dp = Dispatcher() bot = Bot("TOKEN") engine = SimpleEngine( dp, bot, web_adapter=FastApiWebAdapter(), routing=PathRouting(url="https://example.com/webhook/{bot_token}"), ) @asynccontextmanager async def lifespan(app: FastAPI): engine.register(app) await engine.on_startup(app) yield await engine.on_shutdown(app) app = FastAPI(lifespan=lifespan) # POST /webhook/<token> now delivers MAX updates to the dispatcher ``` -------------------------------- ### Start Source: https://github.com/k1rl3s/maxo A button that starts a new state when clicked. It triggers manager.start() with the specified state and data. ```APIDOC ## Start ### Description A button that starts a new state when clicked. It triggers manager.start() with the specified state and data. ### Constructor ```python Start( text: TextWidget, id: str, state: State, data: Data = None, on_click: OnClick | None = None, show_mode: ShowMode | None = None, mode: StartMode = StartMode.NORMAL, when: WhenCondition = None, ) -> None ``` ### Parameters - **text** (TextWidget) - Required - The text displayed on the button. - **id** (str) - Required - Unique identifier for the button. - **state** (State) - Required - The state to start. - **data** (Data) - Optional - Data to pass to the state. - **on_click** (OnClick | None) - Optional - Callback invoked when the button is clicked. - **show_mode** (ShowMode | None) - Optional - Display mode for the state. - **mode** (StartMode) - Optional - Start mode (default: StartMode.NORMAL). - **when** (WhenCondition) - Optional - Condition controlling when the button is shown. ``` -------------------------------- ### Dishka DI usage example — setup_dishka with inject Source: https://github.com/k1rl3s/maxo `setup_dishka` installs `DishkaMiddleware` as the outermost middleware of `dispatcher.update`. The middleware opens a request container with `MaxoUpdate[Any]`, the concrete `MaxoUpdate[type(update.update)]`, `Ctx` and `extra_context` bound, and stores it at `ctx[CONTAINER_NAME]`. With `auto_inject=True`, on `BeforeStartup` it registers a handler that performs `inject_router(dispatcher)` so all registered handlers become injection-aware without decorators. Signal handlers resolve directly from the container that `DishkaMiddleware` provides (a fallback puts the container into `ctx` first). ```python from dishka import make_async_container from maxo import Bot, Dispatcher from maxo.fsm.context import FSMContext from maxo.integrations.dishka import MaxoProvider, inject, setup_dishka container = make_async_container(MaxoProvider()) dp = Dispatcher() @dp.message_created() @inject async def handler(message, fsm_context: FSMContext, service: MyService) -> None: ... setup_dishka(container, dp, auto_inject=False) ``` -------------------------------- ### Install Maxo extras via pip Source: https://github.com/k1rl3s/maxo Install optional dependencies for specific Maxo integrations. Required for magic_filter, dishka, redis, fastapi, and preview extras. Importing modules without the extra raises ImportError with a pip install note. ```bash pip install maxo[magic_filter|dishka|redis|fastapi|preview] ``` -------------------------------- ### Custom filter example: TextStartsWith Source: https://github.com/k1rl3s/maxo Shows how to implement a custom filter by subclassing BaseFilter and overriding __call__. The filter checks if the message text starts with a given prefix. ```python from maxo.routing.filters import BaseFilter from maxo.types import MessageCreated class TextStartsWith(BaseFilter[MessageCreated]): def __init__(self, prefix: str) -> None: self.prefix = prefix async def __call__(self, message: MessageCreated, ctx) -> bool: text = message.text return bool(text and text.startswith(self.prefix)) ``` -------------------------------- ### FastAPI Webhook Example Source: https://github.com/k1rl3s/maxo Example of setting up a FastAPI webhook adapter with the SimpleEngine, using PathRouting to deliver updates to the dispatcher. ```APIDOC ## FastAPI Webhook Example ### Description Example of setting up a FastAPI webhook adapter with the SimpleEngine, using PathRouting to deliver updates to the dispatcher. ### Example ```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, PathRouting dp = Dispatcher() bot = Bot("TOKEN") engine = SimpleEngine( dp, bot, web_adapter=FastApiWebAdapter(), routing=PathRouting(url="https://example.com/webhook/{bot_token}"), ) @asynccontextmanager async def lifespan(app: FastAPI): engine.register(app) await engine.on_startup(app) yield await engine.on_shutdown(app) app = FastAPI(lifespan=lifespan) # POST /webhook/<token> now delivers MAX updates to the dispatcher ``` ``` -------------------------------- ### Bot.start Source: https://github.com/k1rl3s/maxo Starts the bot, making it ready for API calls. Idempotent; called implicitly by `__aenter__` and by `LongPolling`/`SimpleEngine`. ```APIDOC ## [METHOD] Bot.start ### Description Starts the bot, making it ready for API calls. Idempotent; called implicitly by `__aenter__` and by `LongPolling`/`SimpleEngine`. ### Method Async Method ### Endpoint `Bot.start` ### Parameters None ### Response #### Success Response - **None** - No return value ``` -------------------------------- ### Long polling usage example Source: https://github.com/k1rl3s/maxo Shows how to instantiate LongPolling with a Bot and Dispatcher, then start polling with custom timeout and drop_pending_updates. The start method is awaited and requires an async context. ```python from maxo import Bot, Dispatcher from maxo.transport.long_polling import LongPolling bot = Bot("TOKEN") dp = Dispatcher() polling = LongPolling(dp) # custom backoff via BackoffConfig await polling.start(bot, timeout=25, drop_pending_updates=True) ``` -------------------------------- ### Bot.__aenter__ Source: https://github.com/k1rl3s/maxo Async context manager entry point that starts the bot. Returns the bot instance. ```APIDOC ## [METHOD] Bot.__aenter__ ### Description Async context manager entry point that starts the bot. Returns the bot instance. ### Method Async Context Manager Entry ### Endpoint `Bot.__aenter__` ### Parameters None ### Response #### Success Response - **Self** - The bot instance ``` -------------------------------- ### ChatMembersIterator usage example Source: https://github.com/k1rl3s/maxo Example of iterating over chat members using ChatMembersIterator with a bot instance and chat_id. ```python from maxo.utils.iterators import ChatMembersIterator async for member in ChatMembersIterator(bot, chat_id=123, user_ids=[1, 2]): print(member.user_id) ``` -------------------------------- ### RedisStorage usage example Source: https://github.com/k1rl3s/maxo Shows how to instantiate RedisStorage from a URL and create a Dispatcher with the storage and its event isolation. The storage is configured with a state TTL of 3600 seconds. ```python from redis.asyncio import Redis from maxo import Dispatcher from maxo.fsm.storages.redis import RedisStorage, RedisEventIsolation storage = RedisStorage.from_url("redis://localhost:6379/0", state_ttl=3600) dp = Dispatcher(storage=storage, events_isolation=storage.create_isolation()) ``` -------------------------------- ### create_start_link Source: https://github.com/k1rl3s/maxo Creates a Telegram deep link with `start` payload. Payload must contain only `A-Z a-z 0-9 _ -` or `ValueError` is raised. ```APIDOC ## create_start_link ### Description Creates a deep link for the `start` parameter. Payloads may contain only `A-Z a-z 0-9 _ -` — otherwise `ValueError` (pass `encode=True`); too-long payloads raise `ValueError` with the limit. ### Signature `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. ``` -------------------------------- ### KeyboardBuilder usage example Source: https://github.com/k1rl3s/maxo Builds a keyboard with two callback buttons and a link, then adjusts to 2 and 1 columns. Pass the built keyboard to message.answer. ```python from maxo.utils.builders import KeyboardBuilder kbd = ( KeyboardBuilder() .add_callback("Да", payload="yes") .add_callback("Нет", payload="no") .add_link("Сайт", "https://max.ru") .adjust(2, 1) ) await message.answer("Выберите:", keyboard=kbd.build()) ``` -------------------------------- ### Usage example: Command and CommandStart handlers Source: https://github.com/k1rl3s/maxo Shows how to use Command and CommandStart filters in a message handler. The Command filter matches multiple command strings and options; CommandStart matches the /start command. The command object is passed as a parameter. ```python from maxo.routing.filters import Command, CommandStart @dp.message_created(Command("help", "start", commands=["menu"], ignore_case=True)) async def help_handler(message, command: CommandObject) -> None: await message.answer(command.text) @dp.message_created(CommandStart()) async def start_handler(message, command: CommandObject) -> None: ... ``` -------------------------------- ### BaseDialogManager.start Source: https://github.com/k1rl3s/maxo Starts a new dialog with the given state and data. Allows specifying start mode, show mode, and access settings. ```APIDOC ## BaseDialogManager.start ### Description Starts a new dialog with the given state and data. Allows specifying start mode, show mode, and access settings. ### Method async ### Signature ```python 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 (default: NORMAL). - **show_mode** (ShowMode | None) - Optional - Show mode for the dialog. - **access_settings** (AccessSettings | None) - Optional - Access settings for the dialog. ``` -------------------------------- ### LongPolling class definition and run/start signatures Source: https://github.com/k1rl3s/maxo Defines the LongPolling class with its constructor and the run and start method signatures. The start method is async and has the same signature as run. The default backoff configuration is BackoffConfig(min_delay=1.0, max_delay=5.0, factor=1.3, jitter=0.1). ```python _DEFAULT_BACKOFF_CONFIG = BackoffConfig(min_delay=1.0, max_delay=5.0, factor=1.3, jitter=0.1) class LongPolling: def __init__( self, dispatcher: Dispatcher, backoff_config: BackoffConfig = _DEFAULT_BACKOFF_CONFIG, ) -> None def run( self, bot: Bot, 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 async def start(self, bot: Bot, ...same signature...) -> None ``` -------------------------------- ### FlagGenerator usage examples Source: https://github.com/k1rl3s/maxo Shows how to create and use flags via the FlagGenerator. Calling a FlagDecorator with both a value and kwargs raises ValueError. ```python flags = FlagGenerator() # flags.throttling / flags.callback_answer / ... any name flags.throttling(rate=3, key="x") # returns FlagDecorator flags.throttling(True) # returns FlagDecorator with value True flags.throttling # value True by default @flags... def my_handler(...): ... # or used directly as decorator ``` -------------------------------- ### setup_dialogs Source: https://github.com/k1rl3s/maxo Registers dialog event observers and installs middlewares on the dispatcher. Returns a BgManagerFactory for background dialog management. ```APIDOC ## setup_dialogs ### Description Registers `DialogUpdateEvent`/`DialogStartEvent`/`DialogSwitchEvent`/`DialogFgEvent` observers, installs the intent, manager, context-saver/unlocker and bg-factory middlewares on every relevant observer of the dispatcher, and returns a `BgManagerFactory` (`BgManagerFactoryImpl(router)`). ### Method Function call ### Endpoint `maxo.dialogs.setup.setup_dialogs` (line 247) ### Parameters #### Function Parameters - **router** (Dispatcher) - Required - The dispatcher to set up dialogs on. - **dialog_manager_factory** (DialogManagerFactory | None) - Optional - Factory for creating dialog managers. Defaults to `DefaultManagerFactory` with `MediaIdStorage()` and `MessageManager(media_id_storage)`. - **message_manager** (MessageManagerProtocol | None) - Optional - Message manager for sending messages. Defaults to `MessageManager(media_id_storage)`. - **media_id_storage** (MediaIdStorageProtocol | None) - Optional - Storage for media IDs. Defaults to `MediaIdStorage()`. - **stack_access_validator** (StackAccessValidator | None) - Optional - Validator for stack access. Defaults to `DefaultAccessValidator`. - **events_isolation** (BaseEventIsolation | None) - Optional - Event isolation strategy. Defaults to `SimpleEventIsolation(DefaultKeyBuilder(with_destiny=True))`. - **getter** (DataGetter | None) - Optional - Data getter for dialog data. ### Returns - **BgManagerFactory** - Factory for background dialog management. ### Example ```python from maxo import Bot, Dispatcher from maxo.dialogs import Dialog, DialogManager, StartMode, Window, setup_dialogs from maxo.dialogs.widgets.kbd import Button from maxo.dialogs.widgets.text import Const from maxo.fsm import State, StatesGroup from maxo.routing.filters import CommandStart from maxo.types import MessageCreated class Main(StatesGroup): main = State() bot = Bot("TOKEN") dp = Dispatcher() async def close_dialog(callback, button, manager: DialogManager) -> None: await manager.done() dialog = Dialog( Window(Const("Меню"), Button(Const("Закрыть"), id="close", on_click=close_dialog), state=Main.main), ) @dp.message_created(CommandStart()) async def start(message: MessageCreated, dialog_manager: DialogManager) -> None: await dialog_manager.start(Main.main, mode=StartMode.RESET_STACK) dp.include(dialog) setup_dialogs(dp) dp.run_polling(bot) ``` ``` -------------------------------- ### Dialog.process_start Source: https://github.com/k1rl3s/maxo 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 Method ### Signature ```python process_start(manager, start_data, state=None) ``` ### Parameters - **manager** - The dialog manager. - **start_data** - The data passed to start the dialog. - **state** (optional) - The initial state. ``` -------------------------------- ### Example: Confirm payload with prefix and usage Source: https://github.com/k1rl3s/maxo Shows a concrete Payload subclass with prefix="confirm" and its usage in a message callback handler. The pack() method produces a string like "confirm:42:1", and unpack() reconstructs the object. The handler receives the parsed payload as a parameter. ```python from dataclasses import dataclass from maxo.routing.filters import Payload from maxo.types import MessageCallback @dataclass class Confirm(Payload, prefix="confirm"): user_id: int ok: bool @dp.message_callback(Confirm.filter()) async def on_confirm(callback: MessageCallback, payload: Confirm) -> None: await callback.callback_answer(f"user={payload.user_id}, ok={payload.ok}") data = Confirm(user_id=42, ok=True).pack() # "confirm:42:1" origin = Confirm.unpack(data) ``` -------------------------------- ### create_deep_link Source: https://github.com/k1rl3s/maxo Creates a deep link with a specified link type (`start` or `startapp`). Payload must contain only `A-Z a-z 0-9 _ -` or `ValueError` is raised. ```APIDOC ## create_deep_link ### Description Creates a deep link with a specified link type. Payloads may contain only `A-Z a-z 0-9 _ -` — otherwise `ValueError` (pass `encode=True`); too-long payloads raise `ValueError` with the limit. ### Signature `def create_deep_link(username: str, link_type: Literal["start", "startapp"], payload: str, encode: bool = False, encoder: Callable[[bytes], bytes] | None = None) -> str` ### Parameters - `username` (str) - Required - The bot username. - `link_type` (Literal["start", "startapp"]) - Required - The type of deep link. - `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. ``` -------------------------------- ### setup_dialogs function signature Source: https://github.com/k1rl3s/maxo Registers dialog event observers and installs middlewares on the dispatcher, returning a BgManagerFactory. Defaults: MediaIdStorage() + MessageManager(media_id_storage) inside DefaultManagerFactory, DefaultAccessValidator, SimpleEventIsolation(DefaultKeyBuilder(with_destiny=True)). ```python def setup_dialogs( router: Dispatcher, *, dialog_manager_factory: DialogManagerFactory | None = None, message_manager: MessageManagerProtocol | None = None, media_id_storage: MediaIdStorageProtocol | None = None, stack_access_validator: StackAccessValidator | None = None, events_isolation: BaseEventIsolation | None = None, getter: DataGetter | None = None, ) -> BgManagerFactory ``` -------------------------------- ### setup_dishka Source: https://github.com/k1rl3s/maxo Installs DishkaMiddleware as the outermost middleware of dispatcher.update. The middleware opens a request container with MaxoUpdate[Any], the concrete MaxoUpdate[type(update.update)], Ctx and extra_context bound, and stores it at ctx[CONTAINER_NAME]. ```APIDOC ## setup_dishka ### Description Installs DishkaMiddleware as the outermost middleware of dispatcher.update. The middleware opens a request container with MaxoUpdate[Any], the concrete MaxoUpdate[type(update.update)], Ctx and extra_context bound, and stores it at ctx[CONTAINER_NAME]. ### 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 async container to use for dependency resolution. - **dispatcher** (Dispatcher) - Required - The Maxo dispatcher to install the middleware on. - **auto_inject** (bool) - Required - If True, registers a handler on BeforeStartup that performs inject_router(dispatcher) so all registered handlers become injection-aware without decorators. - **extra_context** (dict[Any, Any] | None) - Optional - Additional context values to bind into the request container. ### Returns - None ### Example ```python setup_dishka(container, dp, auto_inject=False) ``` ``` -------------------------------- ### Bot.context Source: https://github.com/k1rl3s/maxo Async context manager that starts the bot and optionally closes it on exit. Returns an async iterator of the bot instance. ```APIDOC ## [METHOD] Bot.context ### Description Async context manager that starts the bot and optionally closes it on exit. Returns an async iterator of the bot instance. ### Method Async Context Manager ### Endpoint `Bot.context` ### Parameters #### Parameters - **auto_close** (bool) - Optional - Whether to close the bot on exit (default: True) ### Response #### Success Response - **AsyncIterator[Self]** - Async iterator of the bot instance ``` -------------------------------- ### GET /me Source: https://github.com/k1rl3s/maxo Retrieves information about the current bot. Returns a BotInfo object. ```APIDOC ## GET /me ### Description Retrieves information about the current bot. ### Method GET ### Endpoint /me ### Response #### Success Response (200) - **BotInfo** (object) - Information about the bot. ``` -------------------------------- ### Handler using FSMContext Source: https://github.com/k1rl3s/maxo Example handler that receives FSMContext via fsm_context keyword, sets state, updates data, and replies. Shows typical usage in a message handler. ```python from maxo.fsm import FSMContext @dp.message_created(Command("start")) async def cmd_start(message, fsm_context: FSMContext) -> None: await fsm_context.set_state(Form.name) await fsm_context.update_data(user_id=message.user_id) await message.answer("Как вас зовут?") ``` -------------------------------- ### start_polling Source: https://github.com/k1rl3s/maxo Starts long polling for updates. Builds a LongPolling instance with optional backoff configuration and runs it, forwarding arguments to LongPolling.start. Validates the router graph and resolves middleware chains before startup signals are emitted. ```APIDOC ## start_polling ### Description Starts long polling for updates. Builds a LongPolling instance with optional backoff configuration and runs it, forwarding arguments to LongPolling.start. Validates the router graph and resolves middleware chains before startup signals are emitted. ### Method 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 poll for updates. - **backoff_config** (BackoffConfig | None) - Optional - Configuration for backoff on connection errors. - **timeout** (Omittable[int]) - Optional - Long-poll server timeout seconds. Default: 30. - **limit** (Omittable[int]) - Optional - Max updates per poll response. Default: 100. - **marker** (Omittable[int | None]) - Optional - Updates cursor; None/Omitted() = last update only. Default: Omitted(). - **types** (Omittable[Sequence[str]]) - Optional - Event type whitelist; empty/omitted → derived via collect_used_updates. Default: Omitted(). - **auto_close_bot** (bool) - Optional - Close bot session when polling stops. Default: True. - **drop_pending_updates** (bool) - Optional - Skip updates older than the poll start time. Default: False. - **clear_subscriptions** (bool) - Optional - Unsubscribe all webhooks before polling (else logs a warning if any exist). Default: False. - **workflow_data** (Any) - Optional - Additional workflow data passed to handlers. ### Response #### Success Response - **None** - Returns None. ### Request Example ```python from maxo import Bot, Dispatcher from maxo.types import MessageCreated bot = Bot("TOKEN") dp = Dispatcher() @dp.message_created() async def echo(message: MessageCreated) -> None: await message.answer(message.text or "пусто") dp.run_polling(bot) # sync entry that blocks until KeyboardInterrupt ``` ``` -------------------------------- ### Magic Filter usage example — MagicFilter and MagicData Source: https://github.com/k1rl3s/maxo Both classes subclass `BaseFilter`, so `&`, `|`, `~` composition works as usual (see filters.md). ```python from magic_filter import F from maxo.integrations.magic_filter import MagicFilter from maxo.types import MessageCallback @dp.message_callback(MagicFilter(F.payload == "click_me")) async def on_click(callback: MessageCallback) -> None: await callback.callback_answer("Нажато!") @dp.message_created(MagicData(F.update.message.body.text.startswith("/"), result_key="is_cmd")) async def cmd_like(message, is_cmd: bool) -> None: ... ``` -------------------------------- ### GET /subscriptions Source: https://github.com/k1rl3s/maxo Retrieves current subscriptions. Returns a GetSubscriptionsResult object. ```APIDOC ## GET /subscriptions ### Description Retrieves current subscriptions. ### Method GET ### Endpoint /subscriptions ### Response #### Success Response (200) - **GetSubscriptionsResult** (object) - Subscription information. ``` -------------------------------- ### GET /messages Source: https://github.com/k1rl3s/maxo Retrieves a list of messages. Returns a MessageList object. ```APIDOC ## GET /messages ### Description Retrieves a list of messages. ### Method GET ### Endpoint /messages ### Response #### Success Response (200) - **MessageList** (object) - List of messages. ``` -------------------------------- ### Using SyncFilter with message_created handler Source: https://github.com/k1rl3s/maxo Example of using SyncFilter to handle a message with text exactly 'ping', responding with 'pong'. ```python from maxo.routing.filters import SyncFilter from maxo.types import MessageCreated @dp.message_created(SyncFilter(lambda m: (m.text or "") == "ping")) async def on_ping(message: MessageCreated) -> None: await message.answer("pong") ``` -------------------------------- ### GET /videos/{video_token} Source: https://github.com/k1rl3s/maxo Retrieves details of a video attachment. Returns a VideoAttachmentDetails object. ```APIDOC ## GET /videos/{video_token} ### Description Retrieves details of a video attachment. ### Method GET ### Endpoint /videos/{video_token} ### Parameters #### Path Parameters - **video_token** (string) - Required - The token of the video. ### Response #### Success Response (200) - **VideoAttachmentDetails** (object) - Video attachment details. ``` -------------------------------- ### FSMContext Source: https://github.com/k1rl3s/maxo Provides methods to get and set the current state of the finite state machine. ```APIDOC ## FSMContext ### Description Provides methods to get and set the current state of the finite state machine. ### Methods - **set_state(state: State) -> None** - Sets the current state. - **get_state() -> str** - Returns the current state as a fully qualified string. ### Example ```python await fsm_context.set_state(Form.age) state = await fsm_context.get_state() # "Form:age" ``` ``` -------------------------------- ### TextInput usage example with on_success handler Source: https://github.com/k1rl3s/maxo Shows a TextInput widget asking for a name, with an async on_success handler that switches to the Main.age state in edit mode. The TextInput has id="name" and is placed in a Window with a Const prompt and state Main.name. ```python from maxo.dialogs.widgets.input import TextInput async def on_name(message, widget, manager: DialogManager, name: str) -> None: await manager.switch_to(Main.age, show_mode=ShowMode.EDIT) Window( Const("Ваше имя?"), TextInput(id="name", on_success=on_name), state=Main.name, ) ``` -------------------------------- ### LogMiddleware Source: https://github.com/k1rl3s/maxo An example middleware that logs the update type for MessageCreated updates. It demonstrates how to define and register a custom middleware on a router observer. ```APIDOC ## LogMiddleware ### Description An example middleware that logs the update type for MessageCreated updates. It demonstrates how to define and register a custom middleware on a router observer. ### Method `__call__` ### Parameters - `update` (MessageCreated) - The update object. - `ctx` (Ctx) - The context object. - `next` (callable) - The next middleware/handler in the chain. ### Returns - `None` - The middleware does not return a value. ### Example ```python from maxo import BaseMiddleware, Ctx from maxo.types import MessageCreated class LogMiddleware(BaseMiddleware[MessageCreated]): async def __call__(self, update: MessageCreated, ctx: Ctx, next) -> None: print("update:", update.update_type) return await next(ctx) router.message_created.middleware(LogMiddleware()) # inner router.message_created.outer_middleware(LogMiddleware()) # outer, aiogram-style ``` ``` -------------------------------- ### Bot non-bound methods Source: https://github.com/k1rl3s/maxo Core lifecycle and utility methods for the Bot client. Includes context manager support, start/close, method invocation, download, resumable upload, and subscription clearing. The context method calls start() then close() if auto_close is True. ```python @asynccontextmanager async def context(self, auto_close: bool = True) -> AsyncIterator[Self] async def start(self) -> None async def close(self) -> None async def call_method(self, method: BaseMethod[ResponseType]) -> ResponseType async def silent_call_method(self, method: MaxoMethod[_MethodResultT]) -> None async def __aenter__(self) -> Self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None async def download( self, url: str | AttachmentPayload, destination: BinaryIO | pathlib.Path | str | None = None, timeout: float | ClientTimeout = 30, chunk_size: int = 65536, seek: bool = True, ) -> BinaryIO | None async def upload_media_resumable( self, upload_url: str, file: InputFile, size: int | None = None, ) -> UploadMediaResult | None async def clear_subscriptions( self, active_urls: str | Iterable[str] | None = None, ) -> ClearSubscriptionsResult ``` -------------------------------- ### LongPolling.start Source: https://github.com/k1rl3s/maxo Asynchronously starts the long polling loop. It acquires an internal lock, feeds startup events, opens the bot context, and polls in a loop, dispatching each update to its own task. ```APIDOC ## LongPolling.start ### Description Asynchronously starts the long polling loop. It acquires an internal lock, feeds startup events, opens the bot context, and polls in a loop, dispatching each update to its own task. ### Method start ### Signature ```python async def start(self, bot: Bot, ...same signature...) -> None ``` ### Parameters - **bot** (Bot) - Required - The bot instance to poll updates from. - **timeout** (Omittable[int]) - Optional - Poll timeout (server long-poll seconds). Default: 30. - **limit** (Omittable[int]) - Optional - Max updates per poll response. Default: 100. - **marker** (Omittable[int | None]) - Optional - Start cursor. Default: Omitted(). - **types** (Omittable[Sequence[str]]) - Optional - Whitelist; empty/omitted → `collect_used_updates(dispatcher)`. Default: Omitted(). - **auto_close_bot** (bool) - Optional - Close bot after polling stops. Default: True. - **drop_pending_updates** (bool) - Optional - Skip updates with `timestamp < poll start`. Default: False. - **clear_subscriptions** (bool) - Optional - Remove webhook subscriptions before polling. Default: False. - **workflow_data** (Any) - Optional - Injected into `dispatcher.workflow_data`. ### Returns None ### Request Example ```python from maxo import Bot, Dispatcher from maxo.transport.long_polling import LongPolling bot = Bot("TOKEN") dp = Dispatcher() polling = LongPolling(dp) # custom backoff via BackoffConfig await polling.start(bot, timeout=25, drop_pending_updates=True) ``` ``` -------------------------------- ### create_startapp_link Source: https://github.com/k1rl3s/maxo Creates a Telegram deep link with `startapp` payload. Payload must contain only `A-Z a-z 0-9 _ -` or `ValueError` is raised. ```APIDOC ## create_startapp_link ### Description Creates a deep link for the `startapp` parameter. Payloads may contain only `A-Z a-z 0-9 _ -` — otherwise `ValueError` (pass `encode=True`); too-long payloads raise `ValueError` with the limit. ### Signature `def create_startapp_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. ``` -------------------------------- ### Using State and StatesGroup with FSMContext Source: https://github.com/k1rl3s/maxo Shows how to define a StatesGroup with State attributes, create a child group, and use FSMContext to set and get the current state. The get_state() returns the fully qualified state string like 'Form:age'. NestedForm.get_root() returns the root group Form. ```python from maxo.fsm import State, StatesGroup class Form(StatesGroup): name = State() age = State() class NestedForm(Form): # child group confirm = State() await fsm_context.set_state(Form.age) state = await fsm_context.get_state() # "Form:age" assert NestedForm.get_root() is Form ``` -------------------------------- ### LaunchMode, ShowMode, StartMode, and UnsetId enums Source: https://github.com/k1rl3s/maxo Defines the enums for dialog launch, show, and start modes, plus a sentinel for unset IDs. These control dialog behavior and transitions. ```python class LaunchMode(Enum): # STANDARD / ROOT / EXCLUSIVE / SINGLE_TOP STANDARD = "standard" ROOT = "root" EXCLUSIVE = "exclusive" SINGLE_TOP = "single_top" ``` ```python class ShowMode(Enum): # AUTO / EDIT / SEND / DELETE_AND_SEND / NO_UPDATE AUTO = "auto"; EDIT = "edit"; SEND = "send" DELETE_AND_SEND = "delete_and_send"; NO_UPDATE = "no_update" ``` ```python class StartMode(Enum): # NORMAL / RESET_STACK / NEW_STACK NORMAL = "NORMAL"; RESET_STACK = "RESET_STACK"; NEW_STACK = "NEW_STACK" ``` ```python class UnsetId(Enum): UNSET = "UNSET" ``` -------------------------------- ### Window.__init__ Source: https://github.com/k1rl3s/maxo Initializes a Window instance with widgets, state, and various configuration options. This constructor is part of the maxo.dialogs.window.Window class, which users can instantiate directly. ```APIDOC ## Window.__init__ ### Description Initializes a Window instance with widgets, state, and various configuration options. This constructor is part of the maxo.dialogs.window.Window class, which users can instantiate directly. ### Method Constructor ### Signature ```python Window( *widgets: WidgetSrc, state: State, getter: GetterVariant = None, on_process_result: OnResultEvent | None = None, markup_factory: MarkupFactory = _DEFAULT_MARKUP_FACTORY, parse_mode: Omittable[TextFormat | None] = Omitted(), protect_content: bool | None = None, two_step_media_edit: bool = False, preview_add_transitions: list[Keyboard] | None = None, preview_data: GetterVariant = None, ) -> None ``` ### Parameters - **widgets** (WidgetSrc) - Required - `Text | Keyboard | Media | BaseInput | LinkPreview` (singles or groups); classified into `self.text`, `self.keyboard`, `self.on_message`, `self.media`, `self.link_preview` - **state** (State) - Required - FSM state this window is shown for - **getter / preview_data** (GetterVariant) - Optional - Extra window data sources - **on_process_result** (OnResultEvent | None) - Optional - Called when a sub-dialog returns while this window is current - **markup_factory** (MarkupFactory) - Optional - Converts `MarkupVariant` into a `NewMessage.keyboard`; a custom factory is required for game media or exotic keyboards - **parse_mode** (Omittable[TextFormat | None]) - Optional - Text format for the rendered message - **protect_content** (bool | None) - Optional - Forwarded to the send call (deprecated by MAX; kept for compatibility) - **two_step_media_edit** (bool) - Optional - Edit media and text in two steps (workaround for MAX media-edit race) - **preview_add_transitions** (list[Keyboard] | None) - Optional - Extra transition buttons injected only in previews ### Returns None ``` -------------------------------- ### RedisStorage and RedisEventIsolation Source: https://github.com/k1rl3s/maxo Redis-backed storage and event isolation. Requires `pip install maxo[redis]`; otherwise import raises an error with a note. RedisStorage supports TTL, custom JSON serialization, and a from_url classmethod. RedisEventIsolation uses redis.asyncio.lock.Lock with configurable lock_kwargs (default timeout 60). ```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 @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 ``` -------------------------------- ### setup_jinja Source: https://github.com/k1rl3s/maxo Configures the global Jinja environment used when `JINJA_ENV_FIELD` is absent. ```APIDOC ## setup_jinja ### Description Configures the global Jinja environment used when `JINJA_ENV_FIELD` is absent. ### Signature `setup_jinja(env, *, add_maxo_extensions=True, enable_async=True, autoescape=True, default_env=None, **kwargs)` ### Parameters - `env` - The Jinja environment to configure. - `add_maxo_extensions` (bool) - Optional - Whether to add Maxo extensions. Defaults to True. - `enable_async` (bool) - Optional - Whether to enable async support. Defaults to True. - `autoescape` (bool) - Optional - Whether to enable autoescaping. Defaults to True. - `default_env` - Optional - The default environment to use. - `**kwargs` - Additional keyword arguments. ``` -------------------------------- ### Using callback_answer flag with CallbackAnswer Source: https://github.com/k1rl3s/maxo Example of using the `callback_answer` flag and `CallbackAnswer` to suppress the automatic answer. The handler receives a `CallbackAnswer` instance and calls `disable()` to prevent the auto-answer. ```python from maxo.utils.callback_answer import CallbackAnswer, CallbackAnswerMiddleware @dp.message_callback(flags.callback_answer(notification="Обрабатываю…")) async def handler(callback: MessageCallback, callback_answer: CallbackAnswer) -> None: await callback_answer.disable() # suppress the auto-answer ``` -------------------------------- ### ChatActionSender and ChatActionMiddleware signatures Source: https://github.com/k1rl3s/maxo Defines constants and class signatures for chat action utilities. ChatActionSender periodically calls bot.send_action in a background task; starting twice raises RuntimeError("Отправка действий уже запущена"). The middleware respects the chat_action handler flag and resolves chat_id from UpdateContext or the update itself. ```python DEFAULT_INTERVAL: Final = 5.0 DEFAULT_INITIAL_SLEEP: Final = 0.0 CHAT_ACTION_KEY: Final = "chat_action" class ChatActionSender: def __init__(self, *, bot: Bot, chat_id: int, action: SenderAction | str = SenderAction.TYPING_ON, interval: float = DEFAULT_INTERVAL, initial_sleep: float = DEFAULT_INITIAL_SLEEP) -> None running: bool async def __aenter__(self) -> Self / __aexit__ @classmethod typing_on / sending_photo / sending_video / sending_audio / sending_file / mark_seen (cls, chat_id: int, bot: Bot, interval=5.0, initial_sleep=0.0) -> "ChatActionSender" class ChatActionMiddleware(BaseMiddleware[BaseUpdate]): def __init__(self, action: SenderAction | str = SenderAction.TYPING_ON, interval: float = DEFAULT_INTERVAL, initial_sleep: float = DEFAULT_INITIAL_SLEEP) -> None ```