### Integrate PyrogramAlbumMiddleware with Pyrogram Client Source: https://github.com/rootshinobi/aiogram_album/blob/main/README.md This snippet illustrates initializing PyrogramAlbumMiddleware using an existing Pyrogram Client instance. It requires the Pyrogram client to be started before initializing the middleware. Dependencies include aiogram_album, Pyrogram, cachetools, and TgCrypto. ```python from aiogram_album.pyrogram_album.middleware import PyrogramAlbumMiddleware from pyrogram import Client from aiogram import Bot bot = Bot(BOT_TOKEN) client = Client(str(bot.id), bot_token=BOT_TOKEN, api_hash=API_HASH, api_id=API_ID, no_updates=True) await client.start() PyrogramAlbumMiddleware( client=client, router=dp, ) ``` -------------------------------- ### Use WithoutCountCheckAlbumMiddleware for Unrestricted Album Handling Source: https://github.com/rootshinobi/aiogram_album/blob/main/README.md This example shows how to use WithoutCountCheckAlbumMiddleware, which bypasses any count checks for albums. This middleware is suitable when there are no restrictions on the number of items in a media album. It requires installing the aiogram_album package. ```python from aiogram_album.no_check_count_middleware import WithoutCountCheckAlbumMiddleware WithoutCountCheckAlbumMiddleware(router=dp) ``` -------------------------------- ### Use TTLCacheAlbumMiddleware for Album Caching Source: https://github.com/rootshinobi/aiogram_album/blob/main/README.md This example shows how to implement TTLCacheAlbumMiddleware to manage album caching with a time-to-live (TTL) policy. This middleware helps in efficiently handling album data by setting expiration times. It requires installing aiogram_album and cachetools. ```python from aiogram_album.ttl_cache_middleware import TTLCacheAlbumMiddleware TTLCacheAlbumMiddleware(router=dp) ``` -------------------------------- ### Initialize aiogram Album with Existing Pyrogram Client Source: https://context7.com/rootshinobi/aiogram_album/llms.txt This snippet shows how to initialize aiogram's Album middleware using an existing Pyrogram client instance. It requires Pyrogram and aiogram_album libraries. The function starts the Pyrogram client and then sets up the PyrogramAlbumMiddleware. ```python from pyrogram import Client from aiogram_album import PyrogramAlbumMiddleware async def setup_with_client(): client = Client( name=str(bot.id), bot_token=BOT_TOKEN, api_hash=API_HASH, api_id=API_ID, no_updates=True ) await client.start() PyrogramAlbumMiddleware( client=client, router=router ) dp.include_router(router) ``` -------------------------------- ### Integrate PyrogramAlbumMiddleware with Bot Token Source: https://github.com/rootshinobi/aiogram_album/blob/main/README.md This code shows how to initialize PyrogramAlbumMiddleware using bot token, API ID, and API HASH. This middleware is essential for integrating Pyrogram's capabilities with aiogram for album handling. It requires installing aiogram_album, Pyrogram, cachetools, and TgCrypto. ```python from aiogram_album.pyrogram_album.middleware import PyrogramAlbumMiddleware await PyrogramAlbumMiddleware.from_app_data( bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH, router=dp, ) ``` -------------------------------- ### Apply LockAlbumMiddleware for Concurrent Album Access Control Source: https://github.com/rootshinobi/aiogram_album/blob/main/README.md This code demonstrates how to use LockAlbumMiddleware to prevent concurrent access to media albums, ensuring data integrity when multiple requests might interact with the same album. It requires installing aiogram_album and cachetools. ```python from aiogram_album.lock_middleware import LockAlbumMiddleware LockAlbumMiddleware(router=dp) ``` -------------------------------- ### Implement CountCheckAlbumMiddleware for Album Count Validation Source: https://github.com/rootshinobi/aiogram_album/blob/main/README.md This snippet demonstrates the usage of CountCheckAlbumMiddleware, which enforces a check on the number of items within an album. This is useful for setting limits on media albums. It requires installing the aiogram_album package. ```python from aiogram_album.count_check_middleware import CountCheckAlbumMiddleware CountCheckAlbumMiddleware(router=dp) ``` -------------------------------- ### Use CountCheckAlbumMiddleware for Stable Album Validation Source: https://context7.com/rootshinobi/aiogram_album/llms.txt This example demonstrates the CountCheckAlbumMiddleware, which validates message count stability before processing albums. It requires aiogram and aiogram_album. The middleware ensures that all expected messages in an album arrive before proceeding. ```python from aiogram import Dispatcher, Bot, Router, F from aiogram.types import Message from aiogram_album import AlbumMessage from aiogram_album.count_check_middleware import CountCheckAlbumMiddleware BOT_TOKEN = "your_bot_token_here" bot = Bot(token=BOT_TOKEN) dp = Dispatcher() router = Router() # Middleware with count verification CountCheckAlbumMiddleware( latency=0.1, # Check interval in seconds router=router ) @router.message(F.media_group_id) async def verified_album_handler(message: AlbumMessage): """Processes only when album count is stable""" await message.reply(f"Verified complete album: {len(message)} items") # Access individual messages for i, msg in enumerate(message): if msg.photo: photo = msg.photo[-1] # Highest resolution await message.answer( f"Photo {i+1}: {photo.width}x{photo.height}" ) elif msg.video: await message.answer( f"Video {i+1}: {msg.video.duration}s" ) @router.message() async def single_message_handler(message: Message): """Regular messages bypass album middleware""" await message.reply("Single message received") dp.include_router(router) ``` -------------------------------- ### Channel Post Support for Albums Source: https://context7.com/rootshinobi/aiogram_album/llms.txt Handles media groups in channels and private chats using aiogram_album. The LockAlbumMiddleware automatically manages both message types. Examples show how to handle albums in private chats and channel posts, including forwarding channel albums to an admin. It also includes handlers for non-album messages and channel posts. ```python from aiogram import Dispatcher, Bot, Router, F from aiogram.types import Message from aiogram_album import AlbumMessage from aiogram_album.lock_middleware import LockAlbumMiddleware BOT_TOKEN = "your_bot_token_here" bot = Bot(token=BOT_TOKEN) dp = Dispatcher() router = Router() # Middleware automatically handles both messages and channel posts middleware = LockAlbumMiddleware(router=router) @router.message(F.media_group_id) async def message_album_handler(message: AlbumMessage): """Handles albums in private chats and groups""" await message.reply(f"Message album: {len(message)} items") @router.channel_post(F.media_group_id) async def channel_album_handler(message: AlbumMessage): """Handles albums posted in channels""" # Note: Cannot reply in channels, use answer instead await message.answer( f"Channel album detected: {len(message)} items\n" f"Channel: {message.chat.title}" ) # Forward channel album to admin ADMIN_ID = 123456789 await message.forward(chat_id=ADMIN_ID) @router.message() async def single_message(message: Message): """Non-album messages""" await message.reply("Single message received") @router.channel_post() async def single_channel_post(message: Message): """Non-album channel posts""" print(f"Channel post: {message.text}") dp.include_router(router) ``` -------------------------------- ### Integrate PyrogramAlbumMiddleware for Accurate Album Retrieval in aiogram Source: https://context7.com/rootshinobi/aiogram_album/llms.txt Demonstrates integrating PyrogramAlbumMiddleware to leverage Pyrogram's API for accurate media group retrieval within an aiogram bot. This method ensures all messages in an album are collected reliably and supports album operations like forwarding and copying. ```python from aiogram import Dispatcher, Bot, Router, F from aiogram.types import Message from aiogram_album import AlbumMessage from aiogram_album.pyrogram_album.middleware import PyrogramAlbumMiddleware BOT_TOKEN = "your_bot_token_here" API_ID = 12345678 # Get from https://my.telegram.org API_HASH = "your_api_hash_here" bot = Bot(token=BOT_TOKEN) dp = Dispatcher() router = Router() # Method 1: Initialize from credentials async def setup_middleware(): await PyrogramAlbumMiddleware.from_app_data( bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH, router=router, maxsize=100, # Cache size ttl=10 # Cache TTL in seconds ) @router.message(F.media_group_id) async def pyrogram_album_handler(message: AlbumMessage): """Handles albums fetched via Pyrogram""" await message.reply( f"Complete album: {len(message)} items\n" f"All messages guaranteed collected" ) # Album operations return AlbumMessage instances forwarded_album = await message.forward(chat_id=123456789) copied_album = await message.copy_to(chat_id=987654321) deleted_count = await message.delete() await message.answer(f"Deleted {deleted_count} messages") ``` -------------------------------- ### Handle Media Albums with aiogram Base Handler Source: https://github.com/rootshinobi/aiogram_album/blob/main/README.md This snippet demonstrates how to create a base handler for processing media albums in aiogram. It utilizes the AlbumMessage type to access album details like size and content types. No external dependencies beyond aiogram_album are required. ```python from aiogram_album import AlbumMessage @router.message(F.media_group_id) async def media_handler(message: AlbumMessage): await message.reply( f"album\n" f"size: {len(message)}\n" f"content types: {[m.content_type.value for m in message]}" ) ``` -------------------------------- ### Use TTLCacheAlbumMiddleware for Timed Album Caching Source: https://context7.com/rootshinobi/aiogram_album/llms.txt Demonstrates TTLCacheAlbumMiddleware for collecting albums with automatic TTL-based cache cleanup. It requires aiogram and aiogram_album. The middleware collects media groups, processes them after a delay, and cleans up old entries after a specified TTL. ```python from aiogram import Dispatcher, Bot, Router, F from aiogram.types import Message from aiogram_album import AlbumMessage from aiogram_album.ttl_cache_middleware import TTLCacheAlbumMiddleware BOT_TOKEN = "your_bot_token_here" bot = Bot(token=BOT_TOKEN) dp = Dispatcher() router = Router() # Setup TTL cache middleware TTLCacheAlbumMiddleware( latency=0.2, # Collection delay in seconds maxsize=10000, # Maximum cached album groups ttl=10, # Automatic cleanup after 10 seconds router=router ) @router.message(F.media_group_id) async def ttl_album_handler(message: AlbumMessage): """Process albums with automatic cache expiration""" media_types = [msg.content_type for msg in message] await message.reply( f"Album received:\n" f"• Size: {len(message)}\n" f"• Types: {', '.join(media_types)}\n" f"• IDs: {message.message_ids}" ) # Convert to InputMedia for sending input_media = message.as_input_media( caption=["Photo 1", "Photo 2", "Video 1"], parse_mode="HTML" ) # Send modified album await bot.send_media_group( chat_id=message.chat.id, media=input_media ) dp.include_router(router) ``` -------------------------------- ### Implement LockAlbumMiddleware for Thread-Safe Album Collection in aiogram Source: https://context7.com/rootshinobi/aiogram_album/llms.txt Shows how to set up and use LockAlbumMiddleware for thread-safe media group collection in aiogram bots. This middleware uses async locks and a TTL cache, allowing for atomic operations like forwarding, copying, and deleting entire albums. ```python from aiogram import Dispatcher, Bot, Router, F from aiogram.types import Message from aiogram_album import AlbumMessage from aiogram_album.lock_middleware import LockAlbumMiddleware # Initialize bot and dispatcher BOT_TOKEN = "your_bot_token_here" bot = Bot(token=BOT_TOKEN) dp = Dispatcher() router = Router() # Setup middleware with custom parameters LockAlbumMiddleware( latency=0.2, # Wait 200ms to collect album messages maxsize=1000, # Cache up to 1000 album groups ttl=10, # Cache entries expire after 10 seconds router=router # Auto-register on router ) @router.message(F.media_group_id) async def album_handler(message: AlbumMessage): """Processes complete album after collection""" await message.reply(f"Album with {len(message)} items received!") # Copy album to another chat await message.copy_to(chat_id=123456789) # Forward album preserving original sender await message.forward(chat_id=987654321) # Delete original album await message.delete() dp.include_router(router) # Run bot if __name__ == "__main__": import asyncio asyncio.run(dp.start_polling(bot)) ``` -------------------------------- ### AlbumMessage API Demo Source: https://context7.com/rootshinobi/aiogram_album/llms.txt Demonstrates comprehensive usage of the AlbumMessage API for manipulating albums. It covers accessing properties like album size, message IDs, content type, and individual messages. It also shows iteration, conversion to InputMedia for editing, handling multiple captions and caption entities, forwarding, copying, deleting, replying, and answering album messages. ```python from aiogram import Router, F from aiogram.types import Message, MessageEntity from aiogram_album import AlbumMessage router = Router() @router.message(F.media_group_id) async def album_api_demo(message: AlbumMessage): """Comprehensive AlbumMessage API usage""" # Properties album_size = len(message) message_ids = message.message_ids # List[int] content_type = message.content_type # Returns "media_group" individual_messages = message.messages # List[Message] # Iteration for msg in message: print(f"Message {msg.message_id}: {msg.content_type}") # Convert to InputMedia for editing input_media_list = message.as_input_media( caption="New caption", # Single caption for first item parse_mode="Markdown" ) # Multiple captions input_media_custom = message.as_input_media( caption=["Caption 1", "Caption 2", "Caption 3"], parse_mode="HTML", caption_entities=[ [MessageEntity(type="bold", offset=0, length=7)], [], [] ] ) # Forwarding (preserves sender info) forwarded_messages = await message.forward( chat_id=-1001234567890, # Channel/supergroup message_thread_id=15, disable_notification=True, protect_content=True ) # Copying (removes sender info) copied_messages = await message.copy_to( chat_id="@channel_username", remove_caption=True, protect_content=False ) # Deletion deleted = await message.delete() # Returns True on success # Reply to album await message.reply("Album processed successfully!") # Send new message to same chat await message.answer(f"Processed {album_size} media items") ``` -------------------------------- ### Use WithoutCountCheckAlbumMiddleware for Simple Album Collection Source: https://context7.com/rootshinobi/aiogram_album/llms.txt This snippet illustrates the WithoutCountCheckAlbumMiddleware, a simplified version without count validation. It requires aiogram and aiogram_album. The middleware collects media groups based solely on latency, offering faster processing for non-critical validation scenarios. ```python from aiogram import Dispatcher, Bot, Router, F from aiogram.types import Message from aiogram_album import AlbumMessage from aiogram_album.no_check_count_middleware import WithoutCountCheckAlbumMiddleware BOT_TOKEN = "your_bot_token_here" bot = Bot(token=BOT_TOKEN) dp = Dispatcher() router = Router() # Simple latency-based collection WithoutCountCheckAlbumMiddleware( latency=0.1, # Wait duration before processing router=router ) @router.message(F.media_group_id) async def simple_album_handler(message: AlbumMessage): """Fast album processing without validation""" await message.reply(f"Quick album handler: {len(message)} items") # Bulk operations copied_ids = await message.copy_to( chat_id=123456789, message_thread_id=42, # Topic ID for forum groups disable_notification=True, protect_content=True, remove_caption=False ) forwarded_ids = await message.forward( chat_id=987654321, disable_notification=False, protect_content=False ) await message.answer( f"Copied: {len(copied_ids)} messages\n" f"Forwarded: {len(forwarded_ids)} messages" ) dp.include_router(router) ``` -------------------------------- ### Handle Media Groups with AlbumMessage in aiogram Source: https://context7.com/rootshinobi/aiogram_album/llms.txt Demonstrates basic usage of AlbumMessage for processing unified media groups in aiogram. It shows how to access album properties like item count, content types, media group ID, and individual message details. ```python from aiogram import Router, F from aiogram.types import Message from aiogram_album import AlbumMessage router = Router() @router.message(F.media_group_id) async def media_handler(message: AlbumMessage): """Handle album messages with unified interface""" await message.reply( f"Received album with {len(message)} items\n" f"Content types: {[m.content_type for m in message]}\n" f"Media group ID: {message.media_group_id}\n" f"Message IDs: {message.message_ids}" ) # Iterate through individual messages in album for idx, msg in enumerate(message, 1): if msg.caption: await message.answer(f"Item {idx} caption: {msg.caption}") # Access first message properties first_message = message.messages[0] await message.answer(f"First message from: {first_message.from_user.full_name}") ``` -------------------------------- ### Safe Telegram Album Handling with Error Management (Python) Source: https://context7.com/rootshinobi/aiogram_album/llms.txt This Python handler processes Telegram media albums, ensuring safety by checking for empty albums, handling potential errors during media iteration (e.g., accessing file IDs or durations), and managing errors during album forwarding and deletion. It uses aiogram's `F.media_group_id` and `AlbumMessage` for album detection and processing, with specific error catching for `AttributeError` and `TelegramAPIError`. ```python from aiogram import Router, F from aiogram.types import Message from aiogram.exceptions import TelegramAPIError from aiogram_album import AlbumMessage from aiogram_album.lock_middleware import LockAlbumMiddleware router = Router() LockAlbumMiddleware(router=router) @router.message(F.media_group_id) async def safe_album_handler(message: AlbumMessage): """Album handler with comprehensive error handling""" # Check album is not empty if len(message) == 0: await message.answer("Empty album received") return # Safe iteration with error handling try: for idx, msg in enumerate(message): content_type = msg.content_type if content_type == "photo": file_id = msg.photo[-1].file_id file_size = msg.photo[-1].file_size print(f"Photo {idx}: {file_size} bytes") elif content_type == "video": file_id = msg.video.file_id duration = msg.video.duration print(f"Video {idx}: {duration}s") elif content_type == "document": file_id = msg.document.file_id file_name = msg.document.file_name print(f"Document {idx}: {file_name}") except AttributeError as e: await message.reply(f"Error accessing media: {e}") return # Safe forwarding with error handling try: await message.forward(chat_id=123456789) await message.reply("Album forwarded successfully") except TelegramAPIError as e: await message.reply(f"Failed to forward: {e}") # Safe deletion with confirmation try: if await message.delete(): print(f"Deleted album {message.media_group_id}") except TelegramAPIError as e: print(f"Deletion failed: {e}") @router.message() async def handle_non_album(message: Message): """Handles messages without media_group_id""" if message.photo: await message.reply("Single photo (not an album)") elif message.text: await message.reply(f"Text message: {message.text}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.