Вот мой код:
👉
import datetime
import os
from dotenv import load_dotenv
import asyncio
import logging
import re
from contextlib import suppress
import aiohttp
from telethon import TelegramClient, events
from telethon.errors import (MediaCaptionTooLongError, FloodWaitError,
                            SlowModeWaitError, MediaEmptyError,
                            MediaInvalidError)
from telethon.tl.types import MessageMediaPhoto, MessageMediaDocument

# Load environment variables from .env file
load_dotenv()

API_ID = os.getenv("API_ID")
API_HASH = os.getenv("API_HASH")
BOT_TOKEN = os.getenv("BOT_TOKEN")
CHANNEL_ID = int(os.getenv("CHANNEL_ID"))
ALLOWED_USER_ID = int(os.getenv("ALLOWED_USER_ID"))
MAX_CAPTION_LENGTH = 1024

with TelegramClient('bot', API_ID, API_HASH) as client:
    client.start(bot_token=BOT_TOKEN)
    
logging.basicConfig(filename="bot.log", level=logging.INFO)

def clean_text(text):
    return re.sub(r'@\w+|#\w+', '', text, flags=re.IGNORECASE)

async def send_media_with_caption(event, media_list, caption):
    try:
        # Проверка типа медиафайла
        for media in media_list:
            if not isinstance(media, (MessageMediaPhoto, MessageMediaDocument)):
                raise ValueError("Invalid media type")

        # Проверка длины подписи
        if caption and len(caption) > MAX_CAPTION_LENGTH:
            await client.send_message(CHANNEL_ID, caption)
            caption = None

        # Отправка медиафайлов как альбом
        if len(media_list) > 1:
            await client.send_file(CHANNEL_ID, media_list, caption=caption)
        else:
            await client.send_file(CHANNEL_ID, media_list[0], caption=caption)

    except (MediaCaptionTooLongError, FloodWaitError, SlowModeWaitError,
            MediaEmptyError, MediaInvalidError, ValueError) as e:
        # Обработка исключений
        await client.send_message(event.chat_id, f"Ошибка: {str(e)}")

    else:
        logging.info("Media files sent successfully.")

    finally:
        # Подавление исключений при отправке сообщения об ошибке
        with suppress(Exception):
            await event.delete()

grouped_messages = {}
grouped_messages_timeout = 5  # 30 seconds timeout for grouped messages
grouped_messages_timeouts = {}  # Словарь для хранения таймаутов групп

@client.on(events.NewMessage)
async def handle_message(event):
    if event.sender_id != ALLOWED_USER_ID:
        await event.reply("Извините, вы не имеете доступа к использованию этого бота.")
        return

    # Check if the message is part of a group
    if event.grouped_id:
        # Add the message to the cache
        if event.grouped_id not in grouped_messages:
            grouped_messages[event.grouped_id] = []
        grouped_messages[event.grouped_id].append((event.media, clean_text(event.text) if event.text else None))

        # Сброс таймаута для группы
        if event.grouped_id in grouped_messages_timeouts:
            grouped_messages_timeouts[event.grouped_id].cancel()
        grouped_messages_timeouts[event.grouped_id] = asyncio.create_task(process_grouped_messages(event, event.grouped_id, grouped_messages_timeout))
    else:
        # Process individual messages
        if event.media:
            await send_media_with_caption(event, [event.media], clean_text(event.text) if event.text else None)
        elif event.text:
            cleaned_text = clean_text(event.text)
            # ...

async def process_grouped_messages(event, group_id, timeout):
    await asyncio.sleep(timeout)
    if group_id in grouped_messages:
        messages = grouped_messages.pop(group_id)
        media_list = [media for media, _ in messages]
        caption = messages[0][1]  # Используем подпись первого сообщения
        await send_media_with_caption(event, media_list, caption)
    else:
        print(f"Group {group_id} timed out or was cancelled")

# Additional logic to handle cache cleanup
async def cleanup_cache():
    while True:
        await asyncio.sleep(60)  # run every 1 minute
        for group_id, messages in list(grouped_messages.items()):
            if len(messages) == 0 or messages[-1][0].date < datetime.datetime.now() - datetime.timedelta(minutes=30):
                print(f"Cleaning up group {group_id}")
                grouped_messages.pop(group_id)

# Create an event loop and run the cleanup task
loop = asyncio.get_event_loop()
loop.create_task(cleanup_cache())  # run the cleanup task in the background

async def send_url(session, url, event):
    try:
        await client.send_message(CHANNEL_ID, url)
    except (FloodWaitError, SlowModeWaitError) as e:
        await client.send_message(event.chat_id, f"Ошибка: {str(e)}")  # Использование event

with client:
    client.run_until_disconnected()
👈
🔓Твои предложения и рекомендации по улучшению кода 🙏