### aiogram Deep Linking Examples Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/wiki Provides examples of how to implement deep linking in aiogram, allowing users to start a bot with a specific payload or state. ```python # Example of handling a deep link # @router.message() # async def handle_deep_link(message: types.Message): # if message.text.startswith('/start '): # payload = message.text.split(' ', 1)[1] # await message.answer(f'Received payload: {payload}') ``` -------------------------------- ### aiogram Deep Linking Examples Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/via-filters Provides examples of how to implement deep linking in aiogram, allowing users to start a bot with a specific payload or state. ```python # Example of handling a deep link # @router.message() # async def handle_deep_link(message: types.Message): # if message.text.startswith('/start '): # payload = message.text.split(' ', 1)[1] # await message.answer(f'Received payload: {payload}') ``` -------------------------------- ### AiohttpSession Initialization and Proxy Setup Source: https://docs.aiogram.dev/en/v3.22.0/_modules/aiogram/client/session/aiohttp Initializes the AiohttpSession with optional proxy support and connection limits. If a proxy is provided, it attempts to set up the proxy connector, raising a RuntimeError if the 'aiohttp-socks' library is not installed. ```Python class AiohttpSession(BaseSession): def __init__( self, proxy: Optional[_ProxyType] = None, limit: int = 100, **kwargs: Any, ) -> None: """ Client session based on aiohttp. :param proxy: The proxy to be used for requests. Default is None. :param limit: The total number of simultaneous connections. Default is 100. :param kwargs: Additional keyword arguments. """ super().__init__(**kwargs) self._session: Optional[ClientSession] = None self._connector_type: Type[TCPConnector] = TCPConnector self._connector_init: Dict[str, Any] = { "ssl": ssl.create_default_context(cafile=certifi.where()), "limit": limit, "ttl_dns_cache": 3600, # Workaround for https://github.com/aiogram/aiogram/issues/1500 } self._should_reset_connector = True # flag determines connector state self._proxy: Optional[_ProxyType] = None if proxy is not None: try: self._setup_proxy_connector(proxy) except ImportError as exc: # pragma: no cover raise RuntimeError( "In order to use aiohttp client for proxy requests, install " "https://pypi.org/project/aiohttp-socks/" ) from exc def _setup_proxy_connector(self, proxy: _ProxyType) -> None: self._connector_type, self._connector_init = _prepare_connector(proxy) self._proxy = proxy @property def proxy(self) -> Optional[_ProxyType]: return self._proxy @proxy.setter def proxy(self, proxy: _ProxyType) -> None: self._setup_proxy_connector(proxy) self._should_reset_connector = True ``` -------------------------------- ### Start Live Docs Preview Source: https://docs.aiogram.dev/en/v3.22.0/contributing Starts a live preview server for the aiogram documentation using sphinx-autobuild, watching for changes in the aiogram directory. ```bash sphinx-autobuild --watch aiogram/ docs/ docs/_build/ ``` -------------------------------- ### Webhook Initialization and Setup Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/webhook Configures and starts an aiohttp web server for handling Telegram webhooks. Includes setting the webhook URL, certificate, and secret token. ```Python import ssl import logging import sys from aiogram import Bot, Dispatcher from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.types import FSInputFile from aiohttp import web from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application # Assume these constants are defined elsewhere # BASE_WEBHOOK_URL = "YOUR_BASE_URL" # WEBHOOK_PATH = "/webhook/" # WEBHOOK_SSL_CERT = "path/to/your/cert.pem" # WEBHOOK_SSL_PRIV = "path/to/your/private.key" # WEBHOOK_SECRET = "YOUR_SECRET_TOKEN" # TOKEN = "YOUR_BOT_TOKEN" # WEB_SERVER_HOST = "0.0.0.0" # WEB_SERVER_PORT = 8080 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) # Assuming 'router' is defined elsewhere # 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() ``` -------------------------------- ### aiogram Simple Usage Example Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/wiki This Python code demonstrates a simple aiogram bot setup. It includes handlers for the `/start` command and a general message echo handler. The bot uses asyncio for asynchronous operations and aiogram's Dispatcher to manage incoming messages. It requires a Telegram Bot API token and is configured to use HTML parse mode. ```python import asyncio import logging import sys from os import getenv from aiogram import Bot, Dispatcher, html from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import Message # Bot token can be obtained via https://t.me/BotFather TOKEN = getenv("BOT_TOKEN") # All handlers should be attached to the Router (or Dispatcher) dp = Dispatcher() @dp.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, {html.bold(message.from_user.full_name)}!") @dp.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 a 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 main() -> None: # 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)) # And the run events dispatching await dp.start_polling(bot) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main()) ``` -------------------------------- ### Install aiogram from GitHub Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/wiki Installs aiogram directly from its GitHub repository. This is useful for installing the latest development version or a specific commit. ```bash pip install git+https://github.com/aiogram/aiogram.git ``` -------------------------------- ### aiogram Simple Usage Example Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/via-filters This Python code demonstrates a simple aiogram bot setup. It includes handlers for the `/start` command and a general message echo handler. The bot uses asyncio for asynchronous operations and aiogram's Dispatcher to manage incoming messages. It requires a Telegram Bot API token and is configured to use HTML parse mode. ```python import asyncio import logging import sys from os import getenv from aiogram import Bot, Dispatcher, html from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import Message # Bot token can be obtained via https://t.me/BotFather TOKEN = getenv("BOT_TOKEN") # All handlers should be attached to the Router (or Dispatcher) dp = Dispatcher() @dp.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, {html.bold(message.from_user.full_name)}!") @dp.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 a 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 main() -> None: # 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)) # And the run events dispatching await dp.start_polling(bot) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main()) ``` -------------------------------- ### Complete aiogram Bot Example Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/index This is a comprehensive example of an aiogram bot that guides users through a series of questions to gather information. It uses the Finite State Machine (FSM) to manage the conversation flow, handles commands like /start and /cancel, and responds to user input with specific actions. The bot collects the user's name, whether they like writing bots, and their preferred programming language, then summarizes the collected information. ```Python import asyncio import logging import sys from os import getenv from typing import Any, Dict from aiogram import Bot, Dispatcher, F, Router, html from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import Command, CommandStart from aiogram.fsm.context import FSMContext from aiogram.fsm.state import State, StatesGroup from aiogram.types import ( KeyboardButton, Message, ReplyKeyboardMarkup, ReplyKeyboardRemove, ) TOKEN = getenv("BOT_TOKEN") form_router = Router() class Form(StatesGroup): name = State() like_bots = State() language = State() @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(), ) @form_router.message(Command("cancel")) @form_router.message(F.text.casefold() == "cancel") async def cancel_handler(message: Message, state: FSMContext) -> None: """ Allow user to cancel any action """ current_state = await state.get_state() if current_state is None: return logging.info("Cancelling state %r", current_state) await state.clear() await message.answer( "Cancelled.", reply_markup=ReplyKeyboardRemove(), ) @form_router.message(Form.name) async def process_name(message: Message, state: FSMContext) -> None: await state.update_data(name=message.text) await state.set_state(Form.like_bots) await message.answer( f"Nice to meet you, {html.quote(message.text)}!\nDid you like to write bots?", reply_markup=ReplyKeyboardMarkup( keyboard=[ [ KeyboardButton(text="Yes"), KeyboardButton(text="No"), ] ], resize_keyboard=True, ), ) @form_router.message(Form.like_bots, F.text.casefold() == "no") async def process_dont_like_write_bots(message: Message, state: FSMContext) -> None: data = await state.get_data() await state.clear() await message.answer( "Not bad not terrible.\nSee you soon.", reply_markup=ReplyKeyboardRemove(), ) await show_summary(message=message, data=data, positive=False) @form_router.message(Form.like_bots, F.text.casefold() == "yes") async def process_like_write_bots(message: Message, state: FSMContext) -> None: await state.set_state(Form.language) await message.reply( "Cool! I'm too!\nWhat programming language did you use for it?", reply_markup=ReplyKeyboardRemove(), ) @form_router.message(Form.like_bots) async def process_unknown_write_bots(message: Message) -> None: await message.reply("I don't understand you :(") @form_router.message(Form.language) async def process_language(message: Message, state: FSMContext) -> None: data = await state.update_data(language=message.text) await state.clear() if message.text.casefold() == "python": await message.reply( "Python, you say? That's the language that makes my circuits light up! 😉" ) await show_summary(message=message, data=data) async def show_summary(message: Message, data: Dict[str, Any], positive: bool = True) -> None: name = data["name"] language = data.get("language", "") text = f"I'll keep in mind that, {html.quote(name)}, " text += ( f"you like to write bots with {html.quote(language)}." if positive else "you don't like to write bots, so sad..." ) await message.answer(text=text, reply_markup=ReplyKeyboardRemove()) async def main(): # 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)) dp = Dispatcher() dp.include_router(form_router) # Start event dispatching await dp.start_polling(bot) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main()) ``` -------------------------------- ### Complete FSM Example - Python Source: https://docs.aiogram.dev/en/v3.22.0/_sources/dispatcher/finite_state_machine/index Provides a complete, runnable example of an FSM implementation in aiogram, covering multiple states and transitions. ```python import asyncio from enum import Enum from aiogram import Bot, Dispatcher, types from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from aiogram.utils import executor API_TOKEN = '...' # For example, a simple state machine for collecting data class Form(Enum): """A collection of states""" name = 1 like_bots = 2 language = 3 # Initialize bot and dispatcher bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) @dp.message_handler(commands=['start']) async def command_start(message: types.Message): """User starts dialog and enters 'name' state""" # Flushes all user data when new dialog starts await Form.name.set() # set initial state await message.reply("I need your name") @dp.message_handler(state=Form.name) async def process_name(message: types.Message, state: FSMContext): """Save user name and ask about favorite bots""" async with state.proxy() as data: data['name'] = message.text # finishing current state await Form.next() await message.reply("What is your favorite bot?") @dp.message_handler(lambda message: not message.text.startswith("/"), state=Form.like_bots) async def process_like_write_bots(message: types.Message, state: FSMContext): """Save favorite bot and ask about programming language""" async with state.proxy() as data: data['like_bots'] = message.text await Form.next() await message.reply("Perfect, which programming language do you want to learn?") @dp.message_handler(state='*', commands='cancel') @dp.message_handler(Text(equals='cancel', ignore_case=True), state='*') async def cancel_handler(message: types.Message, state: FSMContext): """Allow user to cancel any action""" current_state = await state.get_state() if current_state is None: # User is in no state, so ignore it return await state.finish() await message.reply('Cancelled.') @dp.message_handler(state=Form.language) async def process_language(message: types.Message, state: FSMContext): """Save language and finish conversation""" async with state.proxy() as data: data['language'] = message.text await message.reply("Done, thank you!") # Fetch data from state storage await message.answer(str(data)) # Finish conversation await state.finish() if __name__ == '__main__': executor.start_polling(dp, skip_updates=True) ``` -------------------------------- ### BaseStorage Methods for State and Data Management Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/index Provides examples of core methods in BaseStorage for managing bot states and data, including setting, getting, updating, and closing storage connections. ```Python await base_storage.set_state(state) await base_storage.get_state() await base_storage.set_data(data) await base_storage.get_data() await base_storage.update_data(data) await base_storage.close() ``` -------------------------------- ### Start FSM Dialog - Python Source: https://docs.aiogram.dev/en/v3.22.0/_sources/dispatcher/finite_state_machine/index Handles the '/start' command to initiate a dialog and transitions the user to the 'Form.name' state, starting the FSM process. ```python @dp.message_handler(commands=['start']) async def command_start(message: types.Message): """User starts dialog and enters 'name' state""" # Flushes all user data when new dialog starts await Form.name.set() # set initial state await message.reply("I need your name") ``` -------------------------------- ### Quiz Example Source: https://docs.aiogram.dev/en/v3.22.0/_sources/dispatcher/finite_state_machine/scene This is a comprehensive example of a quiz game implemented using aiogram scenes, showcasing various handlers and transitions. ```python # Example code for quiz_scene.py would go here, demonstrating Scene, on.exit, on.leave, etc. ``` -------------------------------- ### Install aiogram from PyPI Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/wiki Installs the aiogram library using pip, the Python package installer. This is the most common method for obtaining the latest stable release. ```bash pip install aiogram ``` -------------------------------- ### Aiogram Multi-file Bot Example Source: https://docs.aiogram.dev/en/v3.22.0/changelog Includes a multi-file bot example in the Aiogram repository. This provides a practical demonstration of how to structure larger Aiogram projects. ```Python # This update includes the addition of a multi-file bot example to the repository. ``` -------------------------------- ### Start Sphinx Live Preview Source: https://docs.aiogram.dev/en/v3.22.0/_sources/contributing Builds and serves the documentation locally using sphinx-autobuild, allowing for live preview of changes as they are made. ```bash sphinx-autobuild --watch aiogram/ docs/ docs/_build/ ``` -------------------------------- ### Combine filters with OR operator Source: https://docs.aiogram.dev/en/v3.22.0/_sources/dispatcher/filters/magic_filters This example combines two filters using the bitwise OR operator. It passes if the text starts with 'a' OR ends with 'b'. ```python F.text.startswith('a') | F.text.endswith('b') ``` -------------------------------- ### View Translated Documentation Source: https://docs.aiogram.dev/en/v3.22.0/contributing Starts a live preview server for the aiogram documentation, rendering it in a specified language. ```bash sphinx-autobuild --watch aiogram/ docs/ docs/_build/ -D language= ``` -------------------------------- ### Create Basic Start Link with aiogram Source: https://docs.aiogram.dev/en/v3.22.0/utils/deep_linking Demonstrates how to create a basic deep link using the `create_start_link` function from aiogram. This link can be used to pass parameters to a bot on startup. ```Python from aiogram.utils.deep_linking import create_start_link link = await create_start_link(bot, 'foo') # result: 'https://t.me/MyBot?start=foo' ``` -------------------------------- ### I18nMiddleware Configuration and Locale Handling Source: https://docs.aiogram.dev/en/v3.22.0/utils/index Details the setup and usage of I18nMiddleware for internationalization, including methods to get and set the current locale. ```python from aiogram.contrib.middlewares.i18n import I18nMiddleware # Assuming 'dp' is your Dispatcher instance dp.middleware.setup(I18nMiddleware(locale='en', path='locales')) # To get the current locale: # current_locale = dp.current_state().get_state_data().get('locale') # To set the locale (example within a handler): # await dp.storage.set_state_data(chat=message.chat.id, data={'locale': 'es'}) ``` -------------------------------- ### AiohttpSession with Proxy Source: https://docs.aiogram.dev/en/v3.22.0/api/session/aiohttp This example shows how to configure AiohttpSession to use proxy requests. It requires the aiohttp-socks library to be installed. The proxy can be specified as a URL string. ```python from aiogram import Bot from aiogram.client.session.aiohttp import AiohttpSession session = AiohttpSession(proxy="protocol://host:port/") bot = Bot(token="bot token", session=session) ``` -------------------------------- ### Start Dialog and Transition to Name State Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/index Handles the initial `/start` command to begin a dialog, sets the user's state to `Form.name`, and prompts for their name. This is the entry point for the FSM-driven conversation. ```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(), ) ``` -------------------------------- ### Initialize Dispatcher Source: https://docs.aiogram.dev/en/v3.22.0/_sources/dispatcher/dispatcher Demonstrates the basic initialization of an aiogram Dispatcher instance. This is the starting point for setting up event handling. ```python dp = Dispatcher() ``` -------------------------------- ### Setup Development Environment with Virtualenv Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/via-filters This section guides users on setting up a virtual environment for aiogram development. It covers activating the environment and preparing the project for making changes. ```Bash virtualenv venv . venv/bin/activate ``` -------------------------------- ### Get File Path using Aiogram Source: https://docs.aiogram.dev/en/v3.22.0/_sources/api/download_file After obtaining the file_id, this code demonstrates how to use the `get_file` method to fetch the file_path from the Telegram API via Aiogram. ```Python file = await bot.get_file(file_id) file_path = file.file_path ``` -------------------------------- ### Get File ID for Aiogram Download Source: https://docs.aiogram.dev/en/v3.22.0/_sources/api/download_file This snippet shows how to retrieve the file_id from an incoming message, which is the first step in manually downloading a file using Aiogram. ```Python file_id = message.document.file_id ``` -------------------------------- ### Initialize Router and Command Handler Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/webhook Sets up a basic Aiogram router and a handler for the `/start` command. The handler sends a personalized greeting to the user. ```Python from aiogram import Bot, Dispatcher, Router, types from aiogram.filters.command import CommandStart from aiogram.utils.markdown import hbold router = Router() @router.message(CommandStart()) async def command_start_handler(message: types.Message) -> None: """ This handler receives messages with `/start` command """ await message.answer(f"Hello, {hbold(message.from_user.full_name)}!") ``` -------------------------------- ### Setup aiohttp Application for aiogram Source: https://docs.aiogram.dev/en/v3.22.0/_modules/aiogram/webhook/aiohttp_server Configures the startup and shutdown processes for an aiohttp application integrated with an aiogram dispatcher. It emits startup and shutdown signals to the dispatcher. ```Python import asyncio import secrets from abc import ABC, abstractmethod from asyncio import Transport from typing import Any, Awaitable, Callable, Dict, Optional, Set, Tuple, cast from aiohttp import JsonPayload, MultipartWriter, Payload, web from aiohttp.typedefs import Handler from aiohttp.web_app import Application from aiohttp.web_middlewares import middleware from aiogram import Bot, Dispatcher, loggers from aiogram.methods import TelegramMethod from aiogram.methods.base import TelegramType from aiogram.types import InputFile from aiogram.webhook.security import IPFilter def setup_application(app: Application, dispatcher: Dispatcher, /, **kwargs: Any) -> None: """ This function helps to configure a startup-shutdown process :param app: aiohttp application :param dispatcher: aiogram dispatcher :param kwargs: additional data :return: """ workflow_data = { "app": app, "dispatcher": dispatcher, **dispatcher.workflow_data, **kwargs, } async def on_startup(*a: Any, **kw: Any) -> None: # pragma: no cover await dispatcher.emit_startup(**workflow_data) async def on_shutdown(*a: Any, **kw: Any) -> None: # pragma: no cover await dispatcher.emit_shutdown(**workflow_data) app.on_startup.append(on_startup) app.on_shutdown.append(on_shutdown) ``` -------------------------------- ### Short Way to Download File with Aiogram Source: https://docs.aiogram.dev/en/v3.22.0/_sources/api/download_file This example shows the shortcut method `download` in Aiogram, which allows downloading a file directly using a `file_id` or a `Downloadable` object, simplifying the process. ```Python document = message.document await bot.download(document) ``` -------------------------------- ### RedisStorage Initialization from URL Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/storages Creates an instance of RedisStorage by providing a Redis connection string URL. This method simplifies the setup process for Redis connections. It accepts optional connection keyword arguments and other parameters for RedisStorage. ```python from aiogram.fsm.storage.redis import RedisStorage redis_url = "redis://user:password@host:port/db" storage = RedisStorage.from_url(redis_url) ``` -------------------------------- ### Migrate to PyMongoStorage Source: https://docs.aiogram.dev/en/v3.22.0/changelog This guide explains the migration from `MongoStorage` (using the deprecated `motor` package) to `PyMongoStorage` (using the new `async` PyMongo). It highlights that only the package installation and class substitution are required, simplifying the transition. ```python # Before migration (using motor): # from aiogram.contrib.fsm_storage.memory import MemoryStorage # from aiogram.contrib.fsm_storage.mongo import MongoStorage # storage = MongoStorage(host='mongodb://localhost:27017/mydatabase') # After migration (using PyMongo): from aiogram.fsm.storage.mongo import MongoStorage # Ensure you have installed PyMongo: pip install pymongo storage = MongoStorage(host='mongodb://localhost:27017/mydatabase') ``` -------------------------------- ### Download File to Disk with Aiogram Source: https://docs.aiogram.dev/en/v3.22.0/_sources/api/download_file This example illustrates how to download a file to a specified path on the disk using the `download_file` method in Aiogram. The method returns nothing upon successful download to disk. ```Python await bot.download_file(file_path, "text.txt") ``` -------------------------------- ### Download File to Binary I/O Object with Aiogram (Default) Source: https://docs.aiogram.dev/en/v3.22.0/_sources/api/download_file This example demonstrates downloading a file to a default `io.BytesIO` object using Aiogram's `download_file` method when no destination is specified. The method returns the created BytesIO object. ```Python result: io.BytesIO = await bot.download_file(file_path) ``` -------------------------------- ### Create Scene Entry Point Handler in aiogram Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/scene Shows how to create an entry point handler for a scene using the `as_handler` class method. This simplifies the process of starting a scene from a handler. ```python _aiogram.fsm.scene.Scene._as_handler(_** handler_kwargs: Any_) ``` -------------------------------- ### Setup aiogram Webhook Behind Reverse Proxy Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/webhook This example demonstrates how to configure an aiogram bot to use webhooks when running behind a reverse proxy such as Nginx. It sets up an aiohttp web server to handle incoming Telegram requests and includes essential bot and webhook configurations. ```Python import logging 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 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 DNS with HTTPS support BASE_WEBHOOK_URL = "https://aiogram.dev" ``` -------------------------------- ### PyMongoStorage Initialization from URL Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/storages Creates an instance of PyMongoStorage using a MongoDB connection string URL. This simplifies the connection setup for MongoDB. It accepts optional connection keyword arguments and other parameters for PyMongoStorage. ```python from aiogram.fsm.storage.pymongo import PyMongoStorage mongo_url = "mongodb://user:password@host:port" storage = PyMongoStorage.from_url(mongo_url) ``` -------------------------------- ### Initialize Dispatcher and Handle Messages Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/dispatcher Demonstrates how to initialize a Dispatcher and define a message handler to send a reply. This is a basic example of setting up event handling in aiogram. ```python dp = Dispatcher() @dp.message() async def message_handler(message: types.Message) -> None: await SendMessage(chat_id=message.from_user.id, text=message.text) ``` -------------------------------- ### Install aiogram from GitHub Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/via-filters Installs aiogram directly from its GitHub repository. This is useful for installing the latest development version or a specific commit. ```bash pip install git+https://github.com/aiogram/aiogram.git ``` -------------------------------- ### RedisStorage Initialization and URL Configuration Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/index Demonstrates how to initialize RedisStorage and configure it using a connection URL. This is useful for setting up persistent storage for bot states and data. ```Python redis_storage = RedisStorage(redis_client) redis_storage = RedisStorage.from_url("redis://localhost:6379/0") ``` -------------------------------- ### Invert filter result (not starts with) Source: https://docs.aiogram.dev/en/v3.22.0/_sources/dispatcher/filters/magic_filters This filter inverts the result of checking if the 'text' attribute starts with 'spam'. It passes if the text does not start with 'spam'. ```python ~F.text.startswith('spam') # lambda message: not message.text.startswith('spam') ``` -------------------------------- ### Install aiogram from PyPI Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/via-filters Installs the aiogram library using pip, the Python package installer. This is the most common method for obtaining the latest stable release. ```bash pip install aiogram ``` -------------------------------- ### Install aiogram from PyPI Source: https://docs.aiogram.dev/en/v3.22.0/install Installs or upgrades the aiogram library to the latest version available on the Python Package Index (PyPI). This is the recommended method for most users. ```bash pip install -U aiogram ``` -------------------------------- ### MongoStorage Initialization from URL (Deprecated) Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/finite_state_machine/storages Creates an instance of the deprecated MongoStorage using a MongoDB connection string URL. This simplifies the connection setup. It accepts optional connection keyword arguments and other parameters. Use PyMongoStorage instead. ```python from aiogram.fsm.storage.mongo import MongoStorage mongo_url = "mongodb://user:password@host:port" storage = MongoStorage.from_url(mongo_url) ``` -------------------------------- ### Install Babel for Aiogram Source: https://docs.aiogram.dev/en/v3.22.0/_sources/utils/i18n Installs the Babel library, which is required for extracting translation strings from aiogram code. It can be installed via pip or as an extra dependency of aiogram. ```bash pip install Babel ``` ```bash pip install aiogram[i18n] ``` -------------------------------- ### SimpleRequestHandler Initialization and Methods Source: https://docs.aiogram.dev/en/v3.22.0/dispatcher/index Demonstrates the initialization and key methods of SimpleRequestHandler for processing webhook requests, including registration and bot resolution. ```Python handler = SimpleRequestHandler(webhook_info) handler.close() handler.register(webhook_info) handler.resolve_bot(webhook_info) ``` -------------------------------- ### Scene Handler Registration Source: https://docs.aiogram.dev/en/v3.22.0/_sources/dispatcher/finite_state_machine/scene Demonstrates how to register a scene's entry point as a handler using the 'as_handler()' method with a command. ```python from aiogram import F, Router from aiogram.filters import Command from aiogram.types import Message router = Router() # Assuming SettingsScene is defined elsewhere # class SettingsScene(Scene): # ... # router.message.register(SettingsScene.as_handler(), Command("settings")) ``` -------------------------------- ### Install Babel for aiogram Source: https://docs.aiogram.dev/en/v3.22.0/utils/i18n Installs the Babel library, which is required for extracting translation strings from your aiogram code. It can be installed directly via pip or as an extra dependency of aiogram. ```bash pip install Babel ``` ```bash pip install aiogram[i18n] ``` -------------------------------- ### Aiogram Examples Refactoring with Enumerations and Markdown Source: https://docs.aiogram.dev/en/v3.22.0/changelog Refactors Aiogram's example code to use Aiogram enumerations and enhances chat messages with markdown beautification. This improves the clarity and presentation of the examples. ```Python # Refactored examples code to use aiogram enumerations and enhanced chat messages with markdown beautification’s for a more user-friendly display. ```