Team Ai
Apppublic

azils3/bash

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
tools.py464 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}circle`11    Reply to a audio song or gif to get video note.12 13• `{i}ls`14    Get all the Files inside a Directory.15 16• `{i}bots`17    Shows the number of bots in the current chat with their perma-link.18 19• `{i}hl <a link> <text-optional>`20    Embeds the link with a whitespace as message.21 22• `{i}id`23    Reply a Sticker to Get Its Id24    Reply a User to Get His Id25    Without Replying You Will Get the Chat's Id26 27• `{i}sg <reply to a user><username/id>`28    Get His Name History of the replied user.29 30• `{i}tr <dest lang code> <(reply to) a message>`31    Get translated message.32 33• `{i}webshot <url>`34    Get a screenshot of the webpage.35"""36import glob37import io38import os39import secrets40from asyncio.exceptions import TimeoutError as AsyncTimeout41 42try:43    import cv244except ImportError:45    cv2 = None46 47try:48    from playwright.async_api import async_playwright49except ImportError:50    async_playwright = None51try:52    from htmlwebshot import WebShot53except ImportError:54    WebShot = None55 56from telethon.errors.rpcerrorlist import MessageTooLongError, YouBlockedUserError57from telethon.tl.types import (58    ChannelParticipantAdmin,59    ChannelParticipantsBots,60    DocumentAttributeVideo,61)62 63from pyUltroid.fns.tools import metadata, translate64 65from . import (66    HNDLR,67    LOGS,68    ULTConfig,69    async_searcher,70    bash,71    check_filename,72    con,73    download_file,74    eor,75    get_string,76)77from . import humanbytes as hb78from . import inline_mention, is_url_ok, json_parser, mediainfo, ultroid_cmd79 80 81@ultroid_cmd(pattern="tr( (.*)|$)", manager=True)82async def _(event):83    input = event.pattern_match.group(1).strip().split(maxsplit=1)84    txt = input[1] if len(input) > 1 else None85    if input:86        input = input[0]87    if txt:88        text = txt89    elif event.is_reply:90        previous_message = await event.get_reply_message()91        text = previous_message.message92    else:93        return await eor(94            event, f"`{HNDLR}tr LanguageCode` as reply to a message", time=595        )96    lan = input or "en"97    try:98        tt = translate(text, lang_tgt=lan)99        output_str = f"**TRANSLATED** to {lan}\n{tt}"100        await event.eor(output_str)101    except Exception as exc:102        LOGS.exception(exc)103        await event.eor(str(exc), time=5)104 105 106@ultroid_cmd(107    pattern="id( (.*)|$)",108    manager=True,109)110async def _(event):111    ult = event112    match = event.pattern_match.group(1).strip()113    if match:114        try:115            ids = await event.client.parse_id(match)116        except Exception as er:117            return await event.eor(str(er))118        return await event.eor(119            f"**Chat ID:**  `{event.chat_id}`\n**User ID:**  `{ids}`"120        )121    data = f"**Current Chat ID:**  `{event.chat_id}`"122    if event.reply_to_msg_id:123        event = await event.get_reply_message()124        data += f"\n**From User ID:**  `{event.sender_id}`"125    if event.media:126        bot_api_file_id = event.file.id127        data += f"\n**Bot API File ID:**  `{bot_api_file_id}`"128    data += f"\n**Msg ID:**  `{event.id}`"129    await ult.eor(data)130 131 132@ultroid_cmd(pattern="bots( (.*)|$)", groups_only=True, manager=True)133async def _(ult):134    mentions = "• **Bots in this Chat**: \n"135    if input_str := ult.pattern_match.group(1).strip():136        mentions = f"• **Bots in **{input_str}: \n"137        try:138            chat = await ult.client.parse_id(input_str)139        except Exception as e:140            return await ult.eor(str(e))141    else:142        chat = ult.chat_id143    try:144        async for x in ult.client.iter_participants(145            chat,146            filter=ChannelParticipantsBots,147        ):148            if isinstance(x.participant, ChannelParticipantAdmin):149                mentions += f"\n⚜️ {inline_mention(x)} `{x.id}`"150            else:151                mentions += f"\n• {inline_mention(x)} `{x.id}`"152    except Exception as e:153        mentions += f" {str(e)}" + "\n"154    await ult.eor(mentions)155 156 157@ultroid_cmd(158    pattern="hl( (.*)|$)",159)160async def _(ult):161    input_ = ult.pattern_match.group(1).strip()162    if not input_:163        return await ult.eor("`Input some link`", time=5)164    text = None165    if len(input_.split()) > 1:166        spli_ = input_.split()167        input_ = spli_[0]168        text = spli_[1]169    if not text:170        text = "ㅤㅤㅤㅤㅤㅤㅤ"171    await ult.eor(f"[{text}]({input_})", link_preview=False)172 173 174@ultroid_cmd(175    pattern="circle$",176)177async def _(e):178    reply = await e.get_reply_message()179    if not (reply and reply.media):180        return await e.eor("`Reply to a gif or audio file only.`")181    if "audio" in mediainfo(reply.media):182        msg = await e.eor("`Downloading...`")183        try:184            bbbb = await reply.download_media(thumb=-1)185        except TypeError:186            bbbb = ULTConfig.thumb187        im = cv2.imread(bbbb)188        dsize = (512, 512)189        output = cv2.resize(im, dsize, interpolation=cv2.INTER_AREA)190        cv2.imwrite("img.jpg", output)191        thumb = "img.jpg"192        audio, _ = await e.client.fast_downloader(reply.document)193        await msg.edit("`Creating video note...`")194        await bash(195            f'ffmpeg -i "{thumb}" -i "{audio.name}" -preset ultrafast -c:a libmp3lame -ab 64 circle.mp4 -y'196        )197        await msg.edit("`Uploading...`")198        data = await metadata("circle.mp4")199        file, _ = await e.client.fast_uploader("circle.mp4", to_delete=True)200        await e.client.send_file(201            e.chat_id,202            file,203            thumb=thumb,204            reply_to=reply,205            attributes=[206                DocumentAttributeVideo(207                    duration=min(data["duration"], 60),208                    w=512,209                    h=512,210                    round_message=True,211                )212            ],213        )214 215        await msg.delete()216        [os.remove(k) for k in [audio.name, thumb]]217    elif mediainfo(reply.media) == "gif" or mediainfo(reply.media).startswith("video"):218        msg = await e.eor("**Creating video note**")219        file = await reply.download_media("resources/downloads/")220        if file.endswith(".webm"):221            nfile = await con.ffmpeg_convert(file, "file.mp4")222            os.remove(file)223            file = nfile224        if file:225            await e.client.send_file(226                e.chat_id,227                file,228                video_note=True,229                thumb=ULTConfig.thumb,230                reply_to=reply,231            )232            os.remove(file)233        await msg.delete()234 235    else:236        await e.eor("`Reply to a gif or audio file only.`")237 238 239FilesEMOJI = {240    "py": "🐍",241    "json": "🔮",242    ("sh", "bat"): "⌨️",243    (".mkv", ".mp4", ".avi", ".gif", "webm"): "🎥",244    (".mp3", ".ogg", ".m4a", ".opus"): "🔊",245    (".jpg", ".jpeg", ".png", ".webp", ".ico"): "🖼",246    (".txt", ".text", ".log"): "📄",247    (".apk", ".xapk"): "📲",248    (".pdf", ".epub"): "📗",249    (".zip", ".rar"): "🗜",250    (".exe", ".iso"): "⚙",251}252 253 254@ultroid_cmd(255    pattern="ls( (.*)|$)",256)257async def _(e):258    files = e.pattern_match.group(1).strip()259    if not files:260        files = "*"261    elif files.endswith("/"):262        files += "*"263    elif "*" not in files:264        files += "/*"265    files = glob.glob(files)266    if not files:267        return await e.eor("`Directory Empty or Incorrect.`", time=5)268    folders = []269    allfiles = []270    for file in sorted(files):271        if os.path.isdir(file):272            folders.append(f"📂 {file}")273        else:274            for ext in FilesEMOJI.keys():275                if file.endswith(ext):276                    allfiles.append(f"{FilesEMOJI[ext]} {file}")277                    break278            else:279                if "." in str(file)[1:]:280                    allfiles.append(f"🏷 {file}")281                else:282                    allfiles.append(f"📒 {file}")283    omk = [*sorted(folders), *sorted(allfiles)]284    text = ""285    fls, fos = 0, 0286    flc, foc = 0, 0287    for i in omk:288        try:289            emoji = i.split()[0]290            name = i.split(maxsplit=1)[1]291            nam = name.split("/")[-1]292            if os.path.isdir(name):293                size = 0294                for path, dirs, files in os.walk(name):295                    for f in files:296                        fp = os.path.join(path, f)297                        size += os.path.getsize(fp)298                if hb(size):299                    text += f"{emoji} `{nam}`  `{hb(size)}" + "`\n"300                    fos += size301                else:302                    text += f"{emoji} `{nam}`" + "\n"303                foc += 1304            else:305                if hb(int(os.path.getsize(name))):306                    text += (307                        emoji308                        + f" `{nam}`"309                        + "  `"310                        + hb(int(os.path.getsize(name)))311                        + "`\n"312                    )313                    fls += int(os.path.getsize(name))314                else:315                    text += f"{emoji} `{nam}`" + "\n"316                flc += 1317        except BaseException:318            pass319    tfos, tfls, ttol = hb(fos), hb(fls), hb(fos + fls)320    if not hb(fos):321        tfos = "0 B"322    if not hb(fls):323        tfls = "0 B"324    if not hb(fos + fls):325        ttol = "0 B"326    text += f"\n\n`Folders` :  `{foc}` :   `{tfos}`\n`Files` :       `{flc}` :   `{tfls}`\n`Total` :       `{flc+foc}` :   `{ttol}`"327    try:328        if (flc + foc) > 100:329            text = text.replace("`", "")330        await e.eor(text)331    except MessageTooLongError:332        with io.BytesIO(str.encode(text)) as out_file:333            out_file.name = "output.txt"334            await e.reply(f"`{e.text}`", file=out_file, thumb=ULTConfig.thumb)335        await e.delete()336 337 338 339def sanga_seperator(sanga_list):340    string = "".join(info[info.find("\n") + 1 :] for info in sanga_list)341    string = re.sub(r"^$\n", "", string, flags=re.MULTILINE)342    name, username = string.split("Usernames**")343    name = name.split("Names")[1]344    return name, username345 346 347def mentionuser(name, userid):348    return f"[{name}](tg://user?id={userid})"349 350 351@ultroid_cmd(352    pattern="sg(|u)(?:\\s|$)([\\s\\S]*)",353    fullsudo=True,354)355async def sangmata(event):356    "To get name/username history."357    cmd = event.pattern_match.group(1)358    user = event.pattern_match.group(2)359    reply = await event.get_reply_message()360    if not user and reply:361        user = str(reply.sender_id)362    if not user:363        await event.edit(364            "`Reply to  user's text message to get name/username history or give userid/username`",365        )366        await asyncio.sleep(10)367        return await event.delete()368 369    try:370        if user.isdigit():371            userinfo = await ultroid_bot.get_entity(int(user))372        else:373            userinfo = await ultroid_bot.get_entity(user)374    except ValueError:375        userinfo = None376    if not isinstance(userinfo, types.User):377        await event.edit("`Can't fetch the user...`")378        await asyncio.sleep(10)379        return await event.delete()380 381    await event.edit("`Processing...`")382    async with event.client.conversation("@SangMata_beta_bot") as conv:383        try:384            await conv.send_message(f"{userinfo.id}")385        except YouBlockedUserError:386            await catub(unblock("SangMata_beta_bot"))387            await conv.send_message(f"{userinfo.id}")388        responses = []389        while True:390            try:391                response = await conv.get_response(timeout=2)392            except asyncio.TimeoutError:393                break394            responses.append(response.text)395        await event.client.send_read_acknowledge(conv.chat_id)396 397    if not responses:398        await event.edit("`Bot can't fetch results`")399        await asyncio.sleep(10)400        await event.delete()401    if "No records found" in responses or "No data available" in responses:402        await event.edit("`The user doesn't have any record`")403        await asyncio.sleep(10)404        await event.delete()405 406    names, usernames = sanga_seperator(responses)407    check = (usernames, "Username") if cmd == "u" else (names, "Name")408    user_name = (409        f"{userinfo.first_name} {userinfo.last_name}"410        if userinfo.last_name411        else userinfo.first_name412    )413    output = f"**➜ User Info :**  {mentionuser(user_name, userinfo.id)}\n**➜ {check[1]} History :**\n{check[0]}"414    await event.edit(output)415 416 417@ultroid_cmd(pattern="webshot( (.*)|$)")418async def webss(event):419    xx = await event.eor(get_string("com_1"))420    xurl = event.pattern_match.group(1).strip()421    if not xurl:422        return await xx.eor(get_string("wbs_1"), time=5)423    if not (await is_url_ok(xurl)):424        return await xx.eor(get_string("wbs_2"), time=5)425    path, pic = check_filename("shot.png"), None426    if async_playwright:427        try:428            async with async_playwright() as playwright:429                chrome = await playwright.chromium.launch()430                page = await chrome.new_page()431                await page.goto(xurl)432                await page.screenshot(path=path, full_page=True)433                pic = path434        except Exception as er:435            LOGS.exception(er)436            await xx.respond(f"Error with playwright:\n`{er}`")437    if WebShot and not pic:438        try:439            shot = WebShot(440                quality=88, flags=["--enable-javascript", "--no-stop-slow-scripts"]441            )442            pic = await shot.create_pic_async(url=xurl)443        except Exception as er:444            LOGS.exception(er)445    if not pic:446        pic, msg = await download_file(447            f"https://shot.screenshotapi.net/screenshot?&url={xurl}&output=image&file_type=png&wait_for_event=load",448            path,449            validate=True,450        )451        if msg:452            await xx.edit(json_parser(msg, indent=1))453            return454    if pic:455        await xx.reply(456            get_string("wbs_3").format(xurl),457            file=pic,458            link_preview=False,459            force_document=True,460        )461        os.remove(pic)462    await xx.delete()463 464