### Bot Configuration with Proxy using aiomax and aiohttp Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md Shows how to configure an aiomax bot to use a proxy server for its network requests. This example includes setting the proxy URL and authentication details using aiohttp. Requires aiomax, aiohttp, and asyncio. ```python import aiomax import aiohttp import asyncio bot = aiomax.Bot('TOKEN') proxy_url = 'http://url:port' proxy_auth = aiohttp.BasicAuth("login", "pasword") # Аутенфикация прокси ``` -------------------------------- ### Python: Handle Bot Start Event using aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt Responds when the bot is started, optionally sending a welcome message based on a start parameter from a link. This event handler requires the aiomax library. ```python import aiomax bot = aiomax.Bot('TOKEN') # Пользователь запустил бота @bot.on_bot_start() async def bot_started(payload: aiomax.BotStartPayload): # payload.payload содержит start-параметр из ссылки if payload.payload: await payload.send(f"Вы пришли по ссылке: {payload.payload}") else: await payload.send(f"Добро пожаловать, {payload.user.name}!") ``` -------------------------------- ### FSM for User Input (Name and Surname) with aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md Demonstrates using aiomax's Finite State Machine (FSM) to guide users through a multi-step input process, collecting their name and surname. Requires aiomax and fsm modules. ```python import aiomax from aiomax import fsm bot = aiomax.Bot('TOKEN') # Запуск бота пользователем @bot.on_bot_start() async def start(pd: aiomax.BotStartPayload, cursor: fsm.FSMCursor): await pd.send("Как Вас зовут?") cursor.change_state('name') # Изменения состояние # Ввод имени @bot.on_message(aiomax.filters.state('name')) async def write_name(message: aiomax.Message, cursor: fsm.FSMCursor): await message.reply("Напишите свою фамилию") cursor.change_state('surname') # Изменения состояние cursor.change_data({'name': message.content}) # Добавление имени в данные # Ввод фамилии @bot.on_message(aiomax.filters.state('surname')) async def write_surname(message: aiomax.Message, cursor: fsm.FSMCursor): name = cursor.get_data()['name'] # Получение имени из данных surname = message.content await message.reply(f"Здравствуйте, {name} {surname}") cursor.clear() # Очищение состояния и данных пользователя bot.run() ``` -------------------------------- ### Bot.start_polling / Bot.run Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Methods to initialize and start the bot's long polling process. ```APIDOC ## GET /Bot/start_polling ### Description Starts the long polling process for the bot. Can be used with an optional aiohttp session. ### Method GET ### Endpoint /Bot/start_polling --- ## GET /Bot/run ### Description Shorthand method to start the bot using asyncio.run(Bot.start_polling()). ### Method GET ### Endpoint /Bot/run ``` -------------------------------- ### Send and Receive Sticker Codes (Python) Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md This example demonstrates sending a sticker by its code and replying with the code of any sticker received by the bot. It uses `aiomax.StickerAttachment` to send a sticker and iterates through message attachments to find and send sticker codes. ```python import aiomax bot = aiomax.Bot('YOUR_BOT_TOKEN') # Command to send a sticker with a specific code @bot.on_command('send_sticker') async def sticker(ctx: aiomax.CommandContext): # Example sticker code: '2613f6' await ctx.reply(attachments=[ aiomax.StickerAttachment('2613f6') ]) # Handler to reply with the code of any received sticker @bot.on_message() async def get_code(message: aiomax.Message): for attachment in message.body.attachments: if attachment.type == 'sticker': await message.reply(f"Sticker code: {attachment.code}") return # Optional: reply if no sticker was found # await message.reply("I didn't receive a sticker.") bot.run() ``` -------------------------------- ### Implement Full-Featured Bot with FSM and Keyboards Source: https://context7.com/dpnspn/aiomax/llms.txt A complete example showcasing bot initialization, command registration, custom keyboards, and Finite State Machine (FSM) for multi-step interactions like feedback collection. ```python import aiomax from aiomax import filters from aiomax.fsm import FSMCursor from aiomax.buttons import KeyboardBuilder, CallbackButton, LinkButton bot = aiomax.Bot('TOKEN', default_format='markdown') # Состояния FSM class States: FEEDBACK = "feedback" # === Настройка при запуске === @bot.on_ready() async def on_ready(): await bot.patch_me(commands=[ aiomax.BotCommand('start', 'Начать'), aiomax.BotCommand('help', 'Помощь'), aiomax.BotCommand('feedback', 'Обратная связь'), ]) print(f"Бот @{bot.username} запущен!") # === Приветствие === @bot.on_bot_start() async def welcome(payload: aiomax.BotStartPayload): kb = KeyboardBuilder() kb.row(CallbackButton("Помощь", "help")) kb.row(LinkButton("Наш сайт", "https://example.com")) await payload.send( f"Привет, **{payload.user.name}**!\n\n" "Я демонстрационный бот на aiomax.", keyboard=kb ) # === Команды === @bot.on_command('help', aliases=['h', 'помощь']) async def help_cmd(ctx: aiomax.CommandContext): await ctx.reply( "**Доступные команды:**\n\n" "/start - Начать\n" "/help - Эта справка\n" "/feedback - Написать отзыв" ) @bot.on_command('feedback') async def feedback_start(ctx: aiomax.CommandContext, cursor: FSMCursor): cursor.change_state(States.FEEDBACK) kb = KeyboardBuilder() kb.row(CallbackButton("Отмена", "cancel_feedback", intent="negative")) await ctx.reply( "Напишите ваш отзыв или предложение:", keyboard=kb ) # === FSM обработчик === @bot.on_message(filters.state(States.FEEDBACK)) async def receive_feedback(message: aiomax.Message, cursor: FSMCursor): feedback_text = message.content # Здесь можно сохранить отзыв в БД print(f"Отзыв от {message.sender.name}: {feedback_text}") cursor.clear() await message.reply("Спасибо за отзыв! Мы обязательно его рассмотрим.") # === Callback обработчики === @bot.on_button_callback(lambda cb: cb.payload == "help") async def help_callback(cb: aiomax.Callback): await cb.answer(notification="Показываю справку...") await cb.send( "**Доступные команды:**\n\n" "/start - Начать\n" "/help - Эта справка\n" "/feedback - Написать отзыв" ) @bot.on_button_callback(lambda cb: cb.payload == "cancel_feedback") async def cancel_feedback(cb: aiomax.Callback, cursor: FSMCursor): cursor.clear() await cb.answer( notification="Отменено", text="Отправка отзыва отменена." ) ``` -------------------------------- ### BotStartPayload.send Source: https://github.com/dpnspn/aiomax/blob/main/docs/Типы.md Sends a message to the chat where the bot was initiated via the 'Start' button. ```APIDOC ## POST /bot/start/send ### Description Sends a message to the chat in which the bot was started. Used within the context of the `Bot.on_bot_start` decorator. ### Method POST ### Endpoint /bot/start/send ### Parameters #### Request Body - **text** (str) - Required - Message text (max 4000 chars) - **format** (str) - Optional - Format type: 'html', 'markdown', or 'default' - **notify** (bool) - Optional - Whether to notify participants (default: True) - **disable_link_preview** (bool) - Optional - Disable link previews (default: False) - **keyboard** (object) - Optional - Inline keyboard structure - **attachments** (list) - Optional - List of attachments ### Response #### Success Response (200) - **message** (object) - The sent message object ``` -------------------------------- ### Initialize and Run an aiomax Bot Source: https://context7.com/dpnspn/aiomax/llms.txt This snippet demonstrates how to initialize an aiomax Bot with an access token and various settings. It also shows how to define event handlers for bot readiness and incoming messages, and finally, how to run the bot to start polling for updates. ```python import aiomax # Создание бота с токеном и настройками bot = aiomax.Bot( access_token='YOUR_TOKEN', # Токен из https://max.ru/masterbot command_prefixes='/', # Префикс команд (по умолчанию '/') mention_prefix=True, # Реагировать на упоминание бота case_sensitive=True, # Чувствительность к регистру команд default_format='markdown', # Формат сообщений по умолчанию max_messages_cached=10000 # Максимум кешированных сообщений ) @bot.on_ready() async def on_ready(): print(f"Бот запущен: @{bot.username} ({bot.name})") @bot.on_message() async def echo(message: aiomax.Message): await message.reply(message.body.text) # Запуск бота (блокирующий вызов) bot.run() ``` -------------------------------- ### Simple Echo Bot using aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md A basic bot that echoes back any text message it receives. It requires the aiomax library and a bot token. ```python import aiomax import asyncio bot = aiomax.Bot('TOKEN') @bot.on_message() async def echo(message: aiomax.Message): await message.reply(message.body.text) bot.run() ``` -------------------------------- ### Global Message Filters with Routers in aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md Illustrates the use of global message filters within routers. Messages starting with '$' are routed to specific handlers, while other messages are handled by a general bot-level handler. Requires aiomax. ```python import aiomax bot = aiomax.Bot('TOKEN') command_router = aiomax.Router() command_router.add_message_filter(aiomax.filters.startswith('$')) # эти функции сработают только если сообщение начинается с '$' @command_router.on_message() async def echo(message: aiomax.Message): await message.reply(message.content) @command_router.on_message() async def name(message: aiomax.Message): await message.reply(message.sender.name) # эта функция сработает всегда @bot.on_message() async def echo(message: aiomax.Message): await message.reply(message.content) bot.add_router(command_router) bot.run() ``` -------------------------------- ### Run aiomax Bot Source: https://context7.com/dpnspn/aiomax/llms.txt This snippet provides the standard Python entry point to run the aiomax bot. It checks if the script is executed directly and then calls the `bot.run()` method to start the bot's event loop. ```python if __name__ == "__main__": bot.run() ``` -------------------------------- ### Organize Bot Handlers with aiomax Routers Source: https://context7.com/dpnspn/aiomax/llms.txt This example shows how to use aiomax Routers to organize bot handlers into modules. Routers allow for applying filters to groups of handlers and improve code maintainability. It requires the aiomax library. ```python # admin_router.py import aiomax router = aiomax.Router() ADMIN_IDS = [123456, 789012] # Глобальный фильтр для всех обработчиков роутера router.add_message_filter(lambda m: m.user_id in ADMIN_IDS) @router.on_command('ban') async def ban_user(ctx: aiomax.CommandContext): user_id = ctx.message.resolve_mention() if user_id: await ctx.bot.kick_member(ctx.message.recipient.chat_id, user_id, block=True) await ctx.reply("Пользователь заблокирован") @router.on_command('stats') async def admin_stats(ctx: aiomax.CommandContext): chats = [] async for chat in ctx.bot.get_chats(): chats.append(chat) await ctx.reply(f"Бот в {len(chats)} чатах") ``` ```python # echo_router.py import aiomax router = aiomax.Router() @router.on_message() async def echo(message: aiomax.Message): await message.reply(message.content) ``` ```python # main.py import aiomax import admin_router import echo_router bot = aiomax.Bot('TOKEN') # Подключение роутеров bot.add_router(admin_router.router) bot.add_router(echo_router.router) # Обработчики бота выполняются вместе с обработчиками роутеров @bot.on_ready() async def ready(): print("Бот запущен") bot.run() ``` -------------------------------- ### Modular Bot Structure with Routers in aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md Demonstrates how to split bot logic into multiple files using aiomax Routers. An 'echo.py' file contains the router for echo functionality, and 'main.py' imports and adds this router to the main bot instance. Requires aiomax. ```python import aiomax router = aiomax.Router() @router.on_message() async def echo(message: aiomax.Message): await message.reply(message.content) ``` ```python import aiomax import echo bot = aiomax.Bot('TOKEN') bot.add_router(echo.router) bot.run() ``` -------------------------------- ### Upload and Send Image File (Python) Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md This code snippet shows how to upload an image file to a Telegram server and send it as an attachment using the `aiomax` library. It defines a command handler that uploads 'image.png' and then sends it back to the user. ```python import aiomax bot = aiomax.Bot('YOUR_BOT_TOKEN') @bot.on_command('send_photo') async def send_photo(ctx: aiomax.CommandContext): # Ensure 'image.png' exists in the same directory or provide a full path try: attachment = await bot.upload_image('image.png') await ctx.send('Here is the photo:', attachments=attachment) except FileNotFoundError: await ctx.send("Error: 'image.png' not found. Please make sure the file exists.") except Exception as e: await ctx.send(f"An error occurred: {e}") bot.run() ``` -------------------------------- ### Get Chat Administrators Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Fetches a list of administrators for a given chat. Returns a list of `User` objects. ```python admins = await bot.get_admins(chat_id=123456789) ``` -------------------------------- ### Manage message lifecycle and formatting in aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt Covers sending, editing, deleting, and formatting messages using Markdown or HTML. Includes examples of using CommandContext and KeyboardBuilder for interactive bot responses. ```python import aiomax from aiomax.buttons import KeyboardBuilder, CallbackButton bot = aiomax.Bot('TOKEN', default_format='markdown') @bot.on_command('send') async def send_examples(ctx: aiomax.CommandContext): msg = await ctx.send("Простое сообщение") await ctx.reply("Это ответ на команду") await bot.send_message(text="Сообщение в чат", chat_id=ctx.message.recipient.chat_id, format='markdown') @bot.on_command('format') async def formatting(ctx: aiomax.CommandContext): await ctx.send("**Жирный** и *курсив*", format='markdown') await ctx.send("Жирный и курсив", format='html') @bot.on_command('edit') async def edit_example(ctx: aiomax.CommandContext): msg = await ctx.send("Исходное сообщение") await msg.edit(text="Отредактированное сообщение") @bot.on_command('delete') async def delete_example(ctx: aiomax.CommandContext): msg = await ctx.send("Удаление через 3 секунды") import asyncio await asyncio.sleep(3) await msg.delete() @bot.on_command('keyboard') async def with_keyboard(ctx: aiomax.CommandContext): kb = KeyboardBuilder() kb.row(CallbackButton("Кнопка", "payload")) await ctx.send("Сообщение с клавиатурой", keyboard=kb) ``` -------------------------------- ### Simple Counter Bot with Reset using aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md A bot that implements a simple tap counter. It responds to a 'tap' command by displaying the current count and buttons to increment or reset the counter. Uses callback buttons for interaction. Requires aiomax and asyncio. ```python import aiomax import asyncio bot = aiomax.Bot('TOKEN') taps = 0 # Команда отправляющая сообщение с кнопками @bot.on_command('tap') async def tap_command(ctx: aiomax.CommandContext): kb = aiomax.buttons.KeyboardBuilder() kb.add(aiomax.buttons.CallbackButton('Тап', 'tap')) kb.row(aiomax.buttons.CallbackButton('Сбросить', 'reset')) await ctx.reply(f'Тапов: {taps}', keyboard=kb) # Обработчик кнопки "Тап" (увеличение счетчика) @bot.on_button_callback(lambda data: data.payload == 'tap') async def tap(cb: aiomax.Callback): global taps taps += 1 await cb.answer(text=f'Тапов: {taps}', format='markdown') # Обработчик кнопки "Сбросить" (сброс счетчика) @bot.on_button_callback(lambda data: data.payload == 'reset') async def reset(cb: aiomax.Callback): global taps taps = 0 await cb.answer('Вы сбросили все тапы!', text=f'Тапов: {taps}') bot.run() ``` -------------------------------- ### Fetch and Display Country by IP Address (Python) Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md This snippet demonstrates how to fetch the user's country based on their IP address using an external API. It utilizes the `aiomax` library for bot interactions and `aiohttp` for making HTTP requests. The function sends the detected country name back to the user. ```python import aiomax import aiohttp import asyncio # Assuming proxy_url and proxy_auth are defined elsewhere # proxy_url = "http://user:password@host:port" # proxy_auth = aiohttp.BasicAuth('user', 'password') bot = aiomax.Bot('YOUR_BOT_TOKEN') @bot.on_command() async def example(ctx: aiomax.CommandContext): # Using aiohttp.ClientSession within the command handler if not globally initialized async with aiohttp.ClientSession() as session: response = await session.get("http://ip-api.com/json/") data = await response.json() await ctx.send(f"Country: {data.get('country')}") async def main(): # If you need to use a proxy for the bot's session itself: # proxy_session = aiohttp.ClientSession(proxy=proxy_url, proxy_auth=proxy_auth) # await bot.start_polling(proxy_session) # else, use the default session: await bot.start_polling() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Handle Bot Add Event in aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt This snippet shows how to use the `on_bot_add` decorator to send an introductory message when the bot is added to a chat. It utilizes `ChatMembershipPayload` to get the chat ID and sends a plain text message. ```python @bot.on_bot_add() async def bot_added(payload: aiomax.ChatMembershipPayload): await bot.send_message( "Привет! Спасибо, что добавили меня.\n" "Используйте /help для списка команд.", chat_id=payload.chat_id ) ``` -------------------------------- ### Get List of Chats Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Fetches a list of chats the bot is a member of. It supports pagination using `count` and `marker` parameters. Returns a `Chat` object. ```python chats = await bot.get_chats(count=50, marker=12345) ``` -------------------------------- ### Create and Register a Router in aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Роутеры.md Demonstrates how to instantiate a Router, define event handlers using decorators, and attach the router to a Bot instance. This approach is functionally equivalent to defining handlers directly on the Bot object. ```python import aiomax bot = aiomax.Bot('TOKEN') router = aiomax.Router() @router.on_message() async def echo(message: aiomax.Message): await message.reply(message.content) bot.add_router(router) bot.run() ``` -------------------------------- ### Bot Initialization and Configuration Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Details on how to initialize the Bot class and its configuration options. ```APIDOC ## Bot Class Initialization ### Description Initializes the Bot class, which serves as the main router for bot interactions. This class allows you to manage the bot's behavior and connect to the AIOMAX platform. ### Method `Bot(access_token: str, command_prefixes: str | List[str] = '/', mention_prefix: bool = True, case_sensitive: bool = True, default_format: Literal['markdown', 'html'] | None = None, max_messages_cached: int = 10000, debug: bool = False)` ### Parameters - **access_token** (str) - Required - The bot token obtained from [@MasterBot](https://max.ru/masterbot). - **command_prefixes** (str | List[str]) - Optional - The prefix or list of prefixes for bot commands. Defaults to '/'. - **mention_prefix** (bool) - Optional - Whether the bot should respond to commands prefixed with its username (e.g., `@username /command`). Defaults to `True`. If `False`, the bot may not function correctly in groups. - **case_sensitive** (bool) - Optional - Whether command matching should be case-sensitive. Defaults to `True`. - **default_format** ('markdown' | 'html' | None) - Optional - The default markup language to use if not specified in the request. Defaults to `None`. - **max_messages_cached** (int) - Optional - The maximum number of messages to cache. Defaults to `10000`. Set to `0` to disable caching. Caching is used for features like `Bot.on_message_edit`. - **debug** (bool) - Optional - If `True`, provides more detailed error information during polling. Defaults to `False`. ### Related - [Examples](Примеры) - [Routers](Роутеры) ``` -------------------------------- ### Chat Management Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md APIs for retrieving lists of chats, getting specific chat details, and managing chat memberships. ```APIDOC ## Get Chats ### Description Retrieves a list of chats the bot is a member of. ### Method `Bot.get_chats(count: int | None = None, marker: int | None = None) -> Chat` ### Parameters - **count** (int) - Optional - The maximum number of chats to return per page. - **marker** (int) - Optional - A marker for pagination, obtained from a previous call to `get_chats`. ### Response - **Success Response (200)** - Returns a `Chat` object containing a list of chats. ## Get Chat by Link ### Description Retrieves a specific chat object using its invite link. ### Method `Bot.chat_by_link(link: str)` ### Parameters - **link** (str) - Required - The invite link of the chat. ### Response - **Success Response (200)** - Returns a `Chat` object for the specified chat. ## Get Chat by ID ### Description Retrieves a specific chat object using its unique ID. ### Method `Bot.get_chat(chat_id: int) -> Chat` ### Parameters - **chat_id** (int) - Required - The ID of the chat. ### Response - **Success Response (200)** - Returns a `Chat` object for the specified chat. ## Leave Chat ### Description Causes the bot to leave a specified chat. ### Method `Bot.leave_chat(chat_id: int)` ### Parameters - **chat_id** (int) - Required - The ID of the chat to leave. ### Response - **Success Response (200)** - Indicates the bot has successfully left the chat. ``` -------------------------------- ### Get Chat by ID Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Fetches a specific chat object using its unique ID. Requires the chat's ID as input. ```python chat = await bot.get_chat(chat_id=123456789) ``` -------------------------------- ### Get Chat by Link Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Retrieves a specific chat object using its public link. Requires the chat's link as input. ```python chat = await bot.chat_by_link('https://t.me/joinchat/examplelink') ``` -------------------------------- ### Create Keyboards and Buttons Source: https://context7.com/dpnspn/aiomax/llms.txt Explains how to use the KeyboardBuilder class to create various button types including Callback, Link, Geolocation, Contact, and WebApp buttons. It also demonstrates grid layouts and dynamic row management. ```python import aiomax from aiomax.buttons import ( KeyboardBuilder, CallbackButton, LinkButton, GeolocationButton, ContactButton, ChatButton, MessageButton, WebAppButton ) bot = aiomax.Bot('TOKEN') @bot.on_command('buttons') async def show_all_buttons(ctx: aiomax.CommandContext): kb = KeyboardBuilder() kb.row( CallbackButton("Обычная", "default", intent="default"), CallbackButton("Позитив", "positive", intent="positive"), CallbackButton("Негатив", "negative", intent="negative") ) kb.row(LinkButton("Открыть сайт", "https://max.ru")) kb.row(GeolocationButton("Отправить местоположение", quick=False)) kb.row(ContactButton("Поделиться контактом")) kb.row(ChatButton( text="Создать чат", title="Новый чат", description="Описание чата", payload="chat_created" )) kb.row(MessageButton("Отправить приветствие")) await ctx.send("Все типы кнопок:", keyboard=kb) @bot.on_command('grid') async def grid_keyboard(ctx: aiomax.CommandContext): kb = KeyboardBuilder() buttons = [CallbackButton(str(i), f"num_{i}") for i in range(1, 10)] kb.table(3, *buttons) kb.row(CallbackButton("0", "num_0")) await ctx.send("Клавиатура 3x3:", keyboard=kb) @bot.on_command('dynamic') async def dynamic_keyboard(ctx: aiomax.CommandContext): kb = KeyboardBuilder() kb.add(CallbackButton("A", "a")) kb.add(CallbackButton("B", "b")) kb.row(CallbackButton("C", "c"), CallbackButton("D", "d")) await ctx.send("Динамическая клавиатура:", keyboard=kb) bot.run() ``` -------------------------------- ### Get Pinned Message Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Retrieves the pinned message in a specific chat. Returns a `Message` object if a message is pinned, otherwise returns `None`. ```python pinned_message = await bot.get_pin(chat_id=123456789) ``` -------------------------------- ### Get Bot Information Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Retrieves the current bot's profile information. This method returns a `User` object containing details about the bot. ```python bot_info = await bot.get_me() ``` -------------------------------- ### Get Message by ID Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Retrieves message information using its unique ID. Returns a Message object. This is useful for fetching details of a specific message. ```python Bot.get_message(id: str) -> Message ``` -------------------------------- ### Initialize FSM for Dialogues Source: https://context7.com/dpnspn/aiomax/llms.txt Initializes the Finite State Machine (FSM) module for managing multi-step user dialogues. This snippet sets up the basic bot structure required for stateful interactions. ```python import aiomax from aiomax import filters from aiomax.fsm import FSMCursor bot = aiomax.Bot('TOKEN') ``` -------------------------------- ### Initialize aiomax Bot Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Initializes the Bot class with essential parameters like access token and command prefixes. It also allows configuration of mention prefixes, case sensitivity, default message format, message caching, and debug mode. ```python from aiomax.bot import Bot bot = Bot(access_token='YOUR_ACCESS_TOKEN', command_prefixes=['!', '/'], mention_prefix=True, case_sensitive=False, default_format='markdown', max_messages_cached=5000, debug=True) ``` -------------------------------- ### Get Bot's Membership Info Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Retrieves information about the bot's membership in a specific chat. Returns a `User` object representing the bot in that chat. ```python membership_info = await bot.my_membership(chat_id=123456789) ``` -------------------------------- ### Implement Finite State Machine (FSM) with aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt This code demonstrates how to implement a Finite State Machine (FSM) using aiomax for managing conversational flows. It defines states, handles user input, stores data, and transitions between states. Dependencies include the aiomax library. ```python import aiomax from aiomax import filters # Определение состояний (можно использовать любые значения) class States: WAITING_NAME = "waiting_name" WAITING_AGE = "waiting_age" WAITING_CONFIRM = "waiting_confirm" @bot.on_bot_start() async def start(payload: aiomax.BotStartPayload, cursor: FSMCursor): await payload.send("Как вас зовут?") cursor.change_state(States.WAITING_NAME) @bot.on_message(filters.state(States.WAITING_NAME)) async def get_name(message: aiomax.Message, cursor: FSMCursor): name = message.content # Сохранение данных cursor.change_data({"name": name}) # Переход к следующему состоянию cursor.change_state(States.WAITING_AGE) await message.reply(f"Приятно познакомиться, {name}! Сколько вам лет?") @bot.on_message(filters.state(States.WAITING_AGE)) async def get_age(message: aiomax.Message, cursor: FSMCursor): try: age = int(message.content) except ValueError: await message.reply("Пожалуйста, введите число") return # Обновление данных data = cursor.get_data() data["age"] = age cursor.change_data(data) cursor.change_state(States.WAITING_CONFIRM) await message.reply( f"Имя: {data['name']}\nВозраст: {age}\n\nВсё верно? (да/нет)" ) @bot.on_message(filters.state(States.WAITING_CONFIRM)) async def confirm(message: aiomax.Message, cursor: FSMCursor): if message.content.lower() == "да": data = cursor.get_data() await message.reply(f"Регистрация завершена!\n{data}") # Очистка состояния и данных cursor.clear() elif message.content.lower() == "нет": cursor.change_state(States.WAITING_NAME) cursor.change_data({}) await message.reply("Начнём сначала. Как вас зовут?") else: await message.reply("Ответьте 'да' или 'нет'") # Команда отмены в любом состоянии @bot.on_command('cancel') async def cancel(ctx: aiomax.CommandContext, cursor: FSMCursor): state = cursor.get_state() if state: cursor.clear() await ctx.reply("Действие отменено") else: await ctx.reply("Нечего отменять") bot.run() ``` -------------------------------- ### Handle User Join Event in aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt This snippet demonstrates how to use the `on_user_add` decorator to send a welcome message when a new user joins a chat. It takes a `UserMembershipPayload` and sends a formatted Markdown message. ```python @bot.on_user_add() async def user_joined(payload: aiomax.UserMembershipPayload): await bot.send_message( f"Добро пожаловать, **{payload.user.name}**! 👋", chat_id=payload.chat_id, format='markdown' ) ``` -------------------------------- ### Python: Get Pinned Message in a Chat using aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt Retrieves the currently pinned message in a chat and displays its text content. If no message is pinned, it informs the user. This function requires the aiomax library and a bot token. ```python import aiomax bot = aiomax.Bot('TOKEN') @bot.on_command('get_pin') async def get_pinned(ctx: aiomax.CommandContext): chat_id = ctx.message.recipient.chat_id pinned = await bot.get_pin(chat_id) if pinned: await ctx.reply(f"Закреплено: {pinned.body.text}") else: await ctx.reply("Нет закреплённого сообщения") ``` -------------------------------- ### Nest Routers in aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Роутеры.md Illustrates how to create hierarchical structures by adding child routers to a parent router or the main bot instance. ```python bot = aiomax.Bot('TOKEN') router = aiomax.Router() @router.on_message() async def echo(message: aiomax.Message): await message.reply(message.content) bot.add_router(router) child_router = aiomax.Router() @child_router.on_message() async def echo_second(message: aiomax.Message): await message.reply(message.content) router.add_router(child_router) ``` -------------------------------- ### Manage Bot Metadata and Commands Source: https://context7.com/dpnspn/aiomax/llms.txt Shows how to retrieve bot info, register menu commands, update profile details like name and avatar, and list active chats. ```python @bot.on_ready() async def setup_bot(): me = await bot.get_me() commands = [aiomax.BotCommand('start', 'Начать работу'), aiomax.BotCommand('help', 'Справка')] await bot.patch_me(commands=commands) @bot.on_command('update_info') async def update_bot_info(ctx: aiomax.CommandContext): await bot.patch_me(name="New Name", description="New Description") await ctx.reply("Updated!") @bot.on_command('set_avatar') async def set_avatar(ctx: aiomax.CommandContext): photo = aiomax.ImageRequestPayload(url="https://example.com/avatar.jpg") await bot.patch_me(photo=photo) await ctx.reply("Avatar set!") ``` -------------------------------- ### Echo Bot with Chat ID Filter using aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md An echo bot that only processes messages from a specific chat ID. It uses a lambda function as a message filter to check the recipient's chat ID. Requires aiomax and asyncio. ```python import aiomax import asyncio bot = aiomax.Bot('TOKEN') chat_id: int = 2409 # ID чата, сообщения в котором должны обрабатыватся @bot.on_message(lambda message: message.recipient.chat_id == chat_id) async def echo(message: aiomax.Message): await message.send(message.body.text) bot.run() ``` -------------------------------- ### Handle Commands with on_command Decorator in aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt This section explains how to use the `@bot.on_command()` decorator for command handling, including automatic argument parsing. It covers defining commands by function name, specifying explicit names and aliases, handling commands with arguments (accessing `ctx.args` and `ctx.args_raw`), accessing command context properties, and configuring commands to also trigger message handlers (`as_message=True`). ```python import aiomax bot = aiomax.Bot('TOKEN', command_prefixes='/') # Простая команда (имя берётся из функции) @bot.on_command() async def start(ctx: aiomax.CommandContext): await ctx.send(f"Привет, {ctx.sender.name}!") # Команда с явным именем и алиасами @bot.on_command(name='help', aliases=['h', 'помощь']) def help_command(ctx: aiomax.CommandContext): await ctx.reply("Список команд:\n/start - начать\n/help - помощь") # Команда с аргументами @bot.on_command('sum') async def sum_numbers(ctx: aiomax.CommandContext): # ctx.args - список аргументов # ctx.args_raw - строка аргументов try: numbers = [int(x) for x in ctx.args] result = sum(numbers) await ctx.reply(f"Сумма: {result}") except ValueError: await ctx.reply("Используйте: /sum 1 2 3") # Доступ к свойствам контекста @bot.on_command('info') async def info(ctx: aiomax.CommandContext): print(f"Команда: {ctx.command_name}") print(f"Аргументы: {ctx.args}") print(f"Сырые аргументы: {ctx.args_raw}") print(f"Отправитель: {ctx.sender}") print(f"Сообщение: {ctx.message}") print(f"Бот: {ctx.bot}") await ctx.send("Информация выведена в консоль") # Команда, которая также триггерит on_message @bot.on_command('echo', as_message=True) def echo_cmd(ctx: aiomax.CommandContext): await ctx.reply(ctx.args_raw) bot.run() ``` -------------------------------- ### Random Number Generator Bot with aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Примеры.md A bot that generates random numbers within a specified range upon receiving a command. It supports aliases for the command and registers commands with the bot API. Requires aiomax, asyncio, and random libraries. ```python import aiomax import asyncio import random bot = aiomax.Bot('TOKEN', default_format='markdown') # Команда для генерации случайных чисел: /random минимум максимум @bot.on_command('random', aliases=['rnd']) async def gen(ctx: aiomax.CommandContext): try: min_num = int(ctx.args[0]) max_num = int(ctx.args[1]) number = random.randint(min_num, max_num) except: await ctx.reply('❌ **Некорректные аргументы!**\n\n/random <миниммум> <максимум>') return await ctx.reply(f'Ваше число: **{number}**') # Сообщение при начале чата с ботом @bot.on_bot_start() async def on_bot_start(payload: aiomax.BotStartPayload): await payload.send('**Моя команда:**\n\n/random <минимум> <максимум>') # Отправляет команды на сервер, чтобы они отображались у пользователей в меню @bot.on_ready() async def send_commands(): await bot.patch_me(commands=[ aiomax.BotCommand('random', 'Генерирует случайное число от минимума до максимума') ]) bot.run() ``` -------------------------------- ### Access Bot Instance from Router Source: https://github.com/dpnspn/aiomax/blob/main/docs/Роутеры.md Shows how to retrieve the parent Bot instance associated with a router using the router.bot property within an event handler. ```python @router.on_command('my_name') async def my_name(message: aiomax.Message): await message.reply('Мое имя - '+router.bot.name) ``` -------------------------------- ### Using Built-in `startswith` Filter in aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Фильтры.md Demonstrates how to use the `aiomax.filters.startswith` filter to process messages that begin with a specific prefix. This filter is useful for command-based bots. It's applied directly to the `on_message` decorator. ```python import aiomax @bot.on_message(aiomax.filters.startswith('папайя')) async def dialog(message: aiomax.Message): pass # Содержимое функции ``` -------------------------------- ### Python: Get Chat Information using aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt Retrieves and displays detailed information about a chat, including its ID, title, type, participant count, public status, description, and link. This function requires the aiomax library and a bot token. ```python import aiomax bot = aiomax.Bot('TOKEN') @bot.on_command('chat_info') async def chat_info(ctx: aiomax.CommandContext): chat_id = ctx.message.recipient.chat_id # Получение информации о чате chat = await bot.get_chat(chat_id) info = f""" **Информация о чате:** ID: {chat.chat_id} Название: {chat.title} Тип: {chat.type} Участников: {chat.participants_count} Публичный: {chat.is_public} Описание: {chat.description} Ссылка: {chat.link} """ await ctx.send(info, format='markdown') ``` -------------------------------- ### Handle Callback Buttons with on_button_callback Source: https://context7.com/dpnspn/aiomax/llms.txt Demonstrates how to use the on_button_callback decorator to process user interactions with inline buttons. It shows how to filter callbacks by payload and use the Callback object to answer notifications or send messages. ```python import aiomax from aiomax.buttons import CallbackButton, KeyboardBuilder bot = aiomax.Bot('TOKEN') @bot.on_command('menu') async def show_menu(ctx: aiomax.CommandContext): kb = KeyboardBuilder() kb.row( CallbackButton("Кнопка 1", "btn_1"), CallbackButton("Кнопка 2", "btn_2") ) kb.row(CallbackButton("Отмена", "cancel", intent="negative")) await ctx.send("Выберите действие:", keyboard=kb) @bot.on_button_callback(lambda cb: cb.payload == "btn_1") async def button_1(callback: aiomax.Callback): await callback.answer( notification="Вы нажали кнопку 1!", text="Выбрана кнопка 1" ) @bot.on_button_callback(lambda cb: cb.payload == "btn_2") async def button_2(callback: aiomax.Callback): await callback.send("Вы выбрали кнопку 2") @bot.on_button_callback(lambda cb: cb.payload == "cancel") async def cancel_button(callback: aiomax.Callback): await callback.answer(text="Действие отменено") @bot.on_button_callback() async def any_callback(cb: aiomax.Callback): print(f"Payload: {cb.payload}") print(f"Пользователь: {cb.user.name} (ID: {cb.user_id})") print(f"Сообщение: {cb.message}") print(f"Время: {cb.timestamp}") print(f"Локаль: {cb.user_locale}") bot.run() ``` -------------------------------- ### Upload Audio Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Uploads an audio file to the server. Accepts either a file path or a file-like object. Returns an AudioAttachment object upon successful upload. ```python Bot.upload_audio(data: IO | str) -> AudioAttachment ``` -------------------------------- ### Python: Handle User Joined Chat Event using aiomax Source: https://context7.com/dpnspn/aiomax/llms.txt Sends a welcome message to a user who joins a chat and logs the initiator if available. This event handler requires the aiomax library. ```python import aiomax bot = aiomax.Bot('TOKEN') # Пользователь присоединился к чату @bot.on_user_add() async def user_joined(payload: aiomax.UserMembershipPayload): # Отправка приветствия await bot.send_message( f"Добро пожаловать, {payload.user.name}!", chat_id=payload.chat_id ) # Кто пригласил (если есть) if payload.initiator: print(f"Приглашён пользователем {payload.initiator}") ``` -------------------------------- ### Upload Video Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Uploads a video to the server. Accepts either a file path or a file-like object. Returns a VideoAttachment object upon successful upload. ```python Bot.upload_video(data: IO | str) -> VideoAttachment ``` -------------------------------- ### Custom Filter using Lambda Expression in aiomax Source: https://github.com/dpnspn/aiomax/blob/main/docs/Фильтры.md Provides an example of creating a custom filter using a lambda expression. This is suitable for short, inline filter logic, such as checking if a message was sent in a direct chat. The lambda function receives the message object as input. ```python @bot.on_message(lambda message: message.recipient.chat_type == 'dialog') async def dialog(message: aiomax.Message): pass # Содержимое функции ``` -------------------------------- ### Get Chat Members Source: https://github.com/dpnspn/aiomax/blob/main/docs/Бот.md Retrieves a list of users from a chat based on provided user IDs. It can return a list of User objects, a single User object, or None if the user is not found. Handles both single user IDs and lists of user IDs. ```python Bot.get_memberships(chat_id: int, user_ids: List[int]) -> List[User] | User | None ```