### Router-Based Handler Organization Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Organize bot handlers into modular routers for better structure and maintainability. This example shows how to create and include admin, user, and game routers, along with a main dispatcher. ```APIDOC ## Router-Based Handler Organization ### Description Organizing handlers into routers for modular bot structure. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Finite State Machine (FSM) with Context (Python) Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Illustrates managing conversation state and user data across interactions using Finite State Machines (FSM) and context management in the Max Bot API. This example requires the maxapi library, including its context and types modules. ```python from maxapi import Bot, Dispatcher, F from maxapi.context import MemoryContext, State, StatesGroup from maxapi.types import MessageCreated, MessageCallback, CallbackButton from maxapi.utils.inline_keyboard import InlineKeyboardBuilder bot = Bot('your_bot_token_here') dp = Dispatcher() ``` -------------------------------- ### Configure Webhook for Production Deployment in Python Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Sets up a bot to run in webhook mode for production environments, receiving updates via HTTP POST requests instead of polling. It includes subscribing to specific update types and starting a webhook server. ```python import asyncio from maxapi import Bot, Dispatcher from maxapi.types import MessageCreated, Command from maxapi.enums.update import UpdateType bot = Bot('your_bot_token_here') dp = Dispatcher() @dp.message_created(Command('start')) async def start_handler(event: MessageCreated): await event.message.answer("Hello from webhook mode!") async def setup_webhook(): # Subscribe to webhook updates await bot.subscribe_webhook( url='https://your-domain.com/', update_types=[ UpdateType.MESSAGE_CREATED, UpdateType.MESSAGE_CALLBACK, UpdateType.BOT_STARTED ], secret='your-secret-key-here' ) async def main(): # Setup webhook subscription await setup_webhook() # Start webhook server await dp.handle_webhook( bot=bot, host='0.0.0.0', port=8080, log_level='info' ) # To remove webhooks and switch back to polling async def cleanup_webhooks(): await bot.delete_webhook() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Handle Bot Events with Max Bot API Dispatcher in Python Source: https://context7.com/max-messenger/max-botapi-python/llms.txt This snippet illustrates how to set up event handlers for various bot events using the Dispatcher from the Max Bot API. It covers bot lifecycle events (started, added, removed, stopped), user events (added, removed), message events (edited, removed), chat events (title changed, chat created), and dialog events (cleared). It requires the 'maxapi' library, a bot token, and the Dispatcher. ```python from maxapi import Bot, Dispatcher from maxapi.types import ( BotStarted, BotAdded, BotRemoved, BotStopped, UserAdded, UserRemoved, MessageEdited, MessageRemoved, ChatTitleChanged, DialogCleared, MessageChatCreated ) bot = Bot('your_bot_token_here') dp = Dispatcher() # Bot lifecycle events @dp.bot_started() async def on_bot_started(event: BotStarted): await event.bot.send_message( chat_id=event.chat_id, text="Hi! I'm ready to chat!" ) @dp.bot_added() async def on_bot_added(event: BotAdded): await event.bot.send_message( chat_id=event.chat.chat_id, text=f"Thanks for adding me to {event.chat.title}!" ) @dp.bot_removed() async def on_bot_removed(event: BotRemoved): print(f"Bot removed from chat {event.chat.chat_id}") @dp.bot_stopped() async def on_bot_stopped(event: BotStopped): print(f"User {event.from_user.user_id} stopped the bot") # User events in chats @dp.user_added() async def on_user_added(event: UserAdded): await event.bot.send_message( chat_id=event.chat.chat_id, text=f"Welcome {event.user.first_name}!" ) @dp.user_removed() async def on_user_removed(event: UserRemoved): await event.bot.send_message( chat_id=event.chat.chat_id, text=f"{event.user.first_name} left the chat" ) # Message lifecycle events @dp.message_edited() async def on_message_edited(event: MessageEdited): await event.message.answer("I see you edited your message!") @dp.message_removed() async def on_message_removed(event: MessageRemoved): print(f"Message {event.message_id} was removed") # Chat events @dp.chat_title_changed() async def on_title_changed(event: ChatTitleChanged): await event.bot.send_message( chat_id=event.chat.chat_id, text=f"Chat renamed to: {event.chat.title}" ) @dp.message_chat_created() async def on_chat_created(event: MessageChatCreated): await event.bot.send_message( chat_id=event.chat.chat_id, text=f"Chat created! Link: {event.chat.link}" ) # Dialog events @dp.dialog_cleared() async def on_dialog_cleared(event: DialogCleared): print(f"Dialog cleared for user {event.from_user.user_id}") # Startup event (runs once when bot starts) @dp.on_started() async def on_startup(): print("Bot is starting up!") # Perform initialization tasks async def main(): await dp.start_polling(bot) if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Edit and Delete Messages (Python) Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Shows how to modify the text of an existing message and how to delete a message using its ID. It also includes an example of editing a message within an event handler after a delay. Requires the `maxapi` library. ```python from maxapi import Bot from maxapi.types import MessageCreated bot = Bot('your_bot_token_here') async def message_operations(message_id: str): # Edit message text edited = await bot.edit_message( message_id=message_id, text="This message has been edited" ) # Delete message deleted = await bot.delete_message(message_id=message_id) return edited, deleted # Example with event handler @dp.message_created() async def edit_example(event: MessageCreated): sent = await event.message.answer("Original message") # Wait 2 seconds then edit await asyncio.sleep(2) await bot.edit_message( message_id=sent.body.message_id, text="Message updated!" ) ``` -------------------------------- ### Python Middleware for Max Bot API Request Processing Source: https://context7.com/max-messenger/max-botapi-python/llms.txt This Python code defines and applies middleware to a Max Bot API Dispatcher for advanced request processing. It includes examples for access control, logging, and injecting custom data into handler functions, demonstrating how to intercept and modify the event handling flow. ```python from typing import Any, Awaitable, Callable, Dict from maxapi import Bot, Dispatcher from maxapi.filters.middleware import BaseMiddleware from maxapi.types import MessageCreated, Command, UpdateUnion bot = Bot('your_bot_token_here') dp = Dispatcher() # Middleware for access control class AccessControlMiddleware(BaseMiddleware): def __init__(self, allowed_user_ids: list[int]): self.allowed_user_ids = allowed_user_ids async def __call__( self, handler: Callable[[Any, Dict[str, Any]], Awaitable[Any]], event_object: UpdateUnion, data: Dict[str, Any], ) -> Any: # Check if user is allowed if event_object.from_user.user_id in self.allowed_user_ids: return await handler(event_object, data) else: await event_object.bot.send_message( chat_id=event_object.chat.chat_id, text="Access denied!" ) # Middleware for logging class LoggingMiddleware(BaseMiddleware): async def __call__( self, handler: Callable[[Any, Dict[str, Any]], Awaitable[Any]], event_object: UpdateUnion, data: Dict[str, Any], ) -> Any: print(f"Processing event: {event_object.update_type}") print(f"User: {event_object.from_user.user_id}") # Call handler result = await handler(event_object, data) print("Event processed successfully") return result # Middleware for injecting custom data class CustomDataMiddleware(BaseMiddleware): async def __call__( self, handler: Callable[[Any, Dict[str, Any]], Awaitable[Any]], event_object: UpdateUnion, data: Dict[str, Any], ) -> Any: # Add custom data to handler kwargs data['custom_value'] = f"User {event_object.from_user.user_id} at {event_object.timestamp}" data['admin_mode'] = event_object.from_user.user_id in [123, 456] return await handler(event_object, data) # Apply middleware globally to dispatcher dp.middlewares.append(LoggingMiddleware()) # Apply middleware to specific handler allowed_users = [123456, 789012] @dp.message_created(Command('admin'), AccessControlMiddleware(allowed_users)) async def admin_command(event: MessageCreated): await event.message.answer("Admin command executed") # Use injected data from middleware @dp.message_created(Command('info'), CustomDataMiddleware()) async def info_command(event: MessageCreated, custom_value: str, admin_mode: bool): await event.message.answer( f"Info: {custom_value}\n" f"Admin mode: {admin_mode}" ) ``` -------------------------------- ### Initialize Bot and Handle Basic Messages (Python) Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Demonstrates how to initialize a MaxAPI bot with a token and set up handlers for commands and general text messages. It uses async/await patterns and the Dispatcher for event routing. Requires the `maxapi` library. ```python import asyncio import logging from maxapi import Bot, Dispatcher from maxapi.types import MessageCreated, Command logging.basicConfig(level=logging.INFO) # Initialize bot with token bot = Bot('your_bot_token_here') dp = Dispatcher() # Handler for /start command @dp.message_created(Command('start')) async def start_handler(event: MessageCreated): await event.message.answer( text=f"Hello! I'm a MAX bot 💙", notify=True ) # Echo handler for text messages @dp.message_created() async def echo_handler(event: MessageCreated): if event.message.body.text: await event.message.answer( text=f"You said: {event.message.body.text}" ) async def main(): # Start polling for updates await dp.start_polling(bot) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Create Interactive Keyboards with Buttons (Python) Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Demonstrates how to create interactive keyboards with various button types like callback, link, request contact, request location, and open app buttons using InlineKeyboardBuilder. This requires the maxapi library and its types. ```python from maxapi import Bot, Dispatcher from maxapi.types import ( MessageCreated, MessageCallback, Command, CallbackButton, LinkButton, RequestContactButton, RequestGeoLocationButton, OpenAppButton ) from maxapi.utils.inline_keyboard import InlineKeyboardBuilder bot = Bot('your_bot_token_here') dp = Dispatcher() @dp.message_created(Command('menu')) async def show_keyboard(event: MessageCreated): # Build keyboard with buttons builder = InlineKeyboardBuilder() # First row - callback and link buttons builder.row( CallbackButton(text='Click Me', payload='button_clicked'), LinkButton(text='Documentation', url='https://dev.max.ru/docs') ) # Second row - request buttons builder.row( RequestContactButton(text='Share Contact'), RequestGeoLocationButton(text='Share Location') ) # Third row - app button builder.row( OpenAppButton( text='Open App', web_app=event.bot.me.username, contact_id=event.bot.me.user_id ) ) await event.message.answer( text='Choose an option:', attachments=[builder.as_markup()] ) @dp.message_callback() async def handle_callback(event: MessageCallback): if event.callback.payload == 'button_clicked': await event.message.answer('Button was clicked!') # Send callback acknowledgment await event.bot.send_callback( callback_id=event.callback.callback_id, notification='Action completed' ) ``` -------------------------------- ### Organize Bot Handlers with Routers in Python Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Demonstrates how to organize bot command handlers into modular routers for better code structure and maintainability. This approach separates different functionalities into distinct router instances which are then included in the main dispatcher. ```python from maxapi import Bot, Dispatcher, Router from maxapi.types import MessageCreated, Command # Create main dispatcher bot = Bot('your_bot_token_here') dp = Dispatcher() # Create routers for different feature modules admin_router = Router(router_id='admin') user_router = Router(router_id='user') game_router = Router(router_id='games') # Admin router handlers @admin_router.message_created(Command('stats')) async def admin_stats(event: MessageCreated): await event.message.answer("Admin statistics...") @admin_router.message_created(Command('ban')) async def ban_user(event: MessageCreated): await event.message.answer("User banned") # User router handlers @user_router.message_created(Command('profile')) async def user_profile(event: MessageCreated): await event.message.answer("Your profile...") @user_router.get_event_for_user.message_created(Command('settings')) async def user_settings(event: MessageCreated): await event.message.answer("Settings menu") # Game router handlers @game_router.message_created(Command('play')) async def start_game(event: MessageCreated): await event.message.answer("Starting game...") @game_router.message_created(Command('score')) async def show_score(event: MessageCreated): await event.message.answer("Your score: 100") # Main dispatcher handlers @dp.message_created(Command('start')) async def start_handler(event: MessageCreated): await event.message.answer( "Welcome! Available commands:\n" "/profile - User profile\n" "/play - Start game\n" "/stats - Admin stats" ) # Include all routers dp.include_routers(admin_router, user_router, game_router) async def main(): await dp.start_polling(bot) if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Webhook Mode for Production Deployment Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Run your bot in webhook mode for production environments. This involves setting up a webhook subscription to receive updates from the bot platform and handling them via a web server. ```APIDOC ## Webhook Mode for Production Deployment ### Description Running bot with webhooks instead of polling for production environments. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Python State Management for User Registration Bot Source: https://context7.com/max-messenger/max-botapi-python/llms.txt This Python code demonstrates state management for a user registration bot using Max Bot API. It defines states for collecting name, age, and city, storing them in context, and clearing the state upon completion. It also includes commands to check or clear context. ```python from aiogram.fsm.state import StatesGroup, State from aiogram.fsm.context import FSMContext from aiogram.types import Message from aiogram.filters import Command, F from aiogram import Bot, Dispatcher # Dummy implementations for demonstration class MessageCreated: def __init__(self, message): self.message = message class Command: def __init__(self, command): self.command = command class F: class message: class body: text = True class Bot: def __init__(self, token): pass async def send_message(self, chat_id, text): print(f"Sending message to {chat_id}: {text}") class Dispatcher: def __init__(self): self.message_created_handlers = [] self.middlewares = [] def message_created(self, *filters, **kwargs): def decorator(handler): self.message_created_handlers.append({'filters': filters, 'handler': handler, **kwargs}) return handler return decorator async def process_event(self, event, context): for handler_info in self.message_created_handlers: match = True for f in handler_info['filters']: if isinstance(f, Command) and isinstance(event, MessageCreated) and event.message.body.command != f.command: match = False break if isinstance(f, F.message.body.text) and not hasattr(event.message.body, 'text'): match = False break if hasattr(handler_info, 'state') and context.state != handler_info['state']: match = False break if match: await handler_info['handler'](event, context) return # Bot and Dispatcher initialization (simplified for example) dp = Dispatcher() # Define state group class RegistrationForm(StatesGroup): waiting_name = State() waiting_age = State() waiting_city = State() @dp.message_created(Command('register')) async def start_registration(event: MessageCreated, context: FSMContext): await context.set_state(RegistrationForm.waiting_name) await event.message.answer("Please enter your name:") @dp.message_created(F.message.body.text, state=RegistrationForm.waiting_name) async def process_name(event: MessageCreated, context: FSMContext): # Store name in context await context.update_data(name=event.message.body.text) # Move to next state await context.set_state(RegistrationForm.waiting_age) await event.message.answer("Thanks! Now enter your age:") @dp.message_created(F.message.body.text, state=RegistrationForm.waiting_age) async def process_age(event: MessageCreated, context: FSMContext): # Validate age if not event.message.body.text.isdigit(): await event.message.answer("Please enter a valid number") return await context.update_data(age=int(event.message.body.text)) await context.set_state(RegistrationForm.waiting_city) await event.message.answer("Great! What city are you from?") @dp.message_created(F.message.body.text, state=RegistrationForm.waiting_city) async def process_city(event: MessageCreated, context: FSMContext): await context.update_data(city=event.message.body.text) # Get all stored data data = await context.get_data() # Clear state await context.clear() await event.message.answer( f"Registration complete!\n" f"Name: {data['name']}\n" f"Age: {data['age']}\n" f"City: {data['city']}" ) # Check or clear context @dp.message_created(Command('clear')) async def clear_context(event: MessageCreated, context: FSMContext): await context.clear() await event.message.answer("Your context has been cleared!") @dp.message_created(Command('mydata')) async def show_data(event: MessageCreated, context: FSMContext): data = await context.get_data() state = await context.get_state() await event.message.answer( f"Current state: {state}\n" f"Stored data: {data}" ) ``` -------------------------------- ### Send Formatted Messages and Attachments (Python) Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Illustrates sending messages with different formatting options (Markdown) and attaching files or image buffers. It utilizes `ParseMode` for formatting and `InputMedia` types for attachments. Requires the `maxapi` library and `aiohttp`. ```python from maxapi import Bot from maxapi.enums.parse_mode import ParseMode from maxapi.types.input_media import InputMedia, InputMediaBuffer bot = Bot('your_bot_token_here', parse_mode=ParseMode.MARKDOWN) async def send_formatted_message(): # Send message with markdown formatting result = await bot.send_message( chat_id=123456789, text="*Bold text* and _italic text_\n[Link](https://example.com)", parse_mode=ParseMode.MARKDOWN ) # Send message with image from file photo = InputMedia(path='/path/to/image.jpg') await bot.send_message( chat_id=123456789, text="Here's an image!", attachments=[photo] ) # Send message with image from buffer with open('/path/to/photo.png', 'rb') as f: buffer = f.read() photo_buffer = InputMediaBuffer(buffer=buffer, filename='photo.png') await bot.send_message( chat_id=123456789, text="Image from buffer", attachments=[photo_buffer] ) ``` -------------------------------- ### Manage Bot Info and Commands with Max Bot API in Python Source: https://context7.com/max-messenger/max-botapi-python/llms.txt This snippet demonstrates how to retrieve bot information, set and update bot commands, change bot profile details (name, description), send typing actions, retrieve bot details within a specific chat, and remove the bot from a chat using the Max Bot API. It requires the 'maxapi' library and a bot token. ```python from maxapi import Bot from maxapi.types import BotCommand from maxapi.types import SenderAction bot = Bot('your_bot_token_here') async def bot_info_operations(): # Get bot information me = await bot.get_me() print(f"Bot username: @{me.username}") print(f"Bot ID: {me.user_id}") print(f"Bot name: {me.first_name}") # Set bot commands (method 1) await bot.set_my_commands( BotCommand(name='/start', description='Start the bot'), BotCommand(name='/help', description='Get help'), BotCommand(name='/settings', description='Open settings'), BotCommand(name='/profile', description='View profile') ) # Update bot info updated = await bot.change_info( name='My Bot Name', description='This is my awesome bot', commands=[ BotCommand(name='/start', description='Start bot'), BotCommand(name='/help', description='Show help') ] ) # Send typing action await bot.send_action( chat_id=123456789, action=SenderAction.TYPING_ON ) # Get bot info in specific chat bot_in_chat = await bot.get_me_from_chat(chat_id=123456789) print(f"Bot permissions: {bot_in_chat.permissions}") # Remove bot from chat await bot.delete_me_from_chat(chat_id=123456789) ``` -------------------------------- ### Manage Chats and Members with Max Bot API in Python Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Provides Python code for performing various chat management operations, including retrieving chat information, editing chat properties, managing members and administrators, and pinning/unpinning messages. ```python from maxapi import Bot from maxapi.types import ChatAdmin bot = Bot('your_bot_token_here') async def chat_operations(): chat_id = 123456789 user_id = 987654321 # Get chat info by ID chat = await bot.get_chat_by_id(id=chat_id) print(f"Chat: {chat.title}, Type: {chat.type}") # Get chat by link chat_by_link = await bot.get_chat_by_link(link='https://max.ru/...') # Edit chat properties await bot.edit_chat( chat_id=chat_id, title="New Chat Title", notify=True ) # Get chat members members = await bot.get_chat_members(chat_id=chat_id, count=50) for member in members.members: print(f"Member: {member.user.first_name}") # Get specific member member = await bot.get_chat_member(chat_id=chat_id, user_id=user_id) # Add members to chat await bot.add_chat_members( chat_id=chat_id, user_ids=[111111, 222222, 333333] ) # Remove member from chat await bot.kick_chat_member( chat_id=chat_id, user_id=user_id, block=False # Set True to block user ) # Get admins list admins = await bot.get_list_admin_chat(chat_id=chat_id) # Add admin new_admin = ChatAdmin(user_id=user_id) await bot.add_list_admin_chat( chat_id=chat_id, admins=[new_admin] ) # Remove admin await bot.remove_admin(chat_id=chat_id, user_id=user_id) # Pin message await bot.pin_message( chat_id=chat_id, message_id='msg_123', notify=True ) # Get pinned message pinned = await bot.get_pin_message(chat_id=chat_id) # Unpin message await bot.delete_pin_message(chat_id=chat_id) # Delete chat await bot.delete_chat(chat_id=chat_id) ``` -------------------------------- ### Advanced Event Filtering with Magic Filters (Python) Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Shows how to use magic filters (F) for advanced event filtering in the Max Bot API. Filters can check text content, specific values, substrings, chat types, and callback payloads, enabling selective event handling. Requires the maxapi library. ```python from maxapi import Bot, Dispatcher, F from maxapi.types import MessageCreated, MessageCallback bot = Bot('your_bot_token_here') dp = Dispatcher() # Filter by text content @dp.message_created(F.message.body.text) async def handle_text(event: MessageCreated): await event.message.answer(f"You sent text: {event.message.body.text}") # Filter by specific text value @dp.message_created(F.message.body.text == "hello") async def handle_hello(event: MessageCreated): await event.message.answer("Hello to you too!") # Filter by text containing substring @dp.message_created(F.message.body.text.contains("help")) async def handle_help_request(event: MessageCreated): await event.message.answer("How can I help you?") # Filter by chat type @dp.message_created(F.chat.type == "group") async def handle_group_message(event: MessageCreated): await event.message.answer("This is a group chat message") # Filter callback by payload @dp.message_callback(F.callback.payload == 'confirm') async def handle_confirm(event: MessageCallback): await event.message.answer("Confirmed!") # Combined filters @dp.message_created(F.message.body.text & F.chat.type == "private") async def handle_private_text(event: MessageCreated): await event.message.answer("Private text message received") ``` -------------------------------- ### Chat Management Operations Source: https://context7.com/max-messenger/max-botapi-python/llms.txt Perform various chat management operations, including retrieving chat information, editing chat properties, managing members and administrators, pinning/unpinning messages, and deleting chats. ```APIDOC ## Chat Management Operations ### Description Managing chats, members, and administrators. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.