### Start FSM and Transition to Initial State Source: https://docs.aiogram.dev/en/dev-3.x/dispatcher/finite_state_machine/index.html Handle a command (e.g., /start) to initiate the FSM and set the first state for the user. This example transitions to the 'Form.name' state. ```python @form_router.message(CommandStart()) async def command_start(message: Message, state: FSMContext) -> None: await state.set_state(Form.name) await message.answer( "Hi there! What's your name?", reply_markup=ReplyKeyboardRemove(), ) ``` -------------------------------- ### Setup Project with uv Source: https://docs.aiogram.dev/en/dev-3.x/contributing.html Clones the aiogram repository and installs all dependencies using uv, automatically creating a virtual environment. ```bash git clone https://github.com/aiogram/aiogram.git cd aiogram uv sync --all-extras --group dev --group test uv run pre-commit install ``` -------------------------------- ### Setup Project with Pip (Windows) Source: https://docs.aiogram.dev/en/dev-3.x/contributing.html Installs aiogram and its development dependencies in editable mode on Windows. ```bash pip install -e .[dev,test,docs,fast,redis,mongo,proxy,i18n] ``` -------------------------------- ### Creating an Entry Point Handler for a Scene Source: https://docs.aiogram.dev/en/dev-3.x/_modules/aiogram/fsm/scene.html Shows how to create a handler that can be used as an entry point to start a scene. This method simplifies the registration of the initial handler that triggers the scene, as demonstrated with a command handler example. ```python @classmethod def as_handler(cls, **handler_kwargs: Any) -> CallbackType: """ Create an entry point handler for the scene, can be used to simplify the handler that starts the scene. >>> router.message.register(MyScene.as_handler(), Command("start")) """ ``` -------------------------------- ### Setup Project with Pip (Linux/macOS) Source: https://docs.aiogram.dev/en/dev-3.x/contributing.html Installs aiogram and its development dependencies in editable mode on Linux/macOS. ```bash pip install -e ."[dev,test,docs,fast,redis,mongo,proxy,i18n]" ``` -------------------------------- ### Install uv using pip Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Install the uv package manager using pip. ```bash pip install uv ``` -------------------------------- ### Complete FSM Example Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/finite_state_machine/index.rst.txt A complete example demonstrating the implementation of a finite state machine for a multi-step form. ```python import logging from aiogram import Bot, Dispatcher, executor, types from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.utils.markdown import h1 from pydantic import BaseModel API_TOKEN = '...' # For example, use simple memory storage storage = MemoryStorage() # Initialize bot and dispatcher bot = Bot(token=API_TOKEN) dp = Dispatcher(bot, storage=storage) logging.basicConfig(level=logging.INFO) class Form(BaseModel): name: str language: str class FormStates(StatesGroup): name = State() language = State() @dp.message_handler(commands='start', state=None) async def command_start(message: types.Message): await FormStates.name.set() await message.reply("Hi!\nWhat is your name?") @dp.message_handler(state=FormStates.name) async def process_name(message: types.Message, state: FSMContext): async with state.proxy() as data: data['name'] = message.text.lower() await FormStates.next() await message.reply("Favorite bot language?") @dp.message_handler(lambda message: message.text.lower() not in ['python', 'java', 'go', 'c++'], state=FormStates.language) async def process_language_invalid(message: types.Message): return await message.reply("Bad programming language\n(tell me which programming language you use, for example, enter Python, Java, Go, C++ etc.)") @dp.message_handler(state=FormStates.language) async def process_language(message: types.Message, state: FSMContext): async with state.proxy() as data: data['language'] = message.text.lower() # Do contact to API or save data to database await message.reply("Thank you! You have successfully passed the registration.") await state.finish() # You can also use await dp.current_state(user=message.from_user.id).finish() @dp.message_handler(commands='cancel', state='*') async def cancel_handler(message: types.Message, state: FSMContext): current_state = await state.get_state() if current_state is None: return await state.finish() await message.reply('Cancelled.') if __name__ == '__main__': executor.start_polling(dp, skip_updates=True) ``` -------------------------------- ### Webhook Setup with Self-Signed SSL Certificate Source: https://docs.aiogram.dev/en/dev-3.x/dispatcher/webhook.html This example demonstrates setting up a Telegram bot with webhooks using a self-signed SSL certificate. It includes bot initialization, webhook path configuration, SSL certificate paths, and event handlers for /start commands and message echoing. The `on_startup` function configures the webhook with the certificate and secret token, and the `main` function sets up the aiohttp web server with SSL context. ```Python """ This example shows how to use webhook with SSL certificate. """ import logging import ssl import sys from os import getenv from aiohttp import web from aiogram import Bot, Dispatcher, Router from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import FSInputFile, Message from aiogram.utils.markdown import hbold from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application # Bot token can be obtained via https://t.me/BotFather TOKEN = getenv("BOT_TOKEN") # Webserver settings # bind localhost only to prevent any external access WEB_SERVER_HOST = "127.0.0.1" # Port for incoming request from reverse proxy. Should be any available port WEB_SERVER_PORT = 8080 # Path to webhook route, on which Telegram will send requests WEBHOOK_PATH = "/webhook" # Secret key to validate requests from Telegram (optional) WEBHOOK_SECRET = "my-secret" # Base URL for webhook will be used to generate webhook URL for Telegram, # in this example it is used public address with TLS support BASE_WEBHOOK_URL = "https://aiogram.dev" # Path to SSL certificate and private key for self-signed certificate. WEBHOOK_SSL_CERT = "/path/to/cert.pem" WEBHOOK_SSL_PRIV = "/path/to/private.key" # All handlers should be attached to the Router (or Dispatcher) router = Router() @router.message(CommandStart()) async def command_start_handler(message: Message) -> None: """ This handler receives messages with `/start` command """ # Most event objects have aliases for API methods that can be called in events' context # For example if you want to answer to incoming message you can use `message.answer(...)` alias # and the target chat will be passed to :ref:`aiogram.methods.send_message.SendMessage` # method automatically or call API method directly via # Bot instance: `bot.send_message(chat_id=message.chat.id, ...)` await message.answer(f"Hello, {hbold(message.from_user.full_name)}!") @router.message() async def echo_handler(message: Message) -> None: """ Handler will forward receive a message back to the sender By default, message handler will handle all message types (like text, photo, sticker etc.) """ try: # Send a copy of the received message await message.send_copy(chat_id=message.chat.id) except TypeError: # But not all the types is supported to be copied so need to handle it await message.answer("Nice try!") async def on_startup(bot: Bot) -> None: # In case when you have a self-signed SSL certificate, you need to send the certificate # itself to Telegram servers for validation purposes # (see https://core.telegram.org/bots/self-signed) # But if you have a valid SSL certificate, you SHOULD NOT send it to Telegram servers. await bot.set_webhook( f"{BASE_WEBHOOK_URL}{WEBHOOK_PATH}", certificate=FSInputFile(WEBHOOK_SSL_CERT), secret_token=WEBHOOK_SECRET, ) def main() -> None: # Dispatcher is a root router dp = Dispatcher() # ... and all other routers should be attached to Dispatcher dp.include_router(router) # Register startup hook to initialize webhook dp.startup.register(on_startup) # Initialize Bot instance with default bot properties which will be passed to all API calls bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) # Create aiohttp.web.Application instance app = web.Application() # Create an instance of request handler, # aiogram has few implementations for different cases of usage # In this example we use SimpleRequestHandler which is designed to handle simple cases webhook_requests_handler = SimpleRequestHandler( dispatcher=dp, bot=bot, secret_token=WEBHOOK_SECRET, ) # Register webhook handler on application webhook_requests_handler.register(app, path=WEBHOOK_PATH) # Mount dispatcher startup and shutdown hooks to aiohttp application setup_application(app, dp, bot=bot) # Generate SSL context context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.load_cert_chain(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV) # And finally start webserver web.run_app(app, host=WEB_SERVER_HOST, port=WEB_SERVER_PORT, ssl_context=context) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) main() ``` -------------------------------- ### Makefile Install Command Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Use the Makefile to install project dependencies, which internally utilizes uv sync. ```bash make install ``` -------------------------------- ### Install pre-commit hooks with uv Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Install pre-commit hooks using uv to ensure code quality and consistency. ```bash uv run pre-commit install ``` -------------------------------- ### Install uv (Windows PowerShell) Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Install the uv package manager using a PowerShell script on Windows. ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Install Project Dependencies (Windows) Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Install aiogram from source along with all development and testing dependencies on Windows. ```bash pip install -e .[dev,test,docs,fast,redis,mongo,proxy,i18n] ``` -------------------------------- ### Simple Echo Bot Example Source: https://docs.aiogram.dev/en/dev-3.x/_sources/index.rst.txt A basic example demonstrating how to create an echo bot that replies with the same message it receives. This requires setting up a dispatcher to handle events. ```python import asyncio import logging from aiogram import Bot, Dispatcher, types from aiogram.filters.command import Command # Включаем логирование, чтобы видеть сообщения от алертов logging.basicConfig(level=logging.INFO) # Объект бота bot = Bot(token="YOUR_BOT_TOKEN") # Диспетчер dp = Dispatcher() # Хэндлер на команду /start @dp.message(Command("start")) async def cmd_start(message: types.Message): await message.answer("Hello!") # Хэндлер на команду /help @dp.message(Command("help")) async def cmd_help(message: types.Message): await message.answer("I am an echo bot. Send me any message and I will repeat it.") # Хэндлер на любые текстовые сообщения @dp.message() async def echo_handler(message: types.Message): await message.answer(message.text) async def main(): await dp.start_polling(bot) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install uv (Linux/macOS) Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Install the uv package manager using a curl script on Linux or macOS. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install uv Package Manager Source: https://docs.aiogram.dev/en/dev-3.x/contributing.html Installs the uv package manager using a script on Linux/macOS or PowerShell on Windows. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Create Basic Start Link Source: https://docs.aiogram.dev/en/dev-3.x/utils/deep_linking.html Generates a standard Telegram deep link for starting a bot with a payload. No special setup is required. ```python from aiogram.utils.deep_linking import create_start_link link = await create_start_link(bot, 'foo') # result: 'https://t.me/MyBot?start=foo' ``` -------------------------------- ### Setup Project with uv Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Clone the repository and use uv to synchronize all dependencies, automatically creating a virtual environment. ```bash git clone https://github.com/aiogram/aiogram.git cd aiogram uv sync --all-extras --group dev --group test ``` -------------------------------- ### Start Documentation Server with uv Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Build and serve the project documentation using sphinx-autobuild within the uv-managed environment. ```bash uv run sphinx-autobuild --watch aiogram/ docs/ docs/_build/ ``` -------------------------------- ### Build and Serve Docs Source: https://docs.aiogram.dev/en/dev-3.x/contributing.html Build documentation using Sphinx and serve it locally for live preview. Options include traditional execution, uv, or Makefile. ```bash sphinx-autobuild --watch aiogram/ docs/ docs/_build/ ``` ```bash uv run --extra docs sphinx-autobuild --watch aiogram/ docs/ docs/_build/ ``` ```bash make docs-serve ``` -------------------------------- ### Initialize and Use a Router Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/router.rst.txt Demonstrates how to initialize a Router and register a message handler. Ensure the handler is asynchronous. ```python from aiogram import Router from aiogram.types import Message my_router = Router(name=__name__) @my_router.message() async def message_handler(message: Message) -> Any: await message.answer('Hello from my router!') ``` -------------------------------- ### Serve Docs with Makefile Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Use the Makefile to serve the documentation locally. This command simplifies the process of previewing documentation changes. ```bash make docs-serve ``` -------------------------------- ### Quiz Example Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/finite_state_machine/scene.rst.txt A complete example demonstrating the QuizScene functionality. ```python import asyncio import logging import sys from aiogram import Bot, Dispatcher, types from aiogram.filters.command import Command from aiogram.fsm.scene import Scene, SceneRegistry, ScenesManager, on, After from aiogram.fsm.state import State, StatesGroup from aiogram.utils.keyboard import ReplyKeyboardBuilder class QuizScene(Scene, name="quiz"): state = State() def __init__(self, **kwargs): super().__init__(**kwargs) self.questions = { "What is the capital of France?": "Paris", "What is 2 + 2?": "4", "What is the color of the sky?": "Blue", } self.current_question_index = 0 self.score = 0 self.result = "" @on.message.enter() async def on_enter(self, message: types.Message): await self.ask_question(message) async def ask_question(self, message: types.Message): if self.current_question_index < len(self.questions): question = list(self.questions.keys())[self.current_question_index] builder = ReplyKeyboardBuilder() builder.add(types.KeyboardButton(text="/skip")) await message.answer(question, reply_markup=builder.as_markup()) else: await self.on_exit(message) @on.message() async def on_message(self, message: types.Message): if message.text == "/skip": await message.answer("You skipped the question.") await self.ask_question(message) return correct_answer = list(self.questions.values())[self.current_question_index] if message.text == correct_answer: await message.answer("Correct!") self.score += 1 else: await message.answer(f"Wrong! The correct answer is {correct_answer}.") self.current_question_index += 1 await self.ask_question(message) @on.exit() async def on_exit(self, message: types.Message): self.result = f"You got {self.score} out of {len(self.questions)} correct." await message.answer(self.result) @on.back() async def back(self, message: types.Message): await message.answer("Going back to the previous question.") async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher() scene_registry = SceneRegistry() await scene_registry.register(QuizScene) dp.scene_registry = scene_registry @dp.message(Command("start_quiz")) async def start_quiz_handler(message: types.Message, scenes: ScenesManager): await scenes.enter(QuizScene) await dp.start_polling(bot) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main()) ``` -------------------------------- ### Start Polling Source: https://docs.aiogram.dev/en/dev-3.x/dispatcher/finite_state_machine/scene.html Initializes the Dispatcher and Bot, then starts polling for updates. ```python dp = create_dispatcher() bot = Bot(token=TOKEN) await dp.start_polling(bot) ``` -------------------------------- ### Router Initialization and Usage Example Source: https://docs.aiogram.dev/en/dev-3.x/dispatcher/router.html Demonstrates how to initialize a Router and register a message handler using the decorator syntax. ```APIDOC ## Router Initialization and Usage Example ### Description This example shows how to create a new Router instance and define a message handler that responds to incoming messages. ### Usage ```python from aiogram import Router from aiogram.types import Message my_router = Router(name=__name__) @my_router.message() async def message_handler(message: Message) -> Any: await message.answer('Hello from my router!') ``` ``` -------------------------------- ### emit_startup Source: https://docs.aiogram.dev/en/dev-3.x/_modules/aiogram/dispatcher/router.html Recursively calls startup callbacks for the current router and all its sub-routers. ```APIDOC ## emit_startup ### Description Recursively call startup callbacks. ### Parameters #### Path Parameters - **args** (Any) - Optional - Positional arguments to pass to the startup callbacks. - **kwargs** (Any) - Optional - Keyword arguments to pass to the startup callbacks. ``` -------------------------------- ### Install Babel for Translation Source: https://docs.aiogram.dev/en/dev-3.x/_sources/utils/i18n.rst.txt Install the Babel library, which is required for extracting translation strings from your code. ```bash pip install Babel ``` ```bash pip install aiogram[i18n] ``` -------------------------------- ### Build and Serve Docs with Sphinx-Autobuild Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Start a live preview server for documentation using sphinx-autobuild. Changes in the aiogram directory will trigger automatic rebuilds. ```bash sphinx-autobuild --watch aiogram/ docs/ docs/_build/ ``` -------------------------------- ### Install aiogram with i18n extra Source: https://docs.aiogram.dev/en/dev-3.x/utils/i18n.html Alternatively, install aiogram with the i18n extra dependency to include Babel. ```bash pip install aiogram[i18n] ``` -------------------------------- ### Dispatcher Initialization and Basic Usage Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/dispatcher.rst.txt Demonstrates how to initialize a Dispatcher instance and set up a basic message handler. ```APIDOC ## Dispatcher() ### Description Initializes a new Dispatcher instance. This is the root Router for handling incoming updates. ### Method __init__ ### Parameters None ### Request Example ```python dp = Dispatcher() ``` ### Response An initialized Dispatcher object. ``` ```APIDOC ## @dp.message() ### Description Decorator to register a handler for incoming message updates. ### Method message() ### Parameters None (implicitly uses the Dispatcher instance 'dp') ### Request Example ```python @dp.message() async def message_handler(message: types.Message) -> None: await SendMessage(chat_id=message.from_user.id, text=message.text) ``` ### Response Registers the decorated asynchronous function as a message handler. ``` -------------------------------- ### AiohttpSession Initialization with Proxy Source: https://docs.aiogram.dev/en/dev-3.x/_modules/aiogram/client/session/aiohttp.html Initializes AiohttpSession with optional proxy support. Requires 'aiohttp-socks' to be installed for proxy functionality. ```python from aiogram.client.session.aiohttp import AiohttpSession # Example with a direct proxy URL session_direct = AiohttpSession(proxy="socks5://user:password@host:port") # Example with a chained proxy configuration session_chained = AiohttpSession(proxy=[ "socks5://user:password@host1:port1", ("http://user:password@host2:port2", BasicAuth("user", "password")), ]) ``` -------------------------------- ### Start Command Handler Source: https://docs.aiogram.dev/en/dev-3.x/dispatcher/finite_state_machine/scene.html Handles the '/start' command, closes any active scenes, and provides introductory message. ```python await scenes.close() await message.answer( "Hi! This is a quiz bot. To start the quiz, use the /quiz command.", reply_markup=ReplyKeyboardRemove(), ) ``` -------------------------------- ### Register scene as a handler Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/finite_state_machine/scene.rst.txt Shows how to convert a scene's entry point into a handler and register it with a router. ```python from aiogram.fsm.scene import Scene from aiogram.filters.command import Command from aiogram import router # Assuming SettingsScene is a defined Scene class # router.message.register(SettingsScene.as_handler(), Command("settings")) ``` -------------------------------- ### Install aiogram with i18n dependency Source: https://docs.aiogram.dev/en/dev-3.x/_sources/migration_2_to_3.rst.txt If your application uses translation functionality, install aiogram with the optional i18n dependency. ```bash pip install aiogram[i18n] ``` -------------------------------- ### Install aiogram Development Build from GitHub Source: https://docs.aiogram.dev/en/dev-3.x/_sources/install.rst.txt Install the latest development version of aiogram directly from its GitHub repository. ```bash pip install https://github.com/aiogram/aiogram/archive/refs/heads/dev-3.x.zip ``` -------------------------------- ### Install aiogram from PyPI Source: https://docs.aiogram.dev/en/dev-3.x/_sources/install.rst.txt Use this command to install the latest stable version of aiogram from the Python Package Index. ```bash pip install -U aiogram ``` -------------------------------- ### Run the bot example Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/finite_state_machine/scene.rst.txt This snippet shows how to run the bot and test the quiz game functionality. ```python async def main(): # ... bot setup ... await dp.start_polling(bot) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main()) ``` -------------------------------- ### Install Project Dependencies (Linux/macOS) Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Install aiogram from source along with all development and testing dependencies on Linux or macOS. ```bash pip install -e ."[dev,test,docs,fast,redis,mongo,proxy,i18n]" ``` -------------------------------- ### Build and Serve Docs with uv and Sphinx-Autobuild Source: https://docs.aiogram.dev/en/dev-3.x/_sources/contributing.rst.txt Use uv to manage dependencies while serving documentation with sphinx-autobuild. This ensures a consistent build environment. ```bash uv run --extra docs sphinx-autobuild --watch aiogram/ docs/ docs/_build/ ``` -------------------------------- ### View Translated Documentation Source: https://docs.aiogram.dev/en/dev-3.x/contributing.html Serve the documentation with a specific language enabled for preview. Use traditional execution or uv. ```bash sphinx-autobuild --watch aiogram/ docs/ docs/_build/ -D language= ``` ```bash uv run --extra docs sphinx-autobuild --watch aiogram/ docs/ docs/_build/ -D language= ``` -------------------------------- ### Get Webhook Info as Bot Method Source: https://docs.aiogram.dev/en/dev-3.x/_sources/api/methods/get_webhook_info.rst.txt Use this method directly on the bot object to get webhook information. ```python result: WebhookInfo = await bot.get_webhook_info(...) ``` -------------------------------- ### Send Document Example Source: https://docs.aiogram.dev/en/dev-3.x/_modules/aiogram/client/bot.html Example of sending a document with various optional parameters. This method is used for sending files to a chat. ```python call = SendDocument( chat_id=chat_id, document=document, business_connection_id=business_connection_id, message_thread_id=message_thread_id, direct_messages_topic_id=direct_messages_topic_id, thumbnail=thumbnail, caption=caption, parse_mode=parse_mode, caption_entities=caption_entities, disable_content_type_detection=disable_content_type_detection, disable_notification=disable_notification, protect_content=protect_content, allow_paid_broadcast=allow_paid_broadcast, message_effect_id=message_effect_id, suggested_post_parameters=suggested_post_parameters, reply_parameters=reply_parameters, reply_markup=reply_markup, allow_sending_without_reply=allow_sending_without_reply, reply_to_message_id=reply_to_message_id, ) return await self(call, request_timeout=request_timeout) ``` -------------------------------- ### Function-based Outer Middleware Example Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/middlewares.rst.txt Define a middleware as an asynchronous function decorated with `@dispatcher.update.outer_middleware()`. This example shows how to manage database transactions. ```python @dispatcher.update.outer_middleware() async def database_transaction_middleware( handler: Callable[[Update, Dict[str, Any]], Awaitable[Any]], event: Update, data: Dict[str, Any] ) -> Any: async with database.transaction(): return await handler(event, data) ``` -------------------------------- ### Example: Setting Default Parse Mode Source: https://docs.aiogram.dev/en/dev-3.x/api/defaults.html Demonstrates how to initialize a Bot instance with a default parse mode (HTML) and how to override it for specific messages. ```APIDOC ## Example: Default Parse Mode ### Description This example shows how to set a default parse mode for all messages sent by a bot and how to override it for individual messages. ### Usage Initialize the Bot with `DefaultBotProperties`: ```python bot = Bot( token=..., default=DefaultBotProperties( parse_mode=ParseMode.HTML, ) ) ``` Send a message using the default parse mode: ```python await bot.send_message(chat_id, text) ``` Override the default parse mode for a specific message: ```python await bot.send_message(chat_id, text, parse_mode=ParseMode.MARKDOWN_V2) ``` Disable parse mode for a specific message: ```python await bot.send_message(chat_id, text, parse_mode=None) ``` Send a message with explicit entities and no parse mode: ```python await bot.send_message( chat_id=chat_id, text=text, entities=[MessageEntity(type='bold', offset=0, length=4)], parse_mode=None ) ``` ``` -------------------------------- ### Emit Startup Event Source: https://docs.aiogram.dev/en/dev-3.x/_modules/aiogram/dispatcher/router.html Recursively calls startup callbacks for the current router and all its sub-routers. Passes router instance as a keyword argument. ```python async def emit_startup(self, *args: Any, **kwargs: Any) -> None: """ Recursively call startup callbacks :param args: :param kwargs: :return: """ kwargs.update(router=self) await self.startup.trigger(*args, **kwargs) for router in self.sub_routers: await router.emit_startup(*args, **kwargs) ``` -------------------------------- ### Start Dialog and Transition to Form.name Source: https://docs.aiogram.dev/en/dev-3.x/_sources/dispatcher/finite_state_machine/index.rst.txt Handle the initial command to start the dialog and transition the user to the 'name' state within the FSM. ```python @dp.message_handler(state=None) async def command_start(message: types.Message): await Form.name.set() await message.reply("What is your name?") ``` -------------------------------- ### Get File Information (Bot Method) Source: https://docs.aiogram.dev/en/dev-3.x/api/methods/get_file.html Use this snippet as a bot method to get file information. The result will be a File object. ```python result: File = await bot.get_file(...) ```