Team Ai
Apppublic

azils3/bash

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
utilities.py822 linesDownload Raw Back to plugins
1# Ultroid - UserBot2# Copyright (C) 2021-2025 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7"""8✘ Commands Available -9 10• `{i}kickme` : Leaves the group.11 12• `{i}date` : Show Calender.13 14• `{i}listreserved`15    List all usernames (channels/groups) you own.16 17• `{i}stats` : See your profile stats.18 19• `{i}paste` - `Include long text / Reply to text file.`20 21• `{i}info <username/userid/chatid>`22    Reply to someone's msg.23 24• `{i}invite <username/userid>`25    Add user to the chat.26 27• `{i}rmbg <reply to pic>`28    Remove background from that picture.29 30• `{i}telegraph <reply to media/text>`31    Upload media/text to telegraph.32 33• `{i}json <reply to msg>`34    Get the json encoding of the message.35 36• `{i}suggest <reply to message> or <poll title>`37    Create a Yes/No poll for the replied suggestion.38 39• `{i}ipinfo <ipAddress>` : Get info about that IP address.40 41• `{i}cpy <reply to message>`42   Copy the replied message, with formatting. Expires in 24hrs.43• `{i}pst`44   Paste the copied message, with formatting.45 46• `{i}thumb <reply file>` : Download the thumbnail of the replied file.47 48• `{i}getmsg <message link>`49  Get messages from chats with forward/copy restrictions.50"""51 52import asyncio53import calendar54import html55import io56import os57import pathlib58import time59from datetime import datetime as dt60 61try:62    from PIL import Image63except ImportError:64    Image = None65 66from pyUltroid._misc._assistant import asst_cmd67from pyUltroid.dB.gban_mute_db import is_gbanned68from pyUltroid.fns.tools import get_chat_and_msgid69 70from . import upload_file as uf71 72from telethon.errors.rpcerrorlist import ChatForwardsRestrictedError, UserBotError73from telethon.errors import MessageTooLongError74from telethon.events import NewMessage75from telethon.tl.custom import Dialog76from telethon.tl.functions.channels import (77    GetAdminedPublicChannelsRequest,78    InviteToChannelRequest,79    LeaveChannelRequest,80)81from telethon.tl.functions.contacts import GetBlockedRequest82from telethon.tl.functions.messages import AddChatUserRequest, GetAllStickersRequest83from telethon.tl.functions.users import GetFullUserRequest84from telethon.tl.types import (85    Channel,86    Chat,87    InputMediaPoll,88    Poll,89    PollAnswer,90    TLObject,91    User,92    UserStatusOffline,93    UserStatusOnline,94    MessageMediaPhoto,95    MessageMediaDocument,96    DocumentAttributeVideo,97)98from telethon.utils import get_peer_id99 100from pyUltroid.fns.info import get_chat_info101 102from . import (103    HNDLR,104    LOGS,105    Image,106    ReTrieveFile,107    Telegraph,108    asst,109    async_searcher,110    bash,111    check_filename,112    eod,113    eor,114    get_paste,115    get_string,116    inline_mention,117    json_parser,118    mediainfo,119    udB,120    ultroid_cmd,121)122 123# =================================================================#124 125TMP_DOWNLOAD_DIRECTORY = "resources/downloads/"126 127CAPTION_LIMIT = 1024  # Telegram's caption character limit for non-premium128 129_copied_msg = {}130 131 132@ultroid_cmd(pattern="kickme$", fullsudo=True)133async def leave(ult):134    await ult.eor(f"`{ult.client.me.first_name} has left this group, bye!!.`")135    await ult.client(LeaveChannelRequest(ult.chat_id))136 137 138@ultroid_cmd(139    pattern="date$",140)141async def date(event):142    m = dt.now().month143    y = dt.now().year144    d = dt.now().strftime("Date - %B %d, %Y\nTime- %H:%M:%S")145    k = calendar.month(y, m)146    await event.eor(f"`{k}\n\n{d}`")147 148 149@ultroid_cmd(150    pattern="listreserved$",151)152async def _(event):153    result = await event.client(GetAdminedPublicChannelsRequest())154    if not result.chats:155        return await event.eor("`No username Reserved`")156    output_str = "".join(157        f"- {channel_obj.title} @{channel_obj.username} \n"158        for channel_obj in result.chats159    )160    await event.eor(output_str)161 162 163@ultroid_cmd(164    pattern="stats$",165)166async def stats(167    event: NewMessage.Event,168):169    ok = await event.eor("`Collecting stats...`")170    start_time = time.time()171    private_chats = 0172    bots = 0173    groups = 0174    broadcast_channels = 0175    admin_in_groups = 0176    creator_in_groups = 0177    admin_in_broadcast_channels = 0178    creator_in_channels = 0179    unread_mentions = 0180    unread = 0181    dialog: Dialog182    async for dialog in event.client.iter_dialogs():183        entity = dialog.entity184        if isinstance(entity, Channel) and entity.broadcast:185            broadcast_channels += 1186            if entity.creator or entity.admin_rights:187                admin_in_broadcast_channels += 1188            if entity.creator:189                creator_in_channels += 1190 191        elif (isinstance(entity, Channel) and entity.megagroup) or isinstance(192            entity, Chat193        ):194            groups += 1195            if entity.creator or entity.admin_rights:196                admin_in_groups += 1197            if entity.creator:198                creator_in_groups += 1199 200        elif isinstance(entity, User):201            private_chats += 1202            if entity.bot:203                bots += 1204 205        unread_mentions += dialog.unread_mentions_count206        unread += dialog.unread_count207    stop_time = time.time() - start_time208    try:209        ct = (await event.client(GetBlockedRequest(1, 0))).count210    except AttributeError:211        ct = 0212    try:213        sp = await event.client(GetAllStickersRequest(0))214        sp_count = len(sp.sets)215    except BaseException:216        sp_count = 0217    full_name = inline_mention(event.client.me)218    response = f"🔸 **Stats for {full_name}** \n\n"219    response += f"**Private Chats:** {private_chats} \n"220    response += f"**  •• **`Users: {private_chats - bots}` \n"221    response += f"**  •• **`Bots: {bots}` \n"222    response += f"**Groups:** {groups} \n"223    response += f"**Channels:** {broadcast_channels} \n"224    response += f"**Admin in Groups:** {admin_in_groups} \n"225    response += f"**  •• **`Creator: {creator_in_groups}` \n"226    response += f"**  •• **`Admin Rights: {admin_in_groups - creator_in_groups}` \n"227    response += f"**Admin in Channels:** {admin_in_broadcast_channels} \n"228    response += f"**  •• **`Creator: {creator_in_channels}` \n"229    response += f"**  •• **`Admin Rights: {admin_in_broadcast_channels - creator_in_channels}` \n"230    response += f"**Unread:** {unread} \n"231    response += f"**Unread Mentions:** {unread_mentions} \n"232    response += f"**Blocked Users:** {ct}\n"233    response += f"**Total Stickers Pack Installed :** `{sp_count}`\n\n"234    response += f"**__It Took:__** {stop_time:.02f}s \n"235    await ok.edit(response)236 237 238@ultroid_cmd(pattern="paste( (.*)|$)", manager=True, allow_all=True)239async def _(event):240    try:241        input_str = event.text.split(maxsplit=1)[1]242    except IndexError:243        input_str = None244    xx = await event.eor("` 《 Pasting... 》 `")245    downloaded_file_name = None246    if input_str:247        message = input_str248    elif event.reply_to_msg_id:249        previous_message = await event.get_reply_message()250        if previous_message.media:251            downloaded_file_name = await event.client.download_media(252                previous_message,253                "./resources/downloads",254            )255            with open(downloaded_file_name, "r") as fd:256                message = fd.read()257            os.remove(downloaded_file_name)258        else:259            message = previous_message.message260    else:261        message = None262    if not message:263        return await xx.eor(264            "`Reply to a Message/Document or Give me Some Text !`", time=5265        )266    done, data = await get_paste(message)267    if not done and data.get("error"):268        return await xx.eor(data["error"])269    reply_text = (270        f"• **Pasted to SpaceBin :** [Space]({data['link']})\n• **Raw Url :** : [Raw]({data['raw']})"271    )272    try:273        if event.client._bot:274            return await xx.eor(reply_text)275        ok = await event.client.inline_query(asst.me.username, f"pasta-{data['link']}")276        await ok[0].click(event.chat_id, reply_to=event.reply_to_msg_id, hide_via=True)277        await xx.delete()278    except BaseException as e:279        LOGS.exception(e)280        await xx.edit(reply_text)281 282 283@ultroid_cmd(284    pattern="info( (.*)|$)",285    manager=True,286)287async def _(event):288    if match := event.pattern_match.group(1).strip():289        try:290            user = await event.client.parse_id(match)291        except Exception as er:292            return await event.eor(str(er))293    elif event.is_reply:294        rpl = await event.get_reply_message()295        user = rpl.sender_id296    else:297        user = event.chat_id298    xx = await event.eor(get_string("com_1"))299    try:300        _ = await event.client.get_entity(user)301    except Exception as er:302        return await xx.edit(f"**ERROR :** {er}")303    if not isinstance(_, User):304        try:305            peer = get_peer_id(_)306            photo, capt = await get_chat_info(_, event)307            if is_gbanned(peer):308                capt += "\n•<b> Is Gbanned:</b> <code>True</code>"309            if not photo:310                return await xx.eor(capt, parse_mode="html")311            await event.client.send_message(312                event.chat_id, capt[:1024], file=photo, parse_mode="html"313            )314            await xx.delete()315        except Exception as er:316            await event.eor("**ERROR ON CHATINFO**\n" + str(er))317        return318    try:319        full_user = (await event.client(GetFullUserRequest(user))).full_user320    except Exception as er:321        return await xx.edit(f"ERROR : {er}")322    user = _323    user_photos = (324        await event.client.get_profile_photos(user.id, limit=0)325    ).total or "NaN"326    user_id = user.id327    first_name = html.escape(user.first_name)328    if first_name is not None:329        first_name = first_name.replace("\u2060", "")330    last_name = user.last_name331    last_name = (332        last_name.replace("\u2060", "") if last_name else ("Last Name not found")333    )334    user_bio = full_user.about335    if user_bio is not None:336        user_bio = html.escape(full_user.about)337    common_chats = full_user.common_chats_count338    if user.photo:339        dc_id = user.photo.dc_id340    else:341        dc_id = "Need a Profile Picture to check this"342    caption = """<b>Exᴛʀᴀᴄᴛᴇᴅ Dᴀᴛᴀ Fʀᴏᴍ Tᴇʟᴇɢʀᴀᴍ's Dᴀᴛᴀʙᴀsᴇ<b>343<b>••Tᴇʟᴇɢʀᴀᴍ ID</b>: <code>{}</code>344<b>••Pᴇʀᴍᴀɴᴇɴᴛ Lɪɴᴋ</b>: <a href='tg://user?id={}'>Click Here</a>345<b>••Fɪʀsᴛ Nᴀᴍᴇ</b>: <code>{}</code>346<b>••Sᴇᴄᴏɴᴅ Nᴀᴍᴇ</b>: <code>{}</code>347<b>••Bɪᴏ</b>: <code>{}</code>348<b>••Dᴄ ID</b>: <code>{}</code>349<b>••Nᴏ. Oғ PғPs</b> : <code>{}</code>350<b>••Is Rᴇsᴛʀɪᴄᴛᴇᴅ</b>: <code>{}</code>351<b>••Vᴇʀɪғɪᴇᴅ</b>: <code>{}</code>352<b>••Is Pʀᴇᴍɪᴜᴍ</b>: <code>{}</code>353<b>••Is A Bᴏᴛ</b>: <code>{}</code>354<b>••Gʀᴏᴜᴘs Iɴ Cᴏᴍᴍᴏɴ</b>: <code>{}</code>355""".format(356        user_id,357        user_id,358        first_name,359        last_name,360        user_bio,361        dc_id,362        user_photos,363        user.restricted,364        user.verified,365        user.premium,366        user.bot,367        common_chats,368    )369    if chk := is_gbanned(user_id):370        caption += f"""<b>••Gʟᴏʙᴀʟʟʏ Bᴀɴɴᴇᴅ</b>: <code>True</code>371<b>••Rᴇᴀsᴏɴ</b>: <code>{chk}</code>"""372    await event.client.send_message(373        event.chat_id,374        caption,375        reply_to=event.reply_to_msg_id,376        parse_mode="HTML",377        file=full_user.profile_photo,378        force_document=False,379        silent=True,380    )381    await xx.delete()382 383 384@ultroid_cmd(385    pattern="invite( (.*)|$)",386    groups_only=True,387)388async def _(ult):389    xx = await ult.eor(get_string("com_1"))390    to_add_users = ult.pattern_match.group(1).strip()391    if not ult.is_channel and ult.is_group:392        for user_id in to_add_users.split(" "):393            try:394                await ult.client(395                    AddChatUserRequest(396                        chat_id=ult.chat_id,397                        user_id=await ult.client.parse_id(user_id),398                        fwd_limit=1000000,399                    ),400                )401                await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`")402            except Exception as e:403                await xx.edit(str(e))404    else:405        for user_id in to_add_users.split(" "):406            try:407                await ult.client(408                    InviteToChannelRequest(409                        channel=ult.chat_id,410                        users=[await ult.client.parse_id(user_id)],411                    ),412                )413                await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`")414            except UserBotError:415                await xx.edit(416                    f"Bots can only be added as Admins in Channel.\nBetter Use `{HNDLR}promote {user_id}`"417                )418            except Exception as e:419                await xx.edit(str(e))420 421 422@ultroid_cmd(423    pattern="rmbg($| (.*))",424)425async def abs_rmbg(event):426    RMBG_API = udB.get_key("RMBG_API")427    if not RMBG_API:428        return await event.eor(429            "Get your API key from [here](https://www.remove.bg/) for this plugin to work.",430        )431    match = event.pattern_match.group(1).strip()432    reply = await event.get_reply_message()433    if match and os.path.exists(match):434        dl = match435    elif reply and reply.media:436        if reply.document and reply.document.thumbs:437            dl = await reply.download_media(thumb=-1)438        else:439            dl = await reply.download_media()440    else:441        return await eod(442            event, f"Use `{HNDLR}rmbg` as reply to a pic to remove its background."443        )444    if not (dl and dl.endswith(("webp", "jpg", "png", "jpeg"))):445        os.remove(dl)446        return await event.eor(get_string("com_4"))447    if dl.endswith("webp"):448        file = f"{dl}.png"449        Image.open(dl).save(file)450        os.remove(dl)451        dl = file452    xx = await event.eor("`Sending to remove.bg`")453    dn, out = await ReTrieveFile(dl)454    os.remove(dl)455    if not dn:456        dr = out["errors"][0]457        de = dr.get("detail", "")458        return await xx.edit(459            f"**ERROR ~** `{dr['title']}`,\n`{de}`",460        )461    zz = Image.open(out)462    if zz.mode != "RGB":463        zz.convert("RGB")464    wbn = check_filename("ult-rmbg.webp")465    zz.save(wbn, "webp")466    await event.client.send_file(467        event.chat_id,468        out,469        force_document=True,470        reply_to=reply,471    )472    await event.client.send_file(event.chat_id, wbn, reply_to=reply)473    os.remove(out)474    os.remove(wbn)475    await xx.delete()476 477 478@ultroid_cmd(479    pattern="telegraph( (.*)|$)",480)481async def telegraphcmd(event):482    xx = await event.eor(get_string("com_1"))483    match = event.pattern_match.group(1).strip() or "Ultroid"484    reply = await event.get_reply_message()485    if not reply:486        return await xx.eor("`Reply to Message.`")487    if not reply.media and reply.message:488        content = reply.message489    else:490        getit = await reply.download_media()491        dar = mediainfo(reply.media)492        if dar == "sticker":493            file = f"{getit}.png"494            Image.open(getit).save(file)495            os.remove(getit)496            getit = file497        elif dar.endswith("animated"):498            file = f"{getit}.gif"499            await bash(f"lottie_convert.py '{getit}' {file}")500            os.remove(getit)501            getit = file502        if "document" not in dar:503            try:504                nn = uf(getit)505                amsg = f"Uploaded to [Telegraph]({nn}) !"506            except Exception as e:507                amsg = f"Error : {e}"508            os.remove(getit)509            return await xx.eor(amsg)510        content = pathlib.Path(getit).read_text()511        os.remove(getit)512    makeit = Telegraph.create_page(title=match, content=[content])513    await xx.eor(514        f"Pasted to Telegraph : [Telegraph]({makeit['url']})", link_preview=False515    )516 517 518@ultroid_cmd(pattern="json( (.*)|$)")519async def _(event):520    reply_to_id = None521    match = event.pattern_match.group(1).strip()522    if event.reply_to_msg_id:523        msg = await event.get_reply_message()524        reply_to_id = event.reply_to_msg_id525    else:526        msg = event527        reply_to_id = event.message.id528    if match and hasattr(msg, match.split()[0]):529        msg = getattr(msg, match.split()[0])530        try:531            if hasattr(msg, "to_json"):532                msg = msg.to_json(ensure_ascii=False, indent=1)533            elif hasattr(msg, "to_dict"):534                msg = json_parser(msg.to_dict(), indent=1)535            else:536                msg = TLObject.stringify(msg)537        except Exception:538            pass539        msg = str(msg)540    else:541        msg = json_parser(msg.to_json(), indent=1)542    if "-t" in match:543        try:544            data = json_parser(msg)545            msg = json_parser(546                {key: data[key] for key in data.keys() if data[key]}, indent=1547            )548        except Exception:549            pass550    if len(msg) > 4096:551        with io.BytesIO(str.encode(msg)) as out_file:552            out_file.name = "json-ult.txt"553            await event.client.send_file(554                event.chat_id,555                out_file,556                force_document=True,557                allow_cache=False,558                reply_to=reply_to_id,559            )560            await event.delete()561    else:562        await event.eor(f"```{msg or None}```")563 564 565@ultroid_cmd(pattern="suggest( (.*)|$)", manager=True)566async def sugg(event):567    sll = event.text.split(maxsplit=1)568    try:569        text = sll[1]570    except IndexError:571        text = None572    if not (event.is_reply or text):573        return await eod(574            event,575            "`Please reply to a message to make a suggestion poll!`",576        )577    if event.is_reply and not text:578        reply = await event.get_reply_message()579        if reply.text and len(reply.text) < 35:580            text = reply.text581        else:582            text = "Do you Agree to Replied Suggestion ?"583    reply_to = event.reply_to_msg_id if event.is_reply else event.id584    try:585        await event.client.send_file(586            event.chat_id,587            file=InputMediaPoll(588                poll=Poll(589                    id=12345,590                    question=text,591                    answers=[PollAnswer("Yes", b"1"), PollAnswer("No", b"2")],592                ),593            ),594            reply_to=reply_to,595        )596    except Exception as e:597        return await eod(event, f"`Oops, you can't send polls here!\n\n{e}`")598    await event.delete()599 600 601@ultroid_cmd(pattern="ipinfo( (.*)|$)")602async def ipinfo(event):603    ip = event.text.split()604    ipaddr = ""605    try:606        ipaddr = f"/{ip[1]}"607    except IndexError:608        ipaddr = ""609    det = await async_searcher(f"https://ipinfo.io{ipaddr}/geo", re_json=True)610    try:611        ip = det["ip"]612        city = det["city"]613        region = det["region"]614        country = det["country"]615        cord = det["loc"]616        try:617            zipc = det["postal"]618        except KeyError:619            zipc = "None"620        tz = det["timezone"]621        await eor(622            event,623            """624**IP Details Fetched.**625 626**IP:** `{}`627**City:** `{}`628**Region:** `{}`629**Country:** `{}`630**Co-ordinates:** `{}`631**Postal Code:** `{}`632**Time Zone:** `{}`633""".format(634                ip,635                city,636                region,637                country,638                cord,639                zipc,640                tz,641            ),642        )643    except BaseException:644        err = det["error"]["title"]645        msg = det["error"]["message"]646        await event.eor(f"ERROR:\n{err}\n{msg}", time=5)647 648 649@ultroid_cmd(650    pattern="cpy$",651)652async def copp(event):653    msg = await event.get_reply_message()654    if not msg:655        return await event.eor(f"Use `{HNDLR}cpy` as reply to a message!", time=5)656    _copied_msg["CLIPBOARD"] = msg657    await event.eor(f"Copied. Use `{HNDLR}pst` to paste!", time=10)658 659 660@asst_cmd(pattern="pst$")661async def pepsodent(event):662    await toothpaste(event)663 664 665@ultroid_cmd(666    pattern="pst$",667)668async def colgate(event):669    await toothpaste(event)670 671 672async def toothpaste(event):673    try:674        await event.respond(_copied_msg["CLIPBOARD"])675    except KeyError:676        return await eod(677            event,678            f"Nothing was copied! Use `{HNDLR}cpy` as reply to a message first!",679        )680    except Exception as ex:681        return await event.eor(str(ex), time=5)682    await event.delete()683 684 685@ultroid_cmd(pattern="thumb$")686async def thumb_dl(event):687    reply = await event.get_reply_message()688    if not (reply and reply.file):689        return await eod(event, get_string("th_1"), time=5)690    if not reply.file.media.thumbs:691        return await eod(event, get_string("th_2"))692    await event.eor(get_string("com_1"))693    x = await event.get_reply_message()694    m = await x.download_media(thumb=-1)695    await event.reply(file=m)696    os.remove(m)697 698 699async def get_video_duration(file_path):700    cmd = [701        "ffprobe",702        "-v",703        "error",704        "-show_entries",705        "format=duration",706        "-of",707        "default=noprint_wrappers=1:nokey=1",708        file_path,709    ]710    try:711        result = await asyncio.create_subprocess_exec(712            *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE713        )714        stdout, stderr = await result.communicate()715        duration = float(stdout.decode().strip())716        return duration717    except Exception as e:718        print("Error running ffprobe:", e)719        return None720 721async def get_thumbnail(file_path, thumbnail_path):722    try:723        await asyncio.create_subprocess_exec(724            "ffmpeg",725            "-i", file_path,726            "-ss", "00:00:04",727            "-vframes", "1",  # Extract a single frame as the thumbnail728            thumbnail_path,729            stdout=asyncio.subprocess.PIPE,730            stderr=asyncio.subprocess.PIPE,731        )732    except Exception as e:733        print(f"Error extracting thumbnail: {e}")734 735@ultroid_cmd(pattern="getmsg( ?(.*)|$)")736async def get_restricted_msg(event):737    match = event.pattern_match.group(1).strip()738    if not match:739        await event.eor("`Please provide a link!`", time=5)740        return741    742    xx = await event.eor("`Loading...`")743    chat, msg = get_chat_and_msgid(match)744    if not (chat and msg):745        return await event.eor(746            "Invalid link!\nEg: `https://t.me/TeamUltroid/3` or `https://t.me/c/1313492028/3`"747        )748    749    try:750        message = await event.client.get_messages(chat, ids=msg)751    except BaseException as er:752        return await event.eor(f"**ERROR**\n`{er}`")753    754    try:755        await event.client.send_message(event.chat_id, message)756        await xx.try_delete()757        return758    except ChatForwardsRestrictedError:759        pass760    761    if message.media:762        if isinstance(message.media, (MessageMediaPhoto, MessageMediaDocument)):763            media_path, _ = await event.client.fast_downloader(message.document, show_progress=True, event=xx, message=get_string("com_5"))764 765            caption = message.text or ""766 767            attributes = []768            if message.video:769                duration = await get_video_duration(media_path.name)770                771                width, height = 0, 0772                for attribute in message.document.attributes:773                    if isinstance(attribute, DocumentAttributeVideo):774                        width = attribute.w775                        height = attribute.h776                        break777                778                thumb_path = media_path.name + "_thumb.jpg"779                await get_thumbnail(media_path.name, thumb_path)780 781                attributes.append(782                    DocumentAttributeVideo(783                        duration=int(duration) if duration else 0,784                        w=width,785                        h=height,786                        supports_streaming=True,787                    )788                )789            await xx.edit(get_string("com_6"))790            media_path, _ = await event.client.fast_uploader(media_path.name, event=xx, show_progress=True, to_delete=True)791 792            try:793                await event.client.send_file(794                    event.chat_id,795                    media_path,796                    caption=caption,797                    force_document=False,798                    supports_streaming=True if message.video else False,799                    thumb=thumb_path if message.video else None,800                    attributes=attributes if message.video else None,801                )802            except MessageTooLongError:803                if len(caption) > CAPTION_LIMIT:804                    caption = caption[:CAPTION_LIMIT] + "..."805                await event.client.send_file(806                    event.chat_id,807                    media_path,808                    caption=caption,809                    force_document=False,  # Set to True if you want to send as a document810                    supports_streaming=True if message.video else False,811                    thumb=thumb_path if message.video else None,812                    attributes=attributes if message.video else None,813                )814 815            if message.video and os.path.exists(thumb_path):816                os.remove(thumb_path)817            await xx.try_delete()818        else:819            await event.eor("`Cannot process this type of media.`")820    else:821        await event.eor("`No media found in the message.`")822