Skip to content

Instantly share code, notes, and snippets.

@DavideGalilei
Last active December 12, 2024 01:13
Show Gist options
  • Save DavideGalilei/67f96318ee20548bc1e095e1437e93b6 to your computer and use it in GitHub Desktop.
Save DavideGalilei/67f96318ee20548bc1e095e1437e93b6 to your computer and use it in GitHub Desktop.
Album / Media Group handler for Pyrogram Telegram bot
import asyncio
import traceback
from dataclasses import dataclass
from collections import defaultdict
from typing import Coroutine, TypeVar
from pyrogram import Client, filters
from pyrogram.types import Message
app = Client(
"bot",
api_id=0,
api_hash="",
bot_token="",
)
_tasks = set()
T = TypeVar("T")
def background(coro: Coroutine[None, None, T]) -> asyncio.Task[T]:
loop = asyncio.get_event_loop()
task = loop.create_task(coro)
_tasks.add(task)
task.add_done_callback(_tasks.remove)
return task
@dataclass
class Album:
media_group_id: str
messages: list[Message]
# chat_id: group_id: album
_albums: defaultdict[int, dict[str, Album]] = defaultdict(dict)
@app.on_message(filters.media_group)
async def on_media_group(client: Client, message: Message):
try:
chat_id = message.chat.id
media_group_id = message.media_group_id
if media_group_id is None:
return
if media_group_id not in _albums[chat_id]:
album = Album(messages=[message], media_group_id=media_group_id)
_albums[chat_id][media_group_id] = album
async def task():
await asyncio.sleep(1)
_albums[chat_id].pop(media_group_id, None)
try:
album.messages.sort(key=lambda m: m.id)
await on_album(client, album)
except Exception:
traceback.print_exc()
background(task())
else:
album = _albums[chat_id][media_group_id]
album.messages.append(message)
finally:
message.continue_propagation()
async def on_album(client: Client, album: Album):
print(album.messages)
print(f"Album with {len(album.messages)} messages")
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment