Вот мой код:
import datetime
import os
from dotenv import load_dotenv
import asyncio
import logging
import re
from contextlib import suppress
from telethon import TelegramClient, events, Button
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.id)  # Store message ID

        # Сброс таймаута для группы
        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:
        # Copy and send individual messages
        message = await client.get_messages(event.chat_id, ids=event.id)
        await client.send_message(CHANNEL_ID, message)
        await event.delete()

async def process_grouped_messages(event, group_id, timeout):
    await asyncio.sleep(timeout)
    if group_id in grouped_messages:
        message_ids = grouped_messages.pop(group_id)
        messages = await client.get_messages(event.chat_id, ids=message_ids)

        # Collect media files and caption
        media_list = []
        caption = ""
        for message in messages:
            if message.media:
                media_list.append(message.media)
            if message.text:
                caption += message.text + "\n"  # Combine captions if multiple messages have text

        # Send media files as an album
        await client.send_file(CHANNEL_ID, media_list, caption=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

with client:
    client.run_until_disconnected()
➡️Можно ли абсолютно идентично переделать этот код под официальный Telegram Bot API ❤️