id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
5,908
import calendar import html import io import os import pathlib import time from datetime import datetime as dt from pyUltroid._misc._assistant import asst_cmd from pyUltroid.dB.gban_mute_db import is_gbanned from pyUltroid.fns.tools import get_chat_and_msgid from telethon.errors.rpcerrorlist import ChatForwardsRestrictedError, UserBotError from telethon.events import NewMessage from telethon.tl.custom import Dialog from telethon.tl.functions.channels import ( GetAdminedPublicChannelsRequest, InviteToChannelRequest, LeaveChannelRequest, ) from telethon.tl.functions.contacts import GetBlockedRequest from telethon.tl.functions.messages import AddChatUserRequest, GetAllStickersRequest from telethon.tl.functions.users import GetFullUserRequest from telethon.tl.types import ( Channel, Chat, InputMediaPoll, Poll, PollAnswer, TLObject, User, ) from telethon.utils import get_peer_id from pyUltroid.fns.info import get_chat_info from . import ( HNDLR, LOGS, Image, ReTrieveFile, Telegraph, asst, async_searcher, bash, check_filename, eod, eor, get_paste, get_string, inline_mention, json_parser, mediainfo, udB, ultroid_cmd, ) async def toothpaste(event): try: await event.respond(_copied_msg["CLIPBOARD"]) except KeyError: return await eod( event, f"Nothing was copied! Use `{HNDLR}cpy` as reply to a message first!", ) except Exception as ex: return await event.eor(str(ex), time=5) await event.delete() async def colgate(event): await toothpaste(event)
null
5,909
import calendar import html import io import os import pathlib import time from datetime import datetime as dt from pyUltroid._misc._assistant import asst_cmd from pyUltroid.dB.gban_mute_db import is_gbanned from pyUltroid.fns.tools import get_chat_and_msgid from telethon.errors.rpcerrorlist import ChatForwardsRestrictedError, UserBotError from telethon.events import NewMessage from telethon.tl.custom import Dialog from telethon.tl.functions.channels import ( GetAdminedPublicChannelsRequest, InviteToChannelRequest, LeaveChannelRequest, ) from telethon.tl.functions.contacts import GetBlockedRequest from telethon.tl.functions.messages import AddChatUserRequest, GetAllStickersRequest from telethon.tl.functions.users import GetFullUserRequest from telethon.tl.types import ( Channel, Chat, InputMediaPoll, Poll, PollAnswer, TLObject, User, ) from telethon.utils import get_peer_id from pyUltroid.fns.info import get_chat_info from . import ( HNDLR, LOGS, Image, ReTrieveFile, Telegraph, asst, async_searcher, bash, check_filename, eod, eor, get_paste, get_string, inline_mention, json_parser, mediainfo, udB, ultroid_cmd, ) async def thumb_dl(event): reply = await event.get_reply_message() if not (reply and reply.file): return await eod(event, get_string("th_1"), time=5) if not reply.file.media.thumbs: return await eod(event, get_string("th_2")) await event.eor(get_string("com_1")) x = await event.get_reply_message() m = await x.download_media(thumb=-1) await event.reply(file=m) os.remove(m)
null
5,910
import calendar import html import io import os import pathlib import time from datetime import datetime as dt from pyUltroid._misc._assistant import asst_cmd from pyUltroid.dB.gban_mute_db import is_gbanned from pyUltroid.fns.tools import get_chat_and_msgid from telethon.errors.rpcerrorlist import ChatForwardsRestrictedError, UserBotError from telethon.events import NewMessage from telethon.tl.custom import Dialog from telethon.tl.functions.channels import ( GetAdminedPublicChannelsRequest, InviteToChannelRequest, LeaveChannelRequest, ) from telethon.tl.functions.contacts import GetBlockedRequest from telethon.tl.functions.messages import AddChatUserRequest, GetAllStickersRequest from telethon.tl.functions.users import GetFullUserRequest from telethon.tl.types import ( Channel, Chat, InputMediaPoll, Poll, PollAnswer, TLObject, User, ) from telethon.utils import get_peer_id from pyUltroid.fns.info import get_chat_info from . import ( HNDLR, LOGS, Image, ReTrieveFile, Telegraph, asst, async_searcher, bash, check_filename, eod, eor, get_paste, get_string, inline_mention, json_parser, mediainfo, udB, ultroid_cmd, ) async def _(event): result = await event.client(GetAdminedPublicChannelsRequest()) if not result.chats: return await event.eor("`No username Reserved`") output_str = "".join( f"- {channel_obj.title} @{channel_obj.username} \n" for channel_obj in result.chats ) await event.eor(output_str) pattern="stats$", async def _(event): try: input_str = event.text.split(maxsplit=1)[1] except IndexError: input_str = None xx = await event.eor("` 《 Pasting... 》 `") downloaded_file_name = None if input_str: message = input_str elif event.reply_to_msg_id: previous_message = await event.get_reply_message() if previous_message.media: downloaded_file_name = await event.client.download_media( previous_message, "./resources/downloads", ) with open(downloaded_file_name, "r") as fd: message = fd.read() os.remove(downloaded_file_name) else: message = previous_message.message else: message = None if not message: return await xx.eor( "`Reply to a Message/Document or Give me Some Text !`", time=5 ) done, key = await get_paste(message) if not done: return await xx.eor(key) link = f"https://spaceb.in/{key}" raw = f"https://spaceb.in/api/v1/documents/{key}/raw" reply_text = ( f"• **Pasted to SpaceBin :** [Space]({link})\n• **Raw Url :** : [Raw]({raw})" ) try: if event.client._bot: return await xx.eor(reply_text) ok = await event.client.inline_query(asst.me.username, f"pasta-{key}") await ok[0].click(event.chat_id, reply_to=event.reply_to_msg_id, hide_via=True) await xx.delete() except BaseException as e: LOGS.exception(e) await xx.edit(reply_text) pattern="info( (.*)|$)", manager=True, async def _(event): if match := event.pattern_match.group(1).strip(): try: user = await event.client.parse_id(match) except Exception as er: return await event.eor(str(er)) elif event.is_reply: rpl = await event.get_reply_message() user = rpl.sender_id else: user = event.chat_id xx = await event.eor(get_string("com_1")) try: _ = await event.client.get_entity(user) except Exception as er: return await xx.edit(f"**ERROR :** {er}") if not isinstance(_, User): try: peer = get_peer_id(_) photo, capt = await get_chat_info(_, event) if is_gbanned(peer): capt += "\n•<b> Is Gbanned:</b> <code>True</code>" if not photo: return await xx.eor(capt, parse_mode="html") await event.client.send_message( event.chat_id, capt[:1024], file=photo, parse_mode="html" ) await xx.delete() except Exception as er: await event.eor("**ERROR ON CHATINFO**\n" + str(er)) return try: full_user = (await event.client(GetFullUserRequest(user))).full_user except Exception as er: return await xx.edit(f"ERROR : {er}") user = _ user_photos = ( await event.client.get_profile_photos(user.id, limit=0) ).total or "NaN" user_id = user.id first_name = html.escape(user.first_name) if first_name is not None: first_name = first_name.replace("\u2060", "") last_name = user.last_name last_name = ( last_name.replace("\u2060", "") if last_name else ("Last Name not found") ) user_bio = full_user.about if user_bio is not None: user_bio = html.escape(full_user.about) common_chats = full_user.common_chats_count if user.photo: dc_id = user.photo.dc_id else: dc_id = "Need a Profile Picture to check this" caption = """<b>Exᴛʀᴀᴄᴛᴇᴅ Dᴀᴛᴀ Fʀᴏᴍ Tᴇʟᴇɢʀᴀᴍ's Dᴀᴛᴀʙᴀsᴇ<b> <b>••Tᴇʟᴇɢʀᴀᴍ ID</b>: <code>{}</code> <b>••Pᴇʀᴍᴀɴᴇɴᴛ Lɪɴᴋ</b>: <a href='tg://user?id={}'>Click Here</a> <b>••Fɪʀsᴛ Nᴀᴍᴇ</b>: <code>{}</code> <b>••Sᴇᴄᴏɴᴅ Nᴀᴍᴇ</b>: <code>{}</code> <b>••Bɪᴏ</b>: <code>{}</code> <b>••Dᴄ ID</b>: <code>{}</code> <b>••Nᴏ. Oғ PғPs</b> : <code>{}</code> <b>••Is Rᴇsᴛʀɪᴄᴛᴇᴅ</b>: <code>{}</code> <b>••Vᴇʀɪғɪᴇᴅ</b>: <code>{}</code> <b>••Is Pʀᴇᴍɪᴜᴍ</b>: <code>{}</code> <b>••Is A Bᴏᴛ</b>: <code>{}</code> <b>••Gʀᴏᴜᴘs Iɴ Cᴏᴍᴍᴏɴ</b>: <code>{}</code> """.format( user_id, user_id, first_name, last_name, user_bio, dc_id, user_photos, user.restricted, user.verified, user.premium, user.bot, common_chats, ) if chk := is_gbanned(user_id): caption += f"""<b>••Gʟᴏʙᴀʟʟʏ Bᴀɴɴᴇᴅ</b>: <code>True</code> <b>••Rᴇᴀsᴏɴ</b>: <code>{chk}</code>""" await event.client.send_message( event.chat_id, caption, reply_to=event.reply_to_msg_id, parse_mode="HTML", file=full_user.profile_photo, force_document=False, silent=True, ) await xx.delete() pattern="invite( (.*)|$)", groups_only=True, async def _(ult): xx = await ult.eor(get_string("com_1")) to_add_users = ult.pattern_match.group(1).strip() if not ult.is_channel and ult.is_group: for user_id in to_add_users.split(" "): try: await ult.client( AddChatUserRequest( chat_id=ult.chat_id, user_id=await ult.client.parse_id(user_id), fwd_limit=1000000, ), ) await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`") except Exception as e: await xx.edit(str(e)) else: for user_id in to_add_users.split(" "): try: await ult.client( InviteToChannelRequest( channel=ult.chat_id, users=[await ult.client.parse_id(user_id)], ), ) await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`") except UserBotError: await xx.edit( f"Bots can only be added as Admins in Channel.\nBetter Use `{HNDLR}promote {user_id}`" ) except Exception as e: await xx.edit(str(e)) pattern="rmbg($| (.*))", async def _(event): reply_to_id = None match = event.pattern_match.group(1).strip() if event.reply_to_msg_id: msg = await event.get_reply_message() reply_to_id = event.reply_to_msg_id else: msg = event reply_to_id = event.message.id if match and hasattr(msg, match.split()[0]): msg = getattr(msg, match.split()[0]) try: if hasattr(msg, "to_json"): msg = msg.to_json(ensure_ascii=False, indent=1) elif hasattr(msg, "to_dict"): msg = json_parser(msg.to_dict(), indent=1) else: msg = TLObject.stringify(msg) except Exception: pass msg = str(msg) else: msg = json_parser(msg.to_json(), indent=1) if "-t" in match: try: data = json_parser(msg) msg = json_parser( {key: data[key] for key in data.keys() if data[key]}, indent=1 ) except Exception: pass if len(msg) > 4096: with io.BytesIO(str.encode(msg)) as out_file: out_file.name = "json-ult.txt" await event.client.send_file( event.chat_id, out_file, force_document=True, allow_cache=False, reply_to=reply_to_id, ) await event.delete() else: await event.eor(f"```{msg or None}```") from .. import * def get_chat_and_msgid(link): matches = re.findall("https:\\/\\/t\\.me\\/(c\\/|)(.*)\\/(.*)", link) if not matches: return None, None _, chat, msg_id = matches[0] if chat.isdigit(): chat = int("-100" + chat) return chat, int(msg_id) async def get_restriced_msg(event): match = event.pattern_match.group(1).strip() if not match: await event.eor("`Please provide a link!`", time=5) return xx = await event.eor(get_string("com_1")) chat, msg = get_chat_and_msgid(match) if not (chat and msg): return await event.eor( f"{get_string('gms_1')}!\nEg: `https://t.me/TeamUltroid/3 or `https://t.me/c/1313492028/3`" ) try: message = await event.client.get_messages(chat, ids=msg) except BaseException as er: return await event.eor(f"**ERROR**\n`{er}`") try: await event.client.send_message(event.chat_id, message) await xx.try_delete() return except ChatForwardsRestrictedError: pass if message.media: thumb = None if message.document.thumbs: thumb = await message.download_media(thumb=-1) media, _ = await event.client.fast_downloader( message.document, show_progress=True, event=xx, message=f"Downloading {message.file.name}...", ) await xx.edit("`Uploading...`") uploaded, _ = await event.client.fast_uploader( media.name, event=xx, show_progress=True, to_delete=True ) typ = not bool(message.video) await event.reply( message.text, file=uploaded, supports_streaming=typ, force_document=typ, thumb=thumb, attributes=message.document.attributes, ) await xx.delete() if thumb: os.remove(thumb)
null
5,911
from pyUltroid.fns.ytdl import download_yt, get_yt_link from . import get_string, requests, ultroid_cmd def get_yt_link(query): search = VideosSearch(query, limit=1).result() try: return search["result"][0]["link"] except IndexError: return async def download_yt(event, link, ytd): reply_to = event.reply_to_msg_id or event info = await dler(event, link, ytd, download=True) if not info: return if info.get("_type", None) == "playlist": total = info["playlist_count"] for num, file in enumerate(info["entries"]): num += 1 id_ = file["id"] thumb = id_ + ".jpg" title = file["title"] await download_file( file.get("thumbnail", None) or file["thumbnails"][-1]["url"], thumb ) ext = "." + ytd["outtmpl"]["default"].split(".")[-1] if ext == ".m4a": ext = ".mp3" id = None for x in glob.glob(f"{id_}*"): if not x.endswith("jpg"): id = x if not id: return ext = "." + id.split(".")[-1] file = title + ext try: os.rename(id, file) except FileNotFoundError: try: os.rename(id + ext, file) except FileNotFoundError as er: if os.path.exists(id): file = id else: raise er if file.endswith(".part"): os.remove(file) os.remove(thumb) await event.client.send_message( event.chat_id, f"`[{num}/{total}]` `Invalid Video format.\nIgnoring that...`", ) return attributes = await set_attributes(file) res, _ = await event.client.fast_uploader( file, show_progress=True, event=event, to_delete=True ) from_ = info["extractor"].split(":")[0] caption = f"`[{num}/{total}]` `{title}`\n\n`from {from_}`" await event.client.send_file( event.chat_id, file=res, caption=caption, attributes=attributes, supports_streaming=True, thumb=thumb, reply_to=reply_to, ) os.remove(thumb) try: await event.delete() except BaseException: pass return title = info["title"] if len(title) > 20: title = title[:17] + "..." id_ = info["id"] thumb = id_ + ".jpg" await download_file( info.get("thumbnail", None) or f"https://i.ytimg.com/vi/{id_}/hqdefault.jpg", thumb, ) ext = "." + ytd["outtmpl"]["default"].split(".")[-1] for _ext in [".m4a", ".mp3", ".opus"]: if ext == _ext: ext = _ext break id = None for x in glob.glob(f"{id_}*"): if not x.endswith("jpg"): id = x if not id: return ext = "." + id.split(".")[-1] file = title + ext try: os.rename(id, file) except FileNotFoundError: os.rename(id + ext, file) attributes = await set_attributes(file) res, _ = await event.client.fast_uploader( file, show_progress=True, event=event, to_delete=True ) caption = f"`{info['title']}`" await event.client.send_file( event.chat_id, file=res, caption=caption, attributes=attributes, supports_streaming=True, thumb=thumb, reply_to=reply_to, ) os.remove(thumb) try: await event.delete() except BaseException: pass async def download_from_youtube_(event): ytd = { "prefer_ffmpeg": True, "addmetadata": True, "geo-bypass": True, "nocheckcertificate": True, } opt = event.pattern_match.group(1).strip() xx = await event.eor(get_string("com_1")) if opt == "a": ytd["format"] = "bestaudio" ytd["outtmpl"] = "%(id)s.m4a" url = event.pattern_match.group(2) if not url: return await xx.eor(get_string("youtube_1")) try: requests.get(url) except BaseException: return await xx.eor(get_string("youtube_2")) elif opt == "v": ytd["format"] = "best" ytd["outtmpl"] = "%(id)s.mp4" ytd["postprocessors"] = [{"key": "FFmpegMetadata"}] url = event.pattern_match.group(2) if not url: return await xx.eor(get_string("youtube_3")) try: requests.get(url) except BaseException: return await xx.eor(get_string("youtube_4")) elif opt == "sa": ytd["format"] = "bestaudio" ytd["outtmpl"] = "%(id)s.m4a" try: query = event.text.split(" ", 1)[1] except IndexError: return await xx.eor(get_string("youtube_5")) url = get_yt_link(query) if not url: return await xx.edit(get_string("unspl_1")) await xx.eor(get_string("youtube_6")) elif opt == "sv": ytd["format"] = "best" ytd["outtmpl"] = "%(id)s.mp4" ytd["postprocessors"] = [{"key": "FFmpegMetadata"}] try: query = event.text.split(" ", 1)[1] except IndexError: return await xx.eor(get_string("youtube_7")) url = get_yt_link(query) if not url: return await xx.edit(get_string("unspl_1")) await xx.eor(get_string("youtube_8")) else: return await download_yt(xx, url, ytd)
null
5,912
from datetime import timedelta from pyUltroid.fns.admins import ban_time from . import get_string, ultroid_cmd def ban_time(time_str): """Simplify ban time from text""" if not any(time_str.endswith(unit) for unit in ("s", "m", "h", "d")): time_str += "s" unit = time_str[-1] time_int = time_str[:-1] if not time_int.isdigit(): raise Exception("Invalid time amount specified.") to_return = "" if unit == "s": to_return = int(time.time() + int(time_int)) elif unit == "m": to_return = int(time.time() + int(time_int) * 60) elif unit == "h": to_return = int(time.time() + int(time_int) * 60 * 60) elif unit == "d": to_return = int(time.time() + int(time_int) * 24 * 60 * 60) return to_return async def _(e): x = e.pattern_match.group(1).strip() xx = await e.get_reply_message() if x and not xx: y = x.split(" ")[-1] k = x.replace(y, "") if y.isdigit(): await e.client.send_message( e.chat_id, k, schedule=timedelta(seconds=int(y)) ) await e.eor(get_string("schdl_1"), time=5) else: try: z = ban_time(y) await e.respond(k, schedule=z) await e.eor(get_string("schdl_1"), time=5) except BaseException: await e.eor(get_string("schdl_2"), time=5) elif xx and x: if x.isdigit(): await e.respond(xx, schedule=timedelta(seconds=int(x))) await e.eor(get_string("schdl_1"), time=5) else: try: z = ban_time(x) await e.respond(xx, schedule=z) await e.eor(get_string("schdl_1"), time=5) except BaseException: await e.eor(get_string("schdl_2"), time=5) else: return await e.eor(get_string("schdl_2"), time=5)
null
5,913
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) alive_txt = """ The Ultroid Userbot ◍ Version - {} ◍ Py-Ultroid - {} ◍ Telethon - {} """ __version__ = "2023.02.20" async def alive(event): text = alive_txt.format(ultroid_version, UltVer, __version__) await event.answer(text, alert=True)
null
5,914
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) buttons = [ [ Button.url(get_string("bot_3"), "https://github.com/TeamUltroid/Ultroid"), Button.url(get_string("bot_4"), "t.me/UltroidSupportChat"), ] ] in_alive = "{}\n\n🌀 <b>Ultroid Version -><b> <code>{}</code>\n🌀 <b>PyUltroid -></b> <code>{}</code>\n🌀 <b>Python -></b> <code>{}</code>\n🌀 <b>Uptime -></b> <code>{}</code>\n🌀 <b>Branch -></b>[ {} ]\n\n• <b>Join @TeamUltroid</b>" __version__ = "2023.02.20" async def lol(ult): match = ult.pattern_match.group(1).strip() inline = None if match in ["inline", "i"]: try: res = await ult.client.inline_query(asst.me.username, "alive") return await res[0].click(ult.chat_id) except BotMethodInvalidError: pass except BaseException as er: LOGS.exception(er) inline = True pic = udB.get_key("ALIVE_PIC") if isinstance(pic, list): pic = choice(pic) uptime = time_formatter((time.time() - start_time) * 1000) header = udB.get_key("ALIVE_TEXT") or get_string("bot_1") y = Repo().active_branch xx = Repo().remotes[0].config_reader.get("url") rep = xx.replace(".git", f"/tree/{y}") kk = f" `[{y}]({rep})` " if inline: kk = f"<a href={rep}>{y}</a>" parse = "html" als = in_alive.format( header, f"{ultroid_version} [{HOSTED_ON}]", UltVer, pyver(), uptime, kk, ) if _e := udB.get_key("ALIVE_EMOJI"): als = als.replace("🌀", _e) else: parse = "md" als = (get_string("alive_1")).format( header, OWNER_NAME, f"{ultroid_version} [{HOSTED_ON}]", UltVer, uptime, pyver(), __version__, kk, ) if a := udB.get_key("ALIVE_EMOJI"): als = als.replace("✵", a) if pic: try: await ult.reply( als, file=pic, parse_mode=parse, link_preview=False, buttons=buttons if inline else None, ) return await ult.try_delete() except ChatSendMediaForbiddenError: pass except BaseException as er: LOGS.exception(er) try: await ult.reply(file=pic) await ult.reply( als, parse_mode=parse, buttons=buttons if inline else None, link_preview=False, ) return await ult.try_delete() except BaseException as er: LOGS.exception(er) await eor( ult, als, parse_mode=parse, link_preview=False, buttons=buttons if inline else None, )
null
5,915
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) async def _(event): start = time.time() x = await event.eor("Pong !") end = round((time.time() - start) * 1000) uptime = time_formatter((time.time() - start_time) * 1000) await x.edit(get_string("ping").format(end, uptime))
null
5,916
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) async def cmds(event): await allcmds(event, Telegraph)
null
5,917
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) heroku_api = Var.HEROKU_API async def restartbt(ult): ok = await ult.eor(get_string("bot_5")) call_back() who = "bot" if ult.client._bot else "user" udB.set_key("_RESTART", f"{who}_{ult.chat_id}_{ok.id}") if heroku_api: return await restart(ok) await bash("git pull && pip3 install -r requirements.txt") if len(sys.argv) > 1: os.execl(sys.executable, sys.executable, "main.py") else: os.execl(sys.executable, sys.executable, "-m", "pyUltroid")
null
5,918
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) async def shutdownbot(ult): await shutdown(ult)
null
5,919
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) async def _(event): opt = event.pattern_match.group(1).strip() file = f"ultroid{sys.argv[-1]}.log" if len(sys.argv) > 1 else "ultroid.log" if opt == "heroku": await heroku_logs(event) elif opt == "carbon" and Carbon: event = await event.eor(get_string("com_1")) with open(file, "r") as f: code = f.read()[-2500:] file = await Carbon( file_name="ultroid-logs", code=code, backgroundColor=choice(ATRA_COL), ) if isinstance(file, dict): await event.eor(f"`{file}`") return await event.reply("**Ultroid Logs.**", file=file) elif opt == "open": with open("ultroid.log", "r") as f: file = f.read()[-4000:] return await event.eor(f"`{file}`") else: await def_logs(event, file) await event.try_delete()
null
5,920
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) buttons = [ [ Button.url(get_string("bot_3"), "https://github.com/TeamUltroid/Ultroid"), Button.url(get_string("bot_4"), "t.me/UltroidSupportChat"), ] ] in_alive = "{}\n\n🌀 <b>Ultroid Version -><b> <code>{}</code>\n🌀 <b>PyUltroid -></b> <code>{}</code>\n🌀 <b>Python -></b> <code>{}</code>\n🌀 <b>Uptime -></b> <code>{}</code>\n🌀 <b>Branch -></b>[ {} ]\n\n• <b>Join @TeamUltroid</b>" async def inline_alive(ult): pic = udB.get_key("ALIVE_PIC") if isinstance(pic, list): pic = choice(pic) uptime = time_formatter((time.time() - start_time) * 1000) header = udB.get_key("ALIVE_TEXT") or get_string("bot_1") y = Repo().active_branch xx = Repo().remotes[0].config_reader.get("url") rep = xx.replace(".git", f"/tree/{y}") kk = f"<a href={rep}>{y}</a>" als = in_alive.format( header, f"{ultroid_version} [{HOSTED_ON}]", UltVer, pyver(), uptime, kk ) if _e := udB.get_key("ALIVE_EMOJI"): als = als.replace("🌀", _e) builder = ult.builder if pic: try: if ".jpg" in pic: results = [ await builder.photo( pic, text=als, parse_mode="html", buttons=buttons ) ] else: if _pic := resolve_bot_file_id(pic): pic = _pic buttons.insert( 0, [Button.inline(get_string("bot_2"), data="alive")] ) results = [ await builder.document( pic, title="Inline Alive", description="@TeamUltroid", parse_mode="html", buttons=buttons, ) ] return await ult.answer(results) except BaseException as er: LOGS.exception(er) result = [ await builder.article( "Alive", text=als, parse_mode="html", link_preview=False, buttons=buttons ) ] await ult.answer(result)
null
5,921
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) def ULTPIC(): return inline_pic() or choice(ULTROID_IMAGES) buttons = [ [ Button.url(get_string("bot_3"), "https://github.com/TeamUltroid/Ultroid"), Button.url(get_string("bot_4"), "t.me/UltroidSupportChat"), ] ] async def _(e): xx = await e.eor(get_string("upd_1")) if e.pattern_match.group(1).strip() and ( "fast" in e.pattern_match.group(1).strip() or "soft" in e.pattern_match.group(1).strip() ): await bash("git pull -f && pip3 install -r requirements.txt") call_back() await xx.edit(get_string("upd_7")) os.execl(sys.executable, "python3", "-m", "pyUltroid") # return m = await updater() branch = (Repo.init()).active_branch if m: x = await asst.send_file( udB.get_key("LOG_CHANNEL"), ULTPIC(), caption="• **Update Available** •", force_document=False, buttons=Button.inline("Changelogs", data="changes"), ) Link = x.message_link await xx.edit( f'<strong><a href="{Link}">[ChangeLogs]</a></strong>', parse_mode="html", link_preview=False, ) else: await xx.edit( f'<code>Your BOT is </code><strong>up-to-date</strong><code> with </code><strong><a href="https://github.com/TeamUltroid/Ultroid/tree/{branch}">[{branch}]</a></strong>', parse_mode="html", link_preview=False, )
null
5,922
from . import get_help import os import sys import time from platform import python_version as pyver from random import choice from telethon import __version__ from telethon.errors.rpcerrorlist import ( BotMethodInvalidError, ChatSendMediaForbiddenError, ) from pyUltroid.version import __version__ as UltVer from . import HOSTED_ON, LOGS from telethon.utils import resolve_bot_file_id from . import ( ATRA_COL, LOGS, OWNER_NAME, ULTROID_IMAGES, Button, Carbon, Telegraph, Var, allcmds, asst, bash, call_back, callback, def_logs, eor, get_string, heroku_logs, in_pattern, inline_pic, restart, shutdown, start_time, time_formatter, udB, ultroid_cmd, ultroid_version, updater, ) def ULTPIC(): return inline_pic() or choice(ULTROID_IMAGES) buttons = [ [ Button.url(get_string("bot_3"), "https://github.com/TeamUltroid/Ultroid"), Button.url(get_string("bot_4"), "t.me/UltroidSupportChat"), ] ] async def updava(event): await event.delete() await asst.send_file( udB.get_key("LOG_CHANNEL"), ULTPIC(), caption="• **Update Available** •", force_document=False, buttons=Button.inline("Changelogs", data="changes"), )
null
5,923
from . import get_help from telethon.utils import get_display_name from pyUltroid.dB.echo_db import add_echo, check_echo, list_echo, rem_echo from . import inline_mention, ultroid_cmd def add_echo(chat, user): x = get_stuff() if k := x.get(int(chat)): if user not in k: k.append(int(user)) x.update({int(chat): k}) else: x.update({int(chat): [int(user)]}) return udB.set_key("ECHO", x) def check_echo(chat, user): x = get_stuff() if (k := x.get(int(chat))) and int(user) in k: return True async def echo(e): r = await e.get_reply_message() if r: user = r.sender_id else: try: user = e.text.split()[1] if user.startswith("@"): ok = await e.client.get_entity(user) user = ok.id else: user = int(user) except BaseException: return await e.eor("Reply To A user.", time=5) if check_echo(e.chat_id, user): return await e.eor("Echo already activated for this user.", time=5) add_echo(e.chat_id, user) ok = await e.client.get_entity(user) user = inline_mention(ok) await e.eor(f"Activated Echo For {user}.")
null
5,924
from . import get_help from telethon.utils import get_display_name from pyUltroid.dB.echo_db import add_echo, check_echo, list_echo, rem_echo from . import inline_mention, ultroid_cmd def rem_echo(chat, user): x = get_stuff() if k := x.get(int(chat)): if user in k: k.remove(int(user)) x.update({int(chat): k}) return udB.set_key("ECHO", x) def check_echo(chat, user): x = get_stuff() if (k := x.get(int(chat))) and int(user) in k: return True async def rm(e): r = await e.get_reply_message() if r: user = r.sender_id else: try: user = e.text.split()[1] if user.startswith("@"): ok = await e.client.get_entity(user) user = ok.id else: user = int(user) except BaseException: return await e.eor("Reply To A User.", time=5) if check_echo(e.chat_id, user): rem_echo(e.chat_id, user) ok = await e.client.get_entity(user) user = f"[{get_display_name(ok)}](tg://user?id={ok.id})" return await e.eor(f"Deactivated Echo For {user}.") await e.eor("Echo not activated for this user")
null
5,925
from . import get_help from telethon.utils import get_display_name from pyUltroid.dB.echo_db import add_echo, check_echo, list_echo, rem_echo from . import inline_mention, ultroid_cmd def list_echo(chat): x = get_stuff() return x.get(int(chat)) async def lstecho(e): if k := list_echo(e.chat_id): user = "**Activated Echo For Users:**\n\n" for x in k: ok = await e.client.get_entity(int(x)) kk = f"[{get_display_name(ok)}](tg://user?id={ok.id})" user += f"•{kk}" + "\n" await e.eor(user) else: await e.eor("`List is Empty, For echo`", time=5)
null
5,926
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu SUP_BUTTONS = [ [ Button.url("• Repo •", url="https://github.com/TeamUltroid/Ultroid"), Button.url("• Support •", url="t.me/UltroidSupportChat"), ], ] async def inline_alive(o): TLINK = inline_pic() or "https://graph.org/file/74d6259983e0642923fdb.jpg" MSG = "• **Ultroid Userbot •**" WEB0 = InputWebDocument( "https://graph.org/file/acd4f5d61369f74c5e7a7.jpg", 0, "image/jpg", [] ) RES = [ await o.builder.article( type="photo", text=MSG, include_media=True, buttons=SUP_BUTTONS, title="Ultroid Userbot", description="Userbot | Telethon", url=TLINK, thumb=WEB0, content=InputWebDocument(TLINK, 0, "image/jpg", []), ) ] await o.answer( RES, private=True, cache_time=300, switch_pm="👥 ULTROID PORTAL", switch_pm_param="start", )
null
5,927
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu HELP = {} LIST = {} _main_help_menu = [ [ Button.inline(get_string("help_4"), data="uh_Official_"), Button.inline(get_string("help_5"), data="uh_Addons_"), ], [ Button.inline(get_string("help_6"), data="uh_VCBot_"), Button.inline(get_string("help_7"), data="inlone"), ], [ Button.inline(get_string("help_8"), data="ownr"), Button.url( get_string("help_9"), url=f"https://t.me/{asst.me.username}?start=set" ), ], [Button.inline(get_string("help_10"), data="close")], ] async def inline_handler(event): z = [] for x in LIST.values(): z.extend(x) text = get_string("inline_4").format( OWNER_NAME, len(HELP.get("Official", [])), len(HELP.get("Addons", [])), len(z), ) if inline_pic(): result = await event.builder.photo( file=inline_pic(), link_preview=False, text=text, buttons=_main_help_menu, ) else: result = await event.builder.article( title="Ultroid Help Menu", text=text, buttons=_main_help_menu ) await event.answer([result], private=True, cache_time=300, gallery=True)
null
5,928
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu HELP = {} LIST = {} async def setting(event): z = [] for x in LIST.values(): z.extend(x) await event.edit( get_string("inline_4").format( OWNER_NAME, len(HELP.get("Official", [])), len(HELP.get("Addons", [])), len(z), ), file=inline_pic(), link_preview=False, buttons=[ [ Button.inline("•Pɪɴɢ•", data="pkng"), Button.inline("•Uᴘᴛɪᴍᴇ•", data="upp"), ], [ Button.inline("•Stats•", data="alive"), Button.inline("•Uᴘᴅᴀᴛᴇ•", data="doupdate"), ], [Button.inline("« Bᴀᴄᴋ", data="open")], ], )
null
5,929
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu async def _(event): ok = event.text.split("-")[1] link = f"https://spaceb.in/{ok}" raw = f"https://spaceb.in/api/v1/documents/{ok}/raw" result = await event.builder.article( title="Paste", text="Pasted to Spacebin 🌌", buttons=[ [ Button.url("SpaceBin", url=link), Button.url("Raw", url=raw), ], ], ) await event.answer([result]) _strings = {"Official": helps, "Addons": zhelps, "VCBot": get_string("inline_6")} async def _(event): if not await updater(): return await event.answer(get_string("inline_9"), cache_time=0, alert=True) if not inline_pic(): return await event.answer(f"Do '{HNDLR}update' to update..") repo = Repo.init() changelog, tl_chnglog = await gen_chlog( repo, f"HEAD..upstream/{repo.active_branch}" ) changelog_str = changelog + "\n\n" + get_string("inline_8") if len(changelog_str) > 1024: await event.edit(get_string("upd_4")) with open("ultroid_updates.txt", "w+") as file: file.write(tl_chnglog) await event.edit( get_string("upd_5"), file="ultroid_updates.txt", buttons=[ [Button.inline("• Uᴘᴅᴀᴛᴇ Nᴏᴡ •", data="updatenow")], [Button.inline("« Bᴀᴄᴋ", data="ownr")], ], ) remove("ultroid_updates.txt") else: await event.edit( changelog_str, buttons=[ [Button.inline("Update Now", data="updatenow")], [Button.inline("« Bᴀᴄᴋ", data="ownr")], ], parse_mode="html", ) async def _(event): start = datetime.now() end = datetime.now() ms = (end - start).microseconds pin = f"🌋Pɪɴɢ = {ms} microseconds" await event.answer(pin, cache_time=0, alert=True) async def _(event): uptime = time_formatter((time.time() - start_time) * 1000) pin = f"🙋Uᴘᴛɪᴍᴇ = {uptime}" await event.answer(pin, cache_time=0, alert=True) async def _(e): _InButtons = [ Button.switch_inline(_, query=InlinePlugin[_], same_peer=True) for _ in list(InlinePlugin.keys()) ] InButtons = split_list(_InButtons, 2) button = InButtons.copy() button.append( [ Button.inline("« Bᴀᴄᴋ", data="open"), ], ) await e.edit(buttons=button, link_preview=False) def page_num(index, key): rows = udB.get_key("HELP_ROWS") or 5 cols = udB.get_key("HELP_COLUMNS") or 2 loaded = HELP.get(key, []) emoji = udB.get_key("EMOJI_IN_HELP") or "✘" List = [ Button.inline(f"{emoji} {x} {emoji}", data=f"uplugin_{key}_{x}|{index}") for x in sorted(loaded) ] all_ = split_list(List, cols) fl_ = split_list(all_, rows) try: new_ = fl_[index] except IndexError: new_ = fl_[0] if fl_ else [] index = 0 if index == 0 and len(fl_) == 1: new_.append([Button.inline("« Bᴀᴄᴋ »", data="open")]) else: new_.append( [ Button.inline( "« Pʀᴇᴠɪᴏᴜs", data=f"uh_{key}_{index-1}", ), Button.inline("« Bᴀᴄᴋ »", data="open"), Button.inline( "Nᴇxᴛ »", data=f"uh_{key}_{index+1}", ), ] ) return new_ HELP = {} async def help_func(ult): key, count = ult.data_match.group(1).decode("utf-8").split("_") if key == "VCBot" and HELP.get("VCBot") is None: return await ult.answer(get_string("help_12"), alert=True) elif key == "Addons" and HELP.get("Addons") is None: return await ult.answer(get_string("help_13").format(HNDLR), alert=True) if "|" in count: _, count = count.split("|") count = int(count) if count else 0 text = _strings.get(key, "").format(OWNER_NAME, len(HELP.get(key))) await ult.edit(text, buttons=page_num(count, key), link_preview=False)
null
5,930
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu HELP = {} LIST = {} async def uptd_plugin(event): key, file = event.data_match.group(1).decode("utf-8").split("_") index = None if "|" in file: file, index = file.split("|") key_ = HELP.get(key, []) hel_p = f"Plugin Name - `{file}`\n" help_ = "" try: for i in key_[file]: help_ += i except BaseException: if file in LIST: help_ = get_string("help_11").format(file) for d in LIST[file]: help_ += HNDLR + d help_ += "\n" if not help_: help_ = f"{file} has no Detailed Help!" help_ += "\n© @TeamUltroid" buttons = [] if inline_pic(): data = f"sndplug_{key}_{file}" if index is not None: data += f"|{index}" buttons.append( [ Button.inline( "« Sᴇɴᴅ Pʟᴜɢɪɴ »", data=data, ) ] ) data = f"uh_{key}_" if index is not None: data += f"|{index}" buttons.append( [ Button.inline("« Bᴀᴄᴋ", data=data), ] ) try: await event.edit(help_, buttons=buttons) except Exception as er: LOGS.exception(er) help = f"Do `{HNDLR}help {key}` to get list of commands." await event.edit(help, buttons=buttons)
null
5,931
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu HELP = {} LIST = {} _main_help_menu = [ [ Button.inline(get_string("help_4"), data="uh_Official_"), Button.inline(get_string("help_5"), data="uh_Addons_"), ], [ Button.inline(get_string("help_6"), data="uh_VCBot_"), Button.inline(get_string("help_7"), data="inlone"), ], [ Button.inline(get_string("help_8"), data="ownr"), Button.url( get_string("help_9"), url=f"https://t.me/{asst.me.username}?start=set" ), ], [Button.inline(get_string("help_10"), data="close")], ] async def opner(event): z = [] for x in LIST.values(): z.extend(x) await event.edit( get_string("inline_4").format( OWNER_NAME, len(HELP.get("Official", [])), len(HELP.get("Addons", [])), len(z), ), buttons=_main_help_menu, link_preview=False, )
null
5,932
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu async def on_plug_in_callback_query_handler(event): await event.edit( get_string("inline_5"), buttons=Button.inline("Oᴘᴇɴ Aɢᴀɪɴ", data="open"), )
null
5,933
import re import time from datetime import datetime from os import remove from git import Repo from telethon import Button from telethon.tl.types import InputWebDocument, Message from telethon.utils import resolve_bot_file_id from pyUltroid._misc._assistant import callback, in_pattern from pyUltroid.dB._core import HELP, LIST from pyUltroid.fns.helper import gen_chlog, time_formatter, updater from pyUltroid.fns.misc import split_list from . import ( HNDLR, LOGS, OWNER_NAME, InlinePlugin, asst, get_string, inline_pic, split_list, start_time, udB, ) from ._help import _main_help_menu STUFF = {} async def ibuild(e): n = e.pattern_match.group(1).strip() builder = e.builder if not (n and n.isdigit()): return ok = STUFF.get(int(n)) txt = ok.get("msg") pic = ok.get("media") btn = ok.get("button") if not (pic or txt): txt = "Hey!" if pic: try: include_media = True mime_type, _pic = None, None cont, results = None, None try: ext = str(pic).split(".")[-1].lower() except BaseException: ext = None if ext in ["img", "jpg", "png"]: _type = "photo" mime_type = "image/jpg" elif ext in ["mp4", "mkv", "gif"]: mime_type = "video/mp4" _type = "gif" else: try: if "telethon.tl.types" in str(type(pic)): _pic = pic else: _pic = resolve_bot_file_id(pic) except BaseException: pass if _pic: results = [ await builder.document( _pic, title="Ultroid Op", text=txt, description="@TeamUltroid", buttons=btn, link_preview=False, ) ] else: _type = "article" include_media = False if not results: if include_media: cont = InputWebDocument(pic, 0, mime_type, []) results = [ await builder.article( title="Ultroid Op", type=_type, text=txt, description="@TeamUltroid", include_media=include_media, buttons=btn, thumb=cont, content=cont, link_preview=False, ) ] return await e.answer(results) except Exception as er: LOGS.exception(er) result = [ await builder.article("Ultroid Op", text=txt, link_preview=False, buttons=btn) ] await e.answer(result)
null
5,934
import io from pyUltroid.fns.misc import get_synonyms_or_antonyms from pyUltroid.fns.tools import async_searcher from . import get_string, ultroid_cmd async def mean(event): wrd = event.pattern_match.group(1).strip() if not wrd: return await event.eor(get_string("wrd_4")) url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{wrd}" out = await async_searcher(url, re_json=True) try: return await event.eor(f'**{out["title"]}**') except (KeyError, TypeError): pass defi = out[0]["meanings"][0]["definitions"][0] ex = defi["example"] if defi.get("example") else "None" text = get_string("wrd_1").format(wrd, defi["definition"], ex) if defi.get("synonyms"): text += ( f"\n\n• **{get_string('wrd_5')} :**" + "".join(f" {a}," for a in defi["synonyms"])[:-1][:10] ) if defi.get("antonyms"): text += ( f"\n\n**{get_string('wrd_6')} :**" + "".join(f" {a}," for a in defi["antonyms"])[:-1][:10] ) if len(text) > 4096: with io.BytesIO(str.encode(text)) as fle: fle.name = f"{wrd}-meanings.txt" await event.reply( file=fle, force_document=True, caption=f"Meanings of {wrd}", ) await event.delete() else: await event.eor(text)
null
5,935
import io from pyUltroid.fns.misc import get_synonyms_or_antonyms from pyUltroid.fns.tools import async_searcher from . import get_string, ultroid_cmd from .. import * async def get_synonyms_or_antonyms(word, type_of_words): if type_of_words not in ["synonyms", "antonyms"]: return "Dude! Please give a corrent type of words you want." s = await async_searcher( f"https://tuna.thesaurus.com/pageData/{word}", re_json=True ) li_1 = [ y for x in [ s["data"]["definitionData"]["definitions"][0][type_of_words], s["data"]["definitionData"]["definitions"][1][type_of_words], ] for y in x ] return [y["term"] for y in li_1] async def mean(event): task = event.pattern_match.group(1) + "nyms" try: wrd = event.text.split(maxsplit=1)[1] except IndexError: return await event.eor("Give Something to search..") try: ok = await get_synonyms_or_antonyms(wrd, task) x = get_string("wrd_2" if task == "synonyms" else "wrd_3").format(wrd) for c, i in enumerate(ok, start=1): x += f"**{c}.** `{i}`\n" if len(x) > 4096: with io.BytesIO(str.encode(x)) as fle: fle.name = f"{wrd}-{task}.txt" await event.client.send_file( event.chat_id, fle, force_document=True, allow_cache=False, caption=f"{task} of {wrd}", reply_to=event.reply_to_msg_id, ) await event.delete() else: await event.eor(x) except Exception as e: await event.eor( get_string("wrd_7" if task == "synonyms" else "wrd_8").format(e) )
null
5,936
import io from pyUltroid.fns.misc import get_synonyms_or_antonyms from pyUltroid.fns.tools import async_searcher from . import get_string, ultroid_cmd async def _(event): word = event.pattern_match.group(1).strip() if not word: return await event.eor(get_string("autopic_1")) out = await async_searcher( "http://api.urbandictionary.com/v0/define", params={"term": word}, re_json=True ) try: out = out["list"][0] except IndexError: return await event.eor(get_string("autopic_2").format(word)) await event.eor( get_string("wrd_1").format(out["word"], out["definition"], out["example"]), )
null
5,937
import re from telethon import Button from telethon.errors.rpcerrorlist import ( BotInlineDisabledError, BotResponseTimeoutError, MessageNotModifiedError, ) from telethon.tl import types from telethon.tl.functions.users import GetFullUserRequest as gu from . import ( HNDLR, LOGS, asst, callback, get_string, in_pattern, inline_mention, ultroid_bot, ultroid_cmd, ) async def _(e): if e.reply_to_msg_id: okk = await e.get_reply_message() put = f"@{okk.sender.username}" if okk.sender.username else okk.sender_id else: put = e.pattern_match.group(1).strip() if put: try: results = await e.client.inline_query(asst.me.username, f"msg {put}") except BotResponseTimeoutError: return await e.eor( get_string("help_2").format(HNDLR), ) except BotInlineDisabledError: return await e.eor(get_string("help_3")) await results[0].click(e.chat_id, reply_to=e.reply_to_msg_id, hide_via=True) return await e.delete() await e.eor(get_string("wspr_3"))
null
5,938
import re from telethon import Button from telethon.errors.rpcerrorlist import ( BotInlineDisabledError, BotResponseTimeoutError, MessageNotModifiedError, ) from telethon.tl import types from telethon.tl.functions.users import GetFullUserRequest as gu from . import ( HNDLR, LOGS, asst, callback, get_string, in_pattern, inline_mention, ultroid_bot, ultroid_cmd, ) buddhhu = {} async def _(e): iuser = e.query.user_id zzz = e.text.split(maxsplit=2) try: query = zzz[1] if query.isdigit(): query = int(query) logi = await ultroid_bot.get_entity(query) if not isinstance(logi, types.User): raise ValueError("Invalid Username.") except IndexError: sur = await e.builder.article( title="Give Username", description="You Didn't Type Username or id.", text="You Didn't Type Username or id.", ) return await e.answer([sur]) except ValueError as er: LOGS.exception(er) sur = await e.builder.article( title="User Not Found", description="Make sure username or id is correct.", text="Make sure username or id is correct.", ) return await e.answer([sur]) try: desc = zzz[2] except IndexError: sur = await e.builder.article( title="Type ur msg", text="You Didn't Type Your Msg" ) return await e.answer([sur]) button = [ [ Button.inline("Secret Msg", data=f"dd_{e.id}"), Button.inline("Delete Msg", data=f"del_{e.id}"), ], [ Button.switch_inline( "New", query=f"wspr {logi.username or logi.id}", same_peer=True ) ], ] us = logi.username or logi.first_name sur = await e.builder.article( title=logi.first_name, description=desc, text=get_string("wspr_1").format(us), buttons=button, ) buddhhu.update({e.id: [logi.id, iuser, desc]}) await e.answer([sur])
null
5,939
import re from telethon import Button from telethon.errors.rpcerrorlist import ( BotInlineDisabledError, BotResponseTimeoutError, MessageNotModifiedError, ) from telethon.tl import types from telethon.tl.functions.users import GetFullUserRequest as gu from . import ( HNDLR, LOGS, asst, callback, get_string, in_pattern, inline_mention, ultroid_bot, ultroid_cmd, ) async def _(e): zzz = e.text.split(maxsplit=1) desc = "Touch me" try: query = zzz[1] if query.isdigit(): query = int(query) logi = await ultroid_bot(gu(id=query)) user = logi.users[0] mention = inline_mention(user) x = user.status if isinstance(x, types.UserStatusOnline): status = "Online" elif isinstance(x, types.UserStatusOffline): status = "Offline" elif isinstance(x, types.UserStatusRecently): status = "Last Seen Recently" elif isinstance(x, types.UserStatusLastMonth): status = "Last seen months ago" elif isinstance(x, types.UserStatusLastWeek): status = "Last seen weeks ago" else: status = "Can't Tell" text = f"**Name:** `{user.first_name}`\n" text += f"**Id:** `{user.id}`\n" if user.username: text += f"**Username:** `{user.username}`\n" url = f"https://t.me/{user.username}" else: text += f"**Mention:** `{mention}`\n" url = f"tg://user?id={user.id}" text += f"**Status:** `{status}`\n" text += f"**About:** `{logi.full_user.about}`" button = [ Button.url("Private", url=url), Button.switch_inline( "Secret msg", query=f"wspr {query} Hello 👋", same_peer=True, ), ] sur = e.builder.article( title=user.first_name, description=desc, text=text, buttons=button, ) except IndexError: sur = e.builder.article( title="Give Username", description="You Didn't Type Username or id.", text="You Didn't Type Username or id.", ) except BaseException as er: LOGS.exception(er) name = get_string("wspr_4").format(query) sur = e.builder.article( title=name, text=name, ) await e.answer([sur])
null
5,940
import re from telethon import Button from telethon.errors.rpcerrorlist import ( BotInlineDisabledError, BotResponseTimeoutError, MessageNotModifiedError, ) from telethon.tl import types from telethon.tl.functions.users import GetFullUserRequest as gu from . import ( HNDLR, LOGS, asst, callback, get_string, in_pattern, inline_mention, ultroid_bot, ultroid_cmd, ) buddhhu = {} async def _(e): ids = int(e.pattern_match.group(1).strip().decode("UTF-8")) if buddhhu.get(ids): if e.sender_id in buddhhu[ids]: await e.answer(buddhhu[ids][-1], alert=True) else: await e.answer("Not For You", alert=True) else: await e.answer(get_string("wspr_2"), alert=True)
null
5,941
import re from telethon import Button from telethon.errors.rpcerrorlist import ( BotInlineDisabledError, BotResponseTimeoutError, MessageNotModifiedError, ) from telethon.tl import types from telethon.tl.functions.users import GetFullUserRequest as gu from . import ( HNDLR, LOGS, asst, callback, get_string, in_pattern, inline_mention, ultroid_bot, ultroid_cmd, ) buddhhu = {} async def _(e): ids = int(e.pattern_match.group(1).strip().decode("UTF-8")) if buddhhu.get(ids): if e.sender_id in buddhhu[ids]: buddhhu.pop(ids) try: await e.edit(get_string("wspr_2")) except MessageNotModifiedError: pass else: await e.answer(get_string("wspr_5"), alert=True)
null
5,942
from . import get_help import os from pyUltroid.dB.asstcmd_db import add_cmd, cmd_reply, list_cmds, rem_cmd from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from telethon import events, utils from . import asst, get_string, mediainfo, udB, ultroid_cmd async def astcmds(e): xx = (e.text.replace("/", "")).lower().split()[0] if cmd_reply(xx): msg, media, bt = cmd_reply(xx) if bt: bt = create_tl_btn(bt) await e.reply(msg, file=media, buttons=bt) def add_cmd(cmd, msg, media, button): ok = get_stuff() ok.update({cmd: {"msg": msg, "media": media, "button": button}}) return udB.set_key("ASST_CMDS", ok) def list_cmds(): ok = get_stuff() return ok.keys() from .. import * def get_msg_button(texts: str): btn = [] for z in re.findall("\\[(.*?)\\|(.*?)\\]", texts): text, url = z urls = url.split("|") url = urls[0] if len(urls) > 1: btn[-1].append([text, url]) else: btn.append([[text, url]]) txt = texts for z in re.findall("\\[.+?\\|.+?\\]", texts): txt = txt.replace(z, "") return txt.strip(), btn def format_btn(buttons: list): txt = "" for i in buttons: a = 0 for i in i: if hasattr(i.button, "url"): a += 1 if a > 1: txt += f"[{i.button.text} | {i.button.url} | same]" else: txt += f"[{i.button.text} | {i.button.url}]" _, btn = get_msg_button(txt) return btn async def ac(e): wrd = (e.pattern_match.group(1).strip()).lower() wt = await e.get_reply_message() if not (wt and wrd): return await e.eor(get_string("asstcmd_1"), time=5) if "/" in wrd: wrd = wrd.replace("/", "") btn = format_btn(wt.buttons) if wt.buttons else None if wt and wt.media: wut = mediainfo(wt.media) if wut.startswith(("pic", "gif")): dl = await e.client.download_media(wt.media) variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" elif wut == "video": if wt.media.document.size > 8 * 1000 * 1000: return await e.eor(get_string("com_4"), time=5) dl = await e.client.download_media(wt.media) variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" else: m = utils.pack_bot_file_id(wt.media) if wt.text: txt = wt.text if not btn: txt, btn = get_msg_button(wt.text) add_cmd(wrd, txt, m, btn) else: add_cmd(wrd, None, m, btn) else: txt = wt.text if not btn: txt, btn = get_msg_button(wt.text) add_cmd(wrd, txt, None, btn) asst.add_handler( astcmds, events.NewMessage( func=lambda x: x.text.startswith("/") and x.text[1:] in list(list_cmds()) ), ) await e.eor(get_string("asstcmd_4").format(wrd))
null
5,943
from . import get_help import os from pyUltroid.dB.asstcmd_db import add_cmd, cmd_reply, list_cmds, rem_cmd from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from telethon import events, utils from . import asst, get_string, mediainfo, udB, ultroid_cmd def rem_cmd(cmd): ok = get_stuff() if ok.get(cmd): ok.pop(cmd) return udB.set_key("ASST_CMDS", ok) async def rc(e): wrd = (e.pattern_match.group(1).strip()).lower() if not wrd: return await e.eor(get_string("asstcmd_2"), time=5) wrd = wrd.replace("/", "") rem_cmd(wrd) await e.eor(get_string("asstcmd_3").format(wrd))
null
5,944
from . import get_help import os from pyUltroid.dB.asstcmd_db import add_cmd, cmd_reply, list_cmds, rem_cmd from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from telethon import events, utils from . import asst, get_string, mediainfo, udB, ultroid_cmd def list_cmds(): ok = get_stuff() return ok.keys() async def lscmd(e): if list_cmds(): ok = get_string("asstcmd_6") for x in list_cmds(): ok += f"/{x}" + "\n" return await e.eor(ok) return await e.eor(get_string("asstcmd_5"))
null
5,945
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid._misc import sudoers from pyUltroid.dB.snips_db import add_snip, get_snips, list_snip, rem_snip from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import events, get_string, mediainfo, udB, ultroid_bot, ultroid_cmd from ._inline import something async def add_snips(e): if not e.out and e.sender_id not in sudoers(): return xx = [z.replace("$", "") for z in e.text.lower().split() if z.startswith("$")] for z in xx: if k := get_snips(z): msg = k["msg"] media = k["media"] rep = await e.get_reply_message() if rep: if k.get("button"): btn = create_tl_btn(k["button"]) return await something(rep, msg, media, btn) await rep.reply(msg, file=media) else: await e.delete() if k.get("button"): btn = create_tl_btn(k["button"]) return await something(e, msg, media, btn, reply=None) await ultroid_bot.send_message(e.chat_id, msg, file=media) def add_snip(word, msg, media, button): ok = get_all_snips() ok.update({word: {"msg": msg, "media": media, "button": button}}) udB.set_key("SNIP", ok) from .. import * def get_msg_button(texts: str): btn = [] for z in re.findall("\\[(.*?)\\|(.*?)\\]", texts): text, url = z urls = url.split("|") url = urls[0] if len(urls) > 1: btn[-1].append([text, url]) else: btn.append([[text, url]]) txt = texts for z in re.findall("\\[.+?\\|.+?\\]", texts): txt = txt.replace(z, "") return txt.strip(), btn def format_btn(buttons: list): txt = "" for i in buttons: a = 0 for i in i: if hasattr(i.button, "url"): a += 1 if a > 1: txt += f"[{i.button.text} | {i.button.url} | same]" else: txt += f"[{i.button.text} | {i.button.url}]" _, btn = get_msg_button(txt) return btn async def an(e): wrd = (e.pattern_match.group(1).strip()).lower() wt = await e.get_reply_message() if not (wt and wrd): return await e.eor(get_string("snip_1")) if "$" in wrd: wrd = wrd.replace("$", "") btn = format_btn(wt.buttons) if wt.buttons else None if wt and wt.media: wut = mediainfo(wt.media) if wut.startswith(("pic", "gif")): dl = await wt.download_media() variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" elif wut == "video": if wt.media.document.size > 8 * 1000 * 1000: return await e.eor(get_string("com_4"), time=5) dl = await wt.download_media() variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" else: m = pack_bot_file_id(wt.media) if wt.text: txt = wt.text if not btn: txt, btn = get_msg_button(wt.text) add_snip(wrd, txt, m, btn) else: add_snip(wrd, None, m, btn) else: txt = wt.text if not btn: txt, btn = get_msg_button(wt.text) add_snip(wrd, txt, None, btn) await e.eor(f"Done : snip `${wrd}` Saved.") ultroid_bot.add_handler(add_snips, events.NewMessage())
null
5,946
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid._misc import sudoers from pyUltroid.dB.snips_db import add_snip, get_snips, list_snip, rem_snip from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import events, get_string, mediainfo, udB, ultroid_bot, ultroid_cmd from ._inline import something def rem_snip(word): ok = get_all_snips() if ok.get(word): ok.pop(word) udB.set_key("SNIP", ok) async def rs(e): wrd = (e.pattern_match.group(1).strip()).lower() if not wrd: return await e.eor(get_string("snip_2")) if wrd.startswith("$"): wrd = wrd.replace("$", "") rem_snip(wrd) await e.eor(f"Done : snip `${wrd}` Removed.")
null
5,947
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid._misc import sudoers from pyUltroid.dB.snips_db import add_snip, get_snips, list_snip, rem_snip from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import events, get_string, mediainfo, udB, ultroid_bot, ultroid_cmd from ._inline import something def list_snip(): return "".join(f"👉 ${z}\n" for z in get_all_snips()) async def lsnote(e): if x := list_snip(): sd = "SNIPS Found :\n\n" return await e.eor(sd + x) await e.eor("No Snips Found Here")
null
5,948
import os import re from telethon.errors.rpcerrorlist import ( ChannelPrivateError, ChatWriteForbiddenError, MediaCaptionTooLongError, MediaEmptyError, MessageTooLongError, PeerIdInvalidError, UserNotParticipantError, ) from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User from telethon.utils import get_display_name from pyUltroid.dB.botchat_db import tag_add, who_tag from . import ( LOG_CHANNEL, LOGS, Button, asst, callback, events, get_string, inline_mention, udB, ultroid_bot, ) CACHE_SPAM = {} TAG_EDITS = {} if udB.get_key("TAG_LOG"): ) asst.add_event_handler( when_added_or_joined, events.ChatAction(func=lambda x: x.user_added) ) async def parse_buttons(event): y, x = event.chat, event.sender where_n, who_n = get_display_name(y), get_display_name(x) where_l = event.message_link buttons = [[Button.url(where_n, where_l)]] if isinstance(x, User) and x.username: try: buttons.append( [Button.mention(who_n, await asst.get_input_entity(x.username))] ) except Exception as er: LOGS.exception(er) buttons.append([Button.url(who_n, f"t.me/{x.username}")]) elif getattr(x, "username"): buttons.append([Button.url(who_n, f"t.me/{x.username}")]) else: buttons.append([Button.url(who_n, where_l)]) replied = await event.get_reply_message() if replied and replied.out: button = Button.url("Replied to", replied.message_link) if len(who_n) > 7: buttons.append([button]) else: buttons[-1].append(button) return buttons def tag_add(msg, chat, user): ok = get_stuff() if not ok.get("TAG"): ok.update({"TAG": {msg: [chat, user]}}) else: ok["TAG"].update({msg: [chat, user]}) return udB.set_key("BOTCHAT", ok) async def all_messages_catcher(e): x = await e.get_sender() if isinstance(x, User) and (x.bot or x.verified): return if not udB.get_key("TAG_LOG"): return NEEDTOLOG = udB.get_key("TAG_LOG") buttons = await parse_buttons(e) try: sent = await asst.send_message(NEEDTOLOG, e.message, buttons=buttons) if TAG_EDITS.get(e.chat_id): TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id, "msg": e}}) else: TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id, "msg": e}}}) tag_add(sent.id, e.chat_id, e.id) except MediaEmptyError as er: LOGS.debug(f"handling {er}.") try: msg = await asst.get_messages(e.chat_id, ids=e.id) sent = await asst.send_message(NEEDTOLOG, msg, buttons=buttons) if TAG_EDITS.get(e.chat_id): TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id, "msg": e}}) else: TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id, "msg": e}}}) tag_add(sent.id, e.chat_id, e.id) except Exception as me: if not isinstance(me, (PeerIdInvalidError, ValueError)): LOGS.exception(me) if e.photo or e.sticker or e.gif: try: media = await e.download_media() sent = await asst.send_message( NEEDTOLOG, e.message.text, file=media, buttons=buttons ) if TAG_EDITS.get(e.chat_id): TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id, "msg": e}}) else: TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id, "msg": e}}}) return os.remove(media) except Exception as er: LOGS.exception(er) await asst.send_message(NEEDTOLOG, get_string("com_4"), buttons=buttons) except (PeerIdInvalidError, ValueError) as er: LOGS.exception(er) try: CACHE_SPAM[NEEDTOLOG] except KeyError: await asst.send_message( udB.get_key("LOG_CHANNEL"), get_string("userlogs_1") ) CACHE_SPAM.update({NEEDTOLOG: True}) except ChatWriteForbiddenError: try: await asst.get_permissions(NEEDTOLOG, "me") MSG = get_string("userlogs_4") except UserNotParticipantError: MSG = get_string("userlogs_2") try: CACHE_SPAM[NEEDTOLOG] except KeyError: await asst.send_message(LOG_CHANNEL, MSG) CACHE_SPAM.update({NEEDTOLOG: True}) except Exception as er: LOGS.exception(er)
null
5,949
import os import re from telethon.errors.rpcerrorlist import ( ChannelPrivateError, ChatWriteForbiddenError, MediaCaptionTooLongError, MediaEmptyError, MessageTooLongError, PeerIdInvalidError, UserNotParticipantError, ) from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User from telethon.utils import get_display_name from pyUltroid.dB.botchat_db import tag_add, who_tag from . import ( LOG_CHANNEL, LOGS, Button, asst, callback, events, get_string, inline_mention, udB, ultroid_bot, ) TAG_EDITS = {} if udB.get_key("TAG_LOG"): ) asst.add_event_handler( when_added_or_joined, events.ChatAction(func=lambda x: x.user_added) ) async def parse_buttons(event): async def upd_edits(event): x = event.sender if isinstance(x, User) and (x.bot or x.verified): return if event.chat_id not in TAG_EDITS: if event.sender_id == udB.get_key("TAG_LOG"): return if event.is_private: return if entities := event.get_entities_text(): is_self = False username = event.client.me.username if username: username = username.lower() for ent, text in entities: if isinstance(ent, MessageEntityMention): is_self = text[1:].lower() == username elif isinstance(ent, MessageEntityMentionName): is_self = ent.user_id == event.client.me.id if is_self: text = f"**#Edited & #Mentioned**\n\n{event.text}" try: sent = await asst.send_message( udB.get_key("TAG_LOG"), text, buttons=await parse_buttons(event), ) except Exception as er: return LOGS.exception(er) if TAG_EDITS.get(event.chat_id): TAG_EDITS[event.chat_id].update({event.id: {"id": sent.id}}) else: TAG_EDITS.update({event.chat_id: {event.id: {"id": sent.id}}}) return d_ = TAG_EDITS[event.chat_id] if not d_.get(event.id): return d_ = d_[event.id] if d_["msg"].text == event.text: return msg = None if d_.get("count"): d_["count"] += 1 else: msg = True d_.update({"count": 1}) if d_["count"] > 10: return # some limit to take edits try: MSG = await asst.get_messages(udB.get_key("TAG_LOG"), ids=d_["id"]) except Exception as er: return LOGS.exception(er) TEXT = MSG.text if msg: TEXT += "\n\n🖋 **Later Edited to !**" strf = event.edit_date.strftime("%H:%M:%S") if "\n" not in event.text: TEXT += f"\n• `{strf}` : {event.text}" else: TEXT += f"\n• `{strf}` :\n-> {event.text}" if d_["count"] == 10: TEXT += "\n\n• __Only the first 10 Edits are shown.__" try: msg = await MSG.edit(TEXT, buttons=await parse_buttons(event)) d_["msg"] = msg except (MessageTooLongError, MediaCaptionTooLongError): del TAG_EDITS[event.chat_id][event.id] except Exception as er: LOGS.exception(er)
null
5,950
import os import re from telethon.errors.rpcerrorlist import ( ChannelPrivateError, ChatWriteForbiddenError, MediaCaptionTooLongError, MediaEmptyError, MessageTooLongError, PeerIdInvalidError, UserNotParticipantError, ) from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User from telethon.utils import get_display_name from pyUltroid.dB.botchat_db import tag_add, who_tag from . import ( LOG_CHANNEL, LOGS, Button, asst, callback, events, get_string, inline_mention, udB, ultroid_bot, ) ultroid_bot.add_event_handler( when_added_or_joined, events.ChatAction(func=lambda x: x.user_added or x.user_joined), ) def who_tag(msg): ok = get_stuff() if ok.get("TAG") and ok["TAG"].get(msg): return ok["TAG"][msg] return False, False async def idk(e): id = e.reply_to_msg_id chat, msg = who_tag(id) if chat and msg: try: await ultroid_bot.send_message(chat, e.message, reply_to=msg) except BaseException as er: LOGS.exception(er)
null
5,951
import os import re from telethon.errors.rpcerrorlist import ( ChannelPrivateError, ChatWriteForbiddenError, MediaCaptionTooLongError, MediaEmptyError, MessageTooLongError, PeerIdInvalidError, UserNotParticipantError, ) from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User from telethon.utils import get_display_name from pyUltroid.dB.botchat_db import tag_add, who_tag from . import ( LOG_CHANNEL, LOGS, Button, asst, callback, events, get_string, inline_mention, udB, ultroid_bot, ) if udB.get_key("TAG_LOG"): ) asst.add_event_handler( when_added_or_joined, events.ChatAction(func=lambda x: x.user_added) ) async def when_added_or_joined(event): user = await event.get_user() chat = await event.get_chat() if not (user and user.is_self): return if getattr(chat, "username", None): chat = f"[{chat.title}](https://t.me/{chat.username}/{event.action_message.id})" else: chat = f"[{chat.title}](https://t.me/c/{chat.id}/{event.action_message.id})" key = "bot" if event.client._bot else "user" buttons = Button.inline( get_string("userlogs_3"), data=f"leave_ch_{event.chat_id}|{key}" ) if event.user_added: tmp = event.added_by text = f"#ADD_LOG\n\n{inline_mention(tmp)} just added {inline_mention(user)} to {chat}." elif event.from_request: text = f"#APPROVAL_LOG\n\n{inline_mention(user)} just got Chat Join Approval to {chat}." else: text = f"#JOIN_LOG\n\n{inline_mention(user)} just joined {chat}." await asst.send_message(udB.get_key("LOG_CHANNEL"), text, buttons=buttons)
null
5,952
import os import re from telethon.errors.rpcerrorlist import ( ChannelPrivateError, ChatWriteForbiddenError, MediaCaptionTooLongError, MediaEmptyError, MessageTooLongError, PeerIdInvalidError, UserNotParticipantError, ) from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User from telethon.utils import get_display_name from pyUltroid.dB.botchat_db import tag_add, who_tag from . import ( LOG_CHANNEL, LOGS, Button, asst, callback, events, get_string, inline_mention, udB, ultroid_bot, ) _client = {"bot": asst, "user": ultroid_bot} async def leave_ch_at(event): cht = event.data_match.group(1).decode("UTF-8") ch_id, client = cht.split("|") try: client = _client[client] except KeyError: return try: name = (await client.get_entity(int(ch_id))).title await client.delete_dialog(int(ch_id)) except UserNotParticipantError: pass except ChannelPrivateError: return await event.edit( "`[CANT_ACCESS_CHAT]` `Maybe already left or got banned.`" ) except Exception as er: LOGS.exception(er) return await event.answer(str(er)) await event.edit(get_string("userlogs_5").format(name))
null
5,953
import os import re from telethon.errors.rpcerrorlist import ( ChannelPrivateError, ChatWriteForbiddenError, MediaCaptionTooLongError, MediaEmptyError, MessageTooLongError, PeerIdInvalidError, UserNotParticipantError, ) from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User from telethon.utils import get_display_name from pyUltroid.dB.botchat_db import tag_add, who_tag from . import ( LOG_CHANNEL, LOGS, Button, asst, callback, events, get_string, inline_mention, udB, ultroid_bot, ) async def _(event): await event.answer()
null
5,954
from pyUltroid.dB.nsfw_db import profan_chat, rem_profan from . import get_string, ultroid_cmd def profan_chat(chat, action): def rem_profan(chat): async def addp(e): cas = e.pattern_match.group(1) add = cas == "add" if add: profan_chat(e.chat_id, "mute") await e.eor(get_string("prof_1"), time=10) return rem_profan(e.chat_id) await e.eor(get_string("prof_2"), time=10)
null
5,955
from . import get_help import inspect import sys import traceback from io import BytesIO, StringIO from os import remove from pprint import pprint from telethon.utils import get_display_name from pyUltroid import _ignore_eval from . import * from random import choice from telethon.tl import functions async def _(e): xx = await e.eor(get_string("com_1")) x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt") if y and y.endswith("NOT_FOUND"): return await xx.edit(f"Error: `{y}`") with open("neo.txt", "r", encoding="utf-8") as neo: p = (neo.read()).replace("\n\n", "") haa = await Carbon(code=p, file_name="neofetch", backgroundColor=choice(ATRA_COL)) if isinstance(haa, dict): await xx.edit(f"`{haa}`") else: await e.reply(file=haa) await xx.delete() remove("neo.txt") async def _(event): carb, rayso, yamlf = None, None, False try: cmd = event.text.split(" ", maxsplit=1)[1] if cmd.split()[0] in ["-c", "--carbon"]: cmd = cmd.split(maxsplit=1)[1] carb = True if cmd.split()[0] in ["-r", "--rayso"]: cmd = cmd.split(maxsplit=1)[1] rayso = True except IndexError: return await event.eor(get_string("devs_1"), time=10) xx = await event.eor(get_string("com_1")) reply_to_id = event.reply_to_msg_id or event.id stdout, stderr = await bash(cmd, run_code=1) OUT = f"**☞ BASH\n\n• COMMAND:**\n`{cmd}` \n\n" err, out = "", "" if stderr: err = f"**• ERROR:** \n`{stderr}`\n\n" if stdout: if (carb or udB.get_key("CARBON_ON_BASH")) and ( event.is_private or event.chat.admin_rights or event.chat.creator or event.chat.default_banned_rights.embed_links ): li = await Carbon( code=stdout, file_name="bash", download=True, backgroundColor=choice(ATRA_COL), ) if isinstance(li, dict): await xx.edit( f"Unknown Response from Carbon: `{li}`\n\nstdout`:{stdout}`\nstderr: `{stderr}`" ) return url = f"https://graph.org{uf(li)[-1]}" OUT = f"[\xad]({url}){OUT}" out = "**• OUTPUT:**" remove(li) elif (rayso or udB.get_key("RAYSO_ON_BASH")) and ( event.is_private or event.chat.admin_rights or event.chat.creator or event.chat.default_banned_rights.embed_links ): li = await Carbon( code=stdout, file_name="bash", download=True, backgroundColor=choice(ATRA_COL), rayso=True, ) if isinstance(li, dict): await xx.edit( f"Unknown Response from Carbon: `{li}`\n\nstdout`:{stdout}`\nstderr: `{stderr}`" ) return url = f"https://graph.org{uf(li)[-1]}" OUT = f"[\xad]({url}){OUT}" out = "**• OUTPUT:**" remove(li) else: if "pip" in cmd and all(":" in line for line in stdout.split("\n")): try: load = safe_load(stdout) stdout = "" for data in list(load.keys()): res = load[data] or "" if res and "http" not in str(res): res = f"`{res}`" stdout += f"**{data}** : {res}\n" yamlf = True except Exception as er: stdout = f"`{stdout}`" LOGS.exception(er) else: stdout = f"`{stdout}`" out = f"**• OUTPUT:**\n{stdout}" if not stderr and not stdout: out = "**• OUTPUT:**\n`Success`" OUT += err + out if len(OUT) > 4096: ultd = err + out with BytesIO(str.encode(ultd)) as out_file: out_file.name = "bash.txt" await event.client.send_file( event.chat_id, out_file, force_document=True, thumb=ULTConfig.thumb, allow_cache=False, caption=f"`{cmd}`" if len(cmd) < 998 else None, reply_to=reply_to_id, ) await xx.delete() else: await xx.edit(OUT, link_preview=not yamlf) class u: _ = "" def _parse_eval(value=None): if not value: return value if hasattr(value, "stringify"): try: return value.stringify() except TypeError: pass elif isinstance(value, dict): try: return json_parser(value, indent=1) except BaseException: pass elif isinstance(value, list): newlist = "[" for index, child in enumerate(value): newlist += "\n " + str(_parse_eval(child)) if index < len(value) - 1: newlist += "," newlist += "\n]" return newlist return str(value) async def _(event): try: cmd = event.text.split(maxsplit=1)[1] except IndexError: return await event.eor(get_string("devs_2"), time=5) xx = None mode = "" spli = cmd.split() async def get_(): try: cm = cmd.split(maxsplit=1)[1] except IndexError: await event.eor("->> Wrong Format <<-") cm = None return cm if spli[0] in ["-s", "--silent"]: await event.delete() mode = "silent" elif spli[0] in ["-n", "-noedit"]: mode = "no-edit" xx = await event.reply(get_string("com_1")) elif spli[0] in ["-gs", "--source"]: mode = "gsource" elif spli[0] in ["-ga", "--args"]: mode = "g-args" if mode: cmd = await get_() if not cmd: return if not mode == "silent" and not xx: xx = await event.eor(get_string("com_1")) if black: try: cmd = black.format_str(cmd, mode=black.Mode()) except BaseException: # Consider it as Code Error, and move on to be shown ahead. pass reply_to_id = event.reply_to_msg_id or event if any(item in cmd for item in KEEP_SAFE().All) and ( not (event.out or event.sender_id == ultroid_bot.uid) ): warning = await event.forward_to(udB.get_key("LOG_CHANNEL")) await warning.reply( f"Malicious Activities suspected by {inline_mention(await event.get_sender())}" ) _ignore_eval.append(event.sender_id) return await xx.edit( "`Malicious Activities suspected⚠️!\nReported to owner. Aborted this request!`" ) old_stderr = sys.stderr old_stdout = sys.stdout redirected_output = sys.stdout = StringIO() redirected_error = sys.stderr = StringIO() stdout, stderr, exc, timeg = None, None, None, None tima = time.time() try: value = await aexec(cmd, event) except Exception: value = None exc = traceback.format_exc() tima = time.time() - tima stdout = redirected_output.getvalue() stderr = redirected_error.getvalue() sys.stdout = old_stdout sys.stderr = old_stderr if value: try: if mode == "gsource": exc = inspect.getsource(value) elif mode == "g-args": args = inspect.signature(value).parameters.values() name = "" if hasattr(value, "__name__"): name = value.__name__ exc = f"**{name}**\n\n" + "\n ".join([str(arg) for arg in args]) except Exception: exc = traceback.format_exc() evaluation = exc or stderr or stdout or _parse_eval(value) or get_string("instu_4") if mode == "silent": if exc: msg = f"• <b>EVAL ERROR\n\n• CHAT:</b> <code>{get_display_name(event.chat)}</code> [<code>{event.chat_id}</code>]" msg += f"\n\n∆ <b>CODE:</b>\n<code>{cmd}</code>\n\n∆ <b>ERROR:</b>\n<code>{exc}</code>" log_chat = udB.get_key("LOG_CHANNEL") if len(msg) > 4000: with BytesIO(msg.encode()) as out_file: out_file.name = "Eval-Error.txt" return await event.client.send_message( log_chat, f"`{cmd}`", file=out_file ) await event.client.send_message(log_chat, msg, parse_mode="html") return tmt = tima * 1000 timef = time_formatter(tmt) timeform = timef if not timef == "0s" else f"{tmt:.3f}ms" final_output = "__►__ **EVAL** (__in {}__)\n```{}``` \n\n __►__ **OUTPUT**: \n```{}``` \n".format( timeform, cmd, evaluation, ) if len(final_output) > 4096: final_output = evaluation with BytesIO(str.encode(final_output)) as out_file: out_file.name = "eval.txt" await event.client.send_file( event.chat_id, out_file, force_document=True, thumb=ULTConfig.thumb, allow_cache=False, caption=f"```{cmd}```" if len(cmd) < 998 else None, reply_to=reply_to_id, ) return await xx.delete() await xx.edit(final_output) def _stringify(text=None, *args, **kwargs): if text: u._ = text text = _parse_eval(text) return print(text, *args, **kwargs)
null
5,956
from . import get_help import inspect import sys import traceback from io import BytesIO, StringIO from os import remove from pprint import pprint from telethon.utils import get_display_name from pyUltroid import _ignore_eval from . import * from random import choice from telethon.tl import functions DUMMY_CPP = """#include <iostream> using namespace std; int main(){ !code } """ async def doie(e): match = e.text.split(" ", maxsplit=1) try: match = match[1] except IndexError: return await e.eor(get_string("devs_3")) msg = await e.eor(get_string("com_1")) if "main(" not in match: new_m = "".join(" " * 4 + i + "\n" for i in match.split("\n")) match = DUMMY_CPP.replace("!code", new_m) open("cpp-ultroid.cpp", "w").write(match) m = await bash("g++ -o CppUltroid cpp-ultroid.cpp") o_cpp = f"• **Eval-Cpp**\n`{match}`" if m[1]: o_cpp += f"\n\n**• Error :**\n`{m[1]}`" if len(o_cpp) > 3000: os.remove("cpp-ultroid.cpp") if os.path.exists("CppUltroid"): os.remove("CppUltroid") with BytesIO(str.encode(o_cpp)) as out_file: out_file.name = "error.txt" return await msg.reply(f"`{match}`", file=out_file) return await eor(msg, o_cpp) m = await bash("./CppUltroid") if m[0] != "": o_cpp += f"\n\n**• Output :**\n`{m[0]}`" if m[1]: o_cpp += f"\n\n**• Error :**\n`{m[1]}`" if len(o_cpp) > 3000: with BytesIO(str.encode(o_cpp)) as out_file: out_file.name = "eval.txt" await msg.reply(f"`{match}`", file=out_file) else: await eor(msg, o_cpp) os.remove("CppUltroid") os.remove("cpp-ultroid.cpp")
null
5,957
from . import get_help import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.fns.tools import create_tl_btn, get_msg_button from . import HNDLR, get_string, mediainfo, ultroid_cmd from ._inline import something from .. import * def get_msg_button(texts: str): btn = [] for z in re.findall("\\[(.*?)\\|(.*?)\\]", texts): text, url = z urls = url.split("|") url = urls[0] if len(urls) > 1: btn[-1].append([text, url]) else: btn.append([[text, url]]) txt = texts for z in re.findall("\\[.+?\\|.+?\\]", texts): txt = txt.replace(z, "") return txt.strip(), btn def create_tl_btn(button: list): btn = [] for z in button: if len(z) > 1: kk = [Button.url(x, y.strip()) for x, y in z] btn.append(kk) else: btn.append([Button.url(z[0][0], z[0][1].strip())]) return btn async def something(e, msg, media, button, reply=True, chat=None): if e.client._bot: return await e.reply(msg, file=media, buttons=button) num = len(STUFF) + 1 STUFF.update({num: {"msg": msg, "media": media, "button": button}}) try: res = await e.client.inline_query(asst.me.username, f"stf{num}") return await res[0].click( chat or e.chat_id, reply_to=bool(isinstance(e, Message) and reply), hide_via=True, silent=True, ) except Exception as er: LOGS.exception(er) async def butt(event): media, wut, text = None, None, None if event.reply_to: wt = await event.get_reply_message() if wt.text: text = wt.text if wt.media: wut = mediainfo(wt.media) if wut and wut.startswith(("pic", "gif")): dl = await wt.download_media() variable = uf(dl) media = f"https://graph.org{variable[0]}" elif wut == "video": if wt.media.document.size > 8 * 1000 * 1000: return await event.eor(get_string("com_4"), time=5) dl = await wt.download_media() variable = uf(dl) os.remove(dl) media = f"https://graph.org{variable[0]}" else: media = pack_bot_file_id(wt.media) try: text = event.text.split(maxsplit=1)[1] except IndexError: if not text: return await event.eor( f"**Please give some text in correct format.**\n\n`{HNDLR}help button`", ) text, buttons = get_msg_button(text) if buttons: buttons = create_tl_btn(buttons) await something(event, text, media, buttons) await event.delete()
null
5,958
import os import requests from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeAudio from pyUltroid.fns.misc import google_search from pyUltroid.fns.tools import get_google_images, saavn_search from . import LOGS, async_searcher, con, eod, fast_download, get_string, ultroid_cmd async def gitsearch(event): usrname = event.pattern_match.group(1).strip() if not usrname: return await event.eor(get_string("srch_1")) url = f"https://api.github.com/users/{usrname}" ult = await async_searcher(url, re_json=True) try: uname = ult["login"] uid = ult["id"] upic = f"https://avatars.githubusercontent.com/u/{uid}" ulink = ult["html_url"] uacc = ult["name"] ucomp = ult["company"] ublog = ult["blog"] ulocation = ult["location"] ubio = ult["bio"] urepos = ult["public_repos"] ufollowers = ult["followers"] ufollowing = ult["following"] except BaseException: return await event.eor(get_string("srch_2")) fullusr = f""" **[GITHUB]({ulink})** **Name** - {uacc} **UserName** - {uname} **ID** - {uid} **Company** - {ucomp} **Blog** - {ublog} **Location** - {ulocation} **Bio** - {ubio} **Repos** - {urepos} **Followers** - {ufollowers} **Following** - {ufollowing} """ await event.respond(fullusr, file=upic) await event.delete()
null
5,959
import os import requests from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeAudio from pyUltroid.fns.misc import google_search from pyUltroid.fns.tools import get_google_images, saavn_search from . import LOGS, async_searcher, con, eod, fast_download, get_string, ultroid_cmd from .. import * async def google_search(query): query = query.replace(" ", "+") _base = "https://google.com" headers = { "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": choice(some_random_headers), } con = await async_searcher(_base + "/search?q=" + query, headers=headers) soup = BeautifulSoup(con, "html.parser") result = [] pdata = soup.find_all("a", href=re.compile("url=")) for data in pdata: if not data.find("div"): continue try: result.append( { "title": data.find("div").text, "link": data["href"].split("&url=")[1].split("&ved=")[0], "description": data.find_all("div")[-1].text, } ) except BaseException as er: LOGS.exception(er) return result async def google(event): inp = event.pattern_match.group(1).strip() if not inp: return await eod(event, get_string("autopic_1")) x = await event.eor(get_string("com_2")) gs = await google_search(inp) if not gs: return await eod(x, get_string("autopic_2").format(inp)) out = "" for res in gs: text = res["title"] url = res["link"] des = res["description"] out += f" 👉🏻 [{text}]({url})\n`{des}`\n\n" omk = f"**Google Search Query:**\n`{inp}`\n\n**Results:**\n{out}" await x.eor(omk, link_preview=False)
null
5,960
import os import requests from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeAudio from pyUltroid.fns.misc import google_search from pyUltroid.fns.tools import get_google_images, saavn_search from . import LOGS, async_searcher, con, eod, fast_download, get_string, ultroid_cmd from .. import * async def get_google_images(query): soup = BeautifulSoup( await async_searcher( "https://google.com/search", params={"q": query, "tbm": "isch"}, headers={"User-Agent": random.choice(some_random_headers)}, ), "lxml", ) google_images = [] all_script_tags = soup.select("script") matched_images_data = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);", str(all_script_tags)) ) matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_image_data = re.findall( r"\"b-GRID_STATE0\"(.*)sideChannel:\s?{}}", matched_images_data_json ) matched_google_images_thumbnails = ", ".join( re.findall( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", str(matched_google_image_data), ) ).split(", ") thumbnails = [ bytes(bytes(thumbnail, "ascii").decode("unicode-escape"), "ascii").decode( "unicode-escape" ) for thumbnail in matched_google_images_thumbnails ] removed_matched_google_images_thumbnails = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", "", str(matched_google_image_data), ) matched_google_full_resolution_images = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails, ) full_res_images = [ bytes(bytes(img, "ascii").decode("unicode-escape"), "ascii").decode( "unicode-escape" ) for img in matched_google_full_resolution_images ] for index, (metadata, thumbnail, original) in enumerate( zip(soup.select(".isv-r.PNCib.MSM1fd.BUooTd"), thumbnails, full_res_images), start=1, ): google_images.append( { "title": metadata.select_one(".VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb")[ "title" ], "link": metadata.select_one(".VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb")[ "href" ], "source": metadata.select_one(".fxgdke").text, "thumbnail": thumbnail, "original": original, } ) random.shuffle(google_images) return google_images async def goimg(event): query = event.pattern_match.group(1).strip() if not query: return await event.eor(get_string("autopic_1")) nn = await event.eor(get_string("com_1")) lmt = 5 if ";" in query: try: lmt = int(query.split(";")[1]) query = query.split(";")[0] except BaseException: pass images = await get_google_images(query) for img in images[:lmt]: try: await event.client.send_file(event.chat_id, file=img["original"]) except Exception as er: LOGS.exception(er) await nn.delete()
null
5,961
import os import requests from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeAudio from pyUltroid.fns.misc import google_search from pyUltroid.fns.tools import get_google_images, saavn_search from . import LOGS, async_searcher, con, eod, fast_download, get_string, ultroid_cmd from .. import * async def get_google_images(query): soup = BeautifulSoup( await async_searcher( "https://google.com/search", params={"q": query, "tbm": "isch"}, headers={"User-Agent": random.choice(some_random_headers)}, ), "lxml", ) google_images = [] all_script_tags = soup.select("script") matched_images_data = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);", str(all_script_tags)) ) matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_image_data = re.findall( r"\"b-GRID_STATE0\"(.*)sideChannel:\s?{}}", matched_images_data_json ) matched_google_images_thumbnails = ", ".join( re.findall( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", str(matched_google_image_data), ) ).split(", ") thumbnails = [ bytes(bytes(thumbnail, "ascii").decode("unicode-escape"), "ascii").decode( "unicode-escape" ) for thumbnail in matched_google_images_thumbnails ] removed_matched_google_images_thumbnails = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", "", str(matched_google_image_data), ) matched_google_full_resolution_images = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails, ) full_res_images = [ bytes(bytes(img, "ascii").decode("unicode-escape"), "ascii").decode( "unicode-escape" ) for img in matched_google_full_resolution_images ] for index, (metadata, thumbnail, original) in enumerate( zip(soup.select(".isv-r.PNCib.MSM1fd.BUooTd"), thumbnails, full_res_images), start=1, ): google_images.append( { "title": metadata.select_one(".VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb")[ "title" ], "link": metadata.select_one(".VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb")[ "href" ], "source": metadata.select_one(".fxgdke").text, "thumbnail": thumbnail, "original": original, } ) random.shuffle(google_images) return google_images async def reverse(event): reply = await event.get_reply_message() if not reply: return await event.eor("`Reply to an Image`") ult = await event.eor(get_string("com_1")) dl = await reply.download_media() file = await con.convert(dl, convert_to="png") img = Image.open(file) x, y = img.size files = {"encoded_image": (file, open(file, "rb"))} grs = requests.post( "https://www.google.com/searchbyimage/upload", files=files, allow_redirects=False, ) loc = grs.headers.get("Location") response = await async_searcher( loc, headers={ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0", }, ) xx = bs(response, "html.parser") div = xx.find_all("div", {"class": "r5a77d"})[0] alls = div.find("a") link = alls["href"] text = alls.text await ult.edit(f"`Dimension ~ {x} : {y}`\nSauce ~ [{text}](google.com{link})") images = await get_google_images(text) for z in images[:2]: try: await event.client.send_file( event.chat_id, file=z["original"], caption="Similar Images Realted to Search", ) except Exception as er: LOGS.exception(er) os.remove(file)
null
5,962
import os import requests from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeAudio from pyUltroid.fns.misc import google_search from pyUltroid.fns.tools import get_google_images, saavn_search from . import LOGS, async_searcher, con, eod, fast_download, get_string, ultroid_cmd from .. import * async def saavn_search(query: str): async def siesace(e): song = e.pattern_match.group(1).strip() if not song: return await e.eor("`Give me Something to Search", time=5) eve = await e.eor(f"`Searching for {song} on Saavn...`") try: data = (await saavn_search(song))[0] except IndexError: return await eve.eor(f"`{song} not found on saavn.`") try: title = data["title"] url = data["url"] img = data["image"] duration = data["duration"] performer = data["artists"] except KeyError: return await eve.eor("`Something went wrong.`") song, _ = await fast_download(url, filename=f"{title}.m4a") thumb, _ = await fast_download(img, filename=f"{title}.jpg") song, _ = await e.client.fast_uploader(song, to_delete=True) await eve.eor( file=song, text=f"`{title}`\n`From Saavn`", attributes=[ DocumentAttributeAudio( duration=int(duration), title=title, performer=performer, ) ], supports_streaming=True, thumb=thumb, ) await eve.delete() os.remove(thumb)
null
5,963
from PIL import Image from . import HNDLR, eor, get_string, os, ultroid_cmd async def size(e): r = await e.get_reply_message() if not (r and r.media): return await e.eor(get_string("ascii_1")) k = await e.eor(get_string("com_1")) if hasattr(r.media, "document"): img = await e.client.download_media(r, thumb=-1) else: img = await r.download_media() im = Image.open(img) x, y = im.size await k.edit(f"Dimension Of This Image Is\n`{x} x {y}`") os.remove(img)
null
5,964
from PIL import Image from . import HNDLR, eor, get_string, os, ultroid_cmd async def resize(e): r = await e.get_reply_message() if not (r and r.media): return await e.eor(get_string("ascii_1")) sz = e.pattern_match.group(1).strip() if not sz: return await eor( f"Give Some Size To Resize, Like `{HNDLR}resize 720 1080` ", time=5 ) k = await e.eor(get_string("com_1")) if hasattr(r.media, "document"): img = await e.client.download_media(r, thumb=-1) else: img = await r.download_media() sz = sz.split() if len(sz) != 2: return await eor( k, f"Give Some Size To Resize, Like `{HNDLR}resize 720 1080` ", time=5 ) x, y = int(sz[0]), int(sz[1]) im = Image.open(img) ok = im.resize((x, y)) ok.save(img, format="PNG", optimize=True) await e.reply(file=img) os.remove(img) await k.delete()
null
5,965
import os from datetime import datetime as dt from bs4 import BeautifulSoup as bs from . import async_searcher, get_random_user_data, get_string, re, ultroid_cmd async def diela(e): m = await e.eor(get_string("com_1")) li = "https://daysoftheyear.com" te = "🎊 **Events of the Day**\n\n" da = dt.now() month = da.strftime("%b") li += f"/days/{month}/" + da.strftime("%F").split("-")[2] ct = await async_searcher(li, re_content=True) bt = bs(ct, "html.parser", from_encoding="utf-8") ml = bt.find_all("a", "js-link-target", href=re.compile("daysoftheyear.com/days")) for eve in ml[:5]: te += f'• [{eve.text}]({eve["href"]})\n' await m.edit(te, link_preview=False)
null
5,966
import os from datetime import datetime as dt from bs4 import BeautifulSoup as bs from . import async_searcher, get_random_user_data, get_string, re, ultroid_cmd async def pinterest(e): m = e.pattern_match.group(1).strip() if not m: return await e.eor("`Give pinterest link.`", time=3) soup = await async_searcher( "https://www.expertstool.com/download-pinterest-video/", data={"url": m}, post=True, ) try: _soup = bs(soup, "html.parser").find("table").tbody.find_all("tr") except BaseException: return await e.eor("`Wrong link or private pin.`", time=5) file = _soup[1] if len(_soup) > 1 else _soup[0] file = file.td.a["href"] await e.client.send_file(e.chat_id, file, caption=f"Pin:- {m}")
null
5,967
import os from datetime import datetime as dt from bs4 import BeautifulSoup as bs from . import async_searcher, get_random_user_data, get_string, re, ultroid_cmd async def mobs(e): mat = e.pattern_match.group(1).strip() if not mat: await e.eor("Please Give a Mobile Name to look for.") query = mat.replace(" ", "%20") jwala = f"https://gadgets.ndtv.com/search?searchtext={query}" c = await async_searcher(jwala) b = bs(c, "html.parser", from_encoding="utf-8") co = b.find_all("div", "rvw-imgbox") if not co: return await e.eor("No Results Found!") bt = await e.eor(get_string("com_1")) out = "**📱 Mobile / Gadgets Search**\n\n" li = co[0].find("a") imu, title = None, li.find("img")["title"] cont = await async_searcher(li["href"]) nu = bs(cont, "html.parser", from_encoding="utf-8") req = nu.find_all("div", "_pdsd") imu = nu.find_all( "img", src=re.compile("https://i.gadgets360cdn.com/products/large/") ) if imu: imu = imu[0]["src"].split("?")[0] + "?downsize=*:420&output-quality=80" out += f"☑️ **[{title}]({li['href']})**\n\n" for fp in req: ty = fp.findNext() out += f"- **{ty.text}** - `{ty.findNext().text}`\n" out += "_" if imu == []: imu = None await e.reply(out, file=imu, link_preview=False) await bt.delete()
null
5,968
import os from datetime import datetime as dt from bs4 import BeautifulSoup as bs from . import async_searcher, get_random_user_data, get_string, re, ultroid_cmd async def _gen_data(event): x = await event.eor(get_string("com_1")) msg, pic = await get_random_user_data() await event.reply(file=pic, message=msg) await x.delete()
null
5,969
import os from datetime import datetime as dt from bs4 import BeautifulSoup as bs from . import async_searcher, get_random_user_data, get_string, re, ultroid_cmd async def _(e): if not Img2HTMLConverter: return await e.eor("'img2html-converter' not installed!") if not e.reply_to_msg_id: return await e.eor(get_string("ascii_1")) m = await e.eor(get_string("ascii_2")) img = await (await e.get_reply_message()).download_media() char = e.pattern_match.group(1).strip() or "■" converter = Img2HTMLConverter(char=char) html = converter.convert(img) shot = WebShot(quality=85) pic = await shot.create_pic_async(html=html) await m.delete() await e.reply(file=pic) os.remove(pic) os.remove(img)
null
5,970
from telethon.tl.types import ChannelParticipantAdmin as admin from telethon.tl.types import ChannelParticipantCreator as owner from telethon.tl.types import UserStatusOffline as off from telethon.tl.types import UserStatusOnline as onn from telethon.tl.types import UserStatusRecently as rec from . import inline_mention, ultroid_cmd async def _(e): okk = e.text lll = e.pattern_match.group(2) o = 0 nn = 0 rece = 0 xx = f"{lll}" if lll else "" lili = await e.client.get_participants(e.chat_id, limit=99) for bb in lili: x = bb.status y = bb.participant if isinstance(x, onn): o += 1 if "on" in okk: xx += f"\n{inline_mention(bb)}" elif isinstance(x, off): nn += 1 if "off" in okk and not bb.bot and not bb.deleted: xx += f"\n{inline_mention(bb)}" elif isinstance(x, rec): rece += 1 if "rec" in okk and not bb.bot and not bb.deleted: xx += f"\n{inline_mention(bb)}" if isinstance(y, owner): xx += f"\n꧁{inline_mention(bb)}꧂" if isinstance(y, admin) and "admin" in okk and not bb.deleted: xx += f"\n{inline_mention(bb)}" if "all" in okk and not bb.bot and not bb.deleted: xx += f"\n{inline_mention(bb)}" if "bot" in okk and bb.bot: xx += f"\n{inline_mention(bb)}" await e.eor(xx)
null
5,971
import os import time from telethon.tl.types import Message from pyUltroid.fns.gDrive import GDriveManager from pyUltroid.fns.helper import time_formatter from . import ULTConfig, asst, eod, eor, get_string, ultroid_cmd class GDriveManager: def __init__(self): self._flow = {} self.gdrive_creds = { "oauth_scope": [ "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive.metadata", ], "dir_mimetype": "application/vnd.google-apps.folder", "redirect_uri": OOB_CALLBACK_URN, } self.auth_token = udB.get_key("GDRIVE_AUTH_TOKEN") self.folder_id = udB.get_key("GDRIVE_FOLDER_ID") self.token_file = "resources/auth/gdrive_creds.json" def _create_download_link(fileId: str): return f"https://drive.google.com/uc?id={fileId}&export=download" def _create_folder_link(folderId: str): return f"https://drive.google.com/folderview?id={folderId}" def _create_token_file(self, code: str = None): if code and self._flow: _auth_flow = self._flow["_"] credentials = _auth_flow.step2_exchange(code) Storage(self.token_file).put(credentials) return udB.set_key("GDRIVE_AUTH_TOKEN", str(open(self.token_file).read())) try: _auth_flow = OAuth2WebServerFlow( udB.get_key("GDRIVE_CLIENT_ID") or "458306970678-jhfbv6o5sf1ar63o1ohp4c0grblp8qba.apps.googleusercontent.com", udB.get_key("GDRIVE_CLIENT_SECRET") or "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", self.gdrive_creds["oauth_scope"], redirect_uri=self.gdrive_creds["redirect_uri"], ) self._flow["_"] = _auth_flow except KeyError: return "Fill GDRIVE client credentials" return _auth_flow.step1_get_authorize_url() def _http(self): storage = Storage(self.token_file) creds = storage.get() http = Http() http.redirect_codes = http.redirect_codes - {308} creds.refresh(http) return creds.authorize(http) def _build(self): return build("drive", "v2", http=self._http, cache_discovery=False) def _set_permissions(self, fileId: str): _permissions = { "role": "reader", "type": "anyone", "value": None, "withLink": True, } self._build.permissions().insert( fileId=fileId, body=_permissions, supportsAllDrives=True ).execute(http=self._http) async def _upload_file( self, event, path: str, filename: str = None, folder_id: str = None ): last_txt = "" if not filename: filename = path.split("/")[-1] mime_type = guess_type(path)[0] or "application/octet-stream" media_body = MediaFileUpload(path, mimetype=mime_type, resumable=True) body = { "title": filename, "description": "Uploaded using Ultroid Userbot", "mimeType": mime_type, } if folder_id: body["parents"] = [{"id": folder_id}] elif self.folder_id: body["parents"] = [{"id": self.folder_id}] upload = self._build.files().insert( body=body, media_body=media_body, supportsAllDrives=True ) start = time.time() _status = None while not _status: _progress, _status = upload.next_chunk(num_retries=3) if _progress: diff = time.time() - start completed = _progress.resumable_progress total_size = _progress.total_size percentage = round((completed / total_size) * 100, 2) speed = round(completed / diff, 2) eta = round((total_size - completed) / speed, 2) * 1000 crnt_txt = ( f"`Uploading {filename} to GDrive...\n\n" + f"Status: {humanbytes(completed)}/{humanbytes(total_size)} »» {percentage}%\n" + f"Speed: {humanbytes(speed)}/s\n" + f"ETA: {time_formatter(eta)}`" ) if round((diff % 10.00) == 0) or last_txt != crnt_txt: await event.edit(crnt_txt) last_txt = crnt_txt fileId = _status.get("id") try: self._set_permissions(fileId=fileId) except BaseException: pass _url = self._build.files().get(fileId=fileId, supportsAllDrives=True).execute() return _url.get("webContentLink") async def _download_file(self, event, fileId: str, filename: str = None): last_txt = "" if fileId.startswith("http"): if "=download" in fileId: fileId = fileId.split("=")[1][:-7] elif "/view" in fileId: fileId = fileId.split("/")[::-1][1] try: if not filename: filename = ( self._build.files() .get(fileId=fileId, supportsAllDrives=True) .execute()["title"] ) downloader = self._build.files().get_media( fileId=fileId, supportsAllDrives=True ) except Exception as ex: return False, str(ex) with FileIO(filename, "wb") as file: start = time.time() download = MediaIoBaseDownload(file, downloader) _status = None while not _status: _progress, _status = download.next_chunk(num_retries=3) if _progress: diff = time.time() - start completed = _progress.resumable_progress total_size = _progress.total_size percentage = round((completed / total_size) * 100, 2) speed = round(completed / diff, 2) eta = round((total_size - completed) / speed, 2) * 1000 crnt_txt = ( f"`Downloading {filename} from GDrive...\n\n" + f"Status: {humanbytes(completed)}/{humanbytes(total_size)} »» {percentage}%\n" + f"Speed: {humanbytes(speed)}/s\n" + f"ETA: {time_formatter(eta)}`" ) if round((diff % 10.00) == 0) or last_txt != crnt_txt: await event.edit(crnt_txt) last_txt = crnt_txt return True, filename def _list_files(self): _items = ( self._build.files() .list( supportsTeamDrives=True, includeTeamDriveItems=True, spaces="drive", fields="nextPageToken, items(id, title, mimeType)", pageToken=None, ) .execute() ) _files = {} for files in _items["items"]: if files["mimeType"] == self.gdrive_creds["dir_mimetype"]: _files[self._create_folder_link(files["id"])] = files["title"] else: _files[self._create_download_link(files["id"])] = files["title"] return _files def create_directory(self, directory): body = { "title": directory, "mimeType": self.gdrive_creds["dir_mimetype"], } if self.folder_id: body["parents"] = [{"id": self.folder_id}] file = self._build.files().insert(body=body, supportsAllDrives=True).execute() fileId = file.get("id") self._set_permissions(fileId=fileId) return fileId def search(self, title): query = f"title contains '{title}'" if self.folder_id: query = f"'{self.folder_id}' in parents and (title contains '{title}')" _items = ( self._build.files() .list( supportsTeamDrives=True, includeTeamDriveItems=True, q=query, spaces="drive", fields="nextPageToken, items(id, title, mimeType)", pageToken=None, ) .execute() ) _files = {} for files in _items["items"]: _files[self._create_download_link(files["id"])] = files["title"] return _files from . import * def time_formatter(milliseconds): minutes, seconds = divmod(int(milliseconds / 1000), 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) weeks, days = divmod(days, 7) tmp = ( ((str(weeks) + "w:") if weeks else "") + ((str(days) + "d:") if days else "") + ((str(hours) + "h:") if hours else "") + ((str(minutes) + "m:") if minutes else "") + ((str(seconds) + "s") if seconds else "") ) if not tmp: return "0s" if tmp.endswith(":"): return tmp[:-1] return tmp async def gdown(event): GDrive = GDriveManager() match = event.pattern_match.group(1).strip() if not match: return await eod(event, "`Give file id or Gdrive link to download from!`") filename = match.split(" | ")[1].strip() if " | " in match else None eve = await event.eor(get_string("com_1")) _start = time.time() status, response = await GDrive._download_file(eve, match, filename) if not status: return await eve.edit(response) await eve.edit( f"`Downloaded ``{response}`` in {time_formatter((time.time() - _start)*1000)}`" )
null
5,972
import os import random import time from datetime import datetime as dt from . import HNDLR, LOGS, bash, downloader, get_string, mediainfo, ultroid_cmd async def igif(e): match = e.pattern_match.group(1).strip() a = await e.get_reply_message() if not (a and a.media): return await e.eor("`Reply To gif only`", time=5) wut = mediainfo(a.media) if "gif" not in wut: return await e.eor("`Reply To Gif Only`", time=5) xx = await e.eor(get_string("com_1")) z = await a.download_media() if match == "bw": cmd = f'ffmpeg -i "{z}" -vf format=gray ult.gif -y' else: cmd = f'ffmpeg -i "{z}" -vf lutyuv="y=negval:u=negval:v=negval" ult.gif -y' try: await bash(cmd) await e.client.send_file(e.chat_id, "ult.gif", supports_streaming=True) os.remove(z) os.remove("ult.gif") await xx.delete() except Exception as er: LOGS.info(er)
null
5,973
import os import random import time from datetime import datetime as dt from . import HNDLR, LOGS, bash, downloader, get_string, mediainfo, ultroid_cmd async def reverse_gif(event): a = await event.get_reply_message() if not (a and a.media) and "video" not in mediainfo(a.media): return await event.eor("`Reply To Video only`", time=5) msg = await event.eor(get_string("com_1")) file = await a.download_media() await bash(f'ffmpeg -i "{file}" -vf reverse -af areverse reversed.mp4 -y') await event.respond("- **Reversed Video/GIF**", file="reversed.mp4") await msg.delete() os.remove(file) os.remove("reversed.mp4")
null
5,974
import os import random import time from datetime import datetime as dt from . import HNDLR, LOGS, bash, downloader, get_string, mediainfo, ultroid_cmd async def gifs(ult): get = ult.pattern_match.group(1).strip() xx = random.randint(0, 5) n = 0 if ";" in get: try: n = int(get.split(";")[-1]) except IndexError: pass if not get: return await ult.eor(f"`{HNDLR}gif <query>`") m = await ult.eor(get_string("com_2")) gifs = await ult.client.inline_query("gif", get) if not n: await gifs[xx].click( ult.chat_id, reply_to=ult.reply_to_msg_id, silent=True, hide_via=True ) else: for x in range(n): await gifs[x].click( ult.chat_id, reply_to=ult.reply_to_msg_id, silent=True, hide_via=True ) await m.delete()
null
5,975
import os import random import time from datetime import datetime as dt from . import HNDLR, LOGS, bash, downloader, get_string, mediainfo, ultroid_cmd async def vtogif(e): a = await e.get_reply_message() if not (a and a.media): return await e.eor("`Reply To video only`", time=5) wut = mediainfo(a.media) if "video" not in wut: return await e.eor("`Reply To Video Only`", time=5) xx = await e.eor(get_string("com_1")) dur = a.media.document.attributes[0].duration tt = time.time() if int(dur) < 120: z = await a.download_media() await bash( f'ffmpeg -i {z} -vf "fps=10,scale=320:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 ult.gif -y' ) else: filename = a.file.name if not filename: filename = "video_" + dt.now().isoformat("_", "seconds") + ".mp4" vid = await downloader(filename, a.media.document, xx, tt, get_string("com_5")) z = vid.name await bash( f'ffmpeg -ss 3 -t 100 -i {z} -vf "fps=10,scale=320:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 ult.gif' ) await e.client.send_file(e.chat_id, "ult.gif", support_stream=True) os.remove(z) os.remove("ult.gif") await xx.delete()
null
5,976
import math import shutil from random import choice from pyUltroid.fns import some_random_headers from . import ( HOSTED_ON, LOGS, Var, async_searcher, get_string, humanbytes, udB, ultroid_cmd, ) def simple_usage(): try: import psutil except ImportError: return "Install 'psutil' to use this..." total, used, free = shutil.disk_usage(".") cpuUsage = psutil.cpu_percent() memory = psutil.virtual_memory().percent disk = psutil.disk_usage("/").percent upload = humanbytes(psutil.net_io_counters().bytes_sent) down = humanbytes(psutil.net_io_counters().bytes_recv) TOTAL = humanbytes(total) USED = humanbytes(used) FREE = humanbytes(free) return get_string("usage_simple").format( TOTAL, USED, FREE, upload, down, cpuUsage, memory, disk, ) async def heroku_usage(): try: import psutil except ImportError: return ( False, "'psutil' not installed!\nPlease Install it to use this.\n`pip3 install psutil`", ) if not (HEROKU_API and HEROKU_APP_NAME): if HOSTED_ON == "heroku": return False, "Please fill `HEROKU_API` and `HEROKU_APP_NAME`" return ( False, f"`This command is only for Heroku Users, You are using {HOSTED_ON}`", ) user_id = Heroku.account().id headers = { "User-Agent": choice(some_random_headers), "Authorization": f"Bearer {heroku_api}", "Accept": "application/vnd.heroku+json; version=3.account-quotas", } her_url = f"https://api.heroku.com/accounts/{user_id}/actions/get-quota" try: result = await async_searcher(her_url, headers=headers, re_json=True) except Exception as er: return False, str(er) quota = result["account_quota"] quota_used = result["quota_used"] remaining_quota = quota - quota_used percentage = math.floor(remaining_quota / quota * 100) minutes_remaining = remaining_quota / 60 hours = math.floor(minutes_remaining / 60) minutes = math.floor(minutes_remaining % 60) App = result["apps"] try: App[0]["quota_used"] except IndexError: AppQuotaUsed = 0 AppPercentage = 0 else: AppQuotaUsed = App[0]["quota_used"] / 60 AppPercentage = math.floor(App[0]["quota_used"] * 100 / quota) AppHours = math.floor(AppQuotaUsed / 60) AppMinutes = math.floor(AppQuotaUsed % 60) total, used, free = shutil.disk_usage(".") _ = shutil.disk_usage("/") disk = _.used / _.total * 100 cpuUsage = psutil.cpu_percent() memory = psutil.virtual_memory().percent upload = humanbytes(psutil.net_io_counters().bytes_sent) down = humanbytes(psutil.net_io_counters().bytes_recv) TOTAL = humanbytes(total) USED = humanbytes(used) FREE = humanbytes(free) return True, get_string("usage").format( Var.HEROKU_APP_NAME, AppHours, AppMinutes, AppPercentage, hours, minutes, percentage, TOTAL, USED, FREE, upload, down, cpuUsage, memory, disk, ) def db_usage(): if udB.name == "Mongo": total = 512 elif udB.name == "Redis": total = 30 elif udB.name == "SQL": total = 20 total = total * (2**20) used = udB.usage a = f"{humanbytes(used)}/{humanbytes(total)}" b = f"{str(round((used / total) * 100, 2))}%" return f"**{udB.name}**\n\n**Storage Used**: `{a}`\n**Usage percentage**: **{b}**" async def get_full_usage(): is_hk, hk = await heroku_usage() her = hk if is_hk else "" rd = db_usage() return her + "\n\n" + rd async def usage_finder(event): x = await event.eor(get_string("com_1")) try: opt = event.text.split(" ", maxsplit=1)[1] except IndexError: return await x.edit(simple_usage()) if opt == "db": await x.edit(db_usage()) elif opt == "heroku": is_hk, hk = await heroku_usage() await x.edit(hk) else: await x.edit(await get_full_usage())
null
5,977
from . import LOGS from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from pyUltroid.dB.base import KeyManager from . import get_string, udB, ultroid_bot, ultroid_cmd async def set_time(e): if not e.pattern_match.group(1).strip(): return await e.eor(get_string("nightm_1")) try: ok = e.text.split(maxsplit=1)[1].split() if len(ok) != 4: return await e.eor(get_string("nightm_1")) tm = [int(x) for x in ok] udB.set_key("NIGHT_TIME", str(tm)) await e.eor(get_string("nightm_2")) except BaseException: await e.eor(get_string("nightm_1"))
null
5,978
from . import LOGS from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from pyUltroid.dB.base import KeyManager from . import get_string, udB, ultroid_bot, ultroid_cmd keym = KeyManager("NIGHT_CHATS", cast=list) async def add_grp(e): if pat := e.pattern_match.group(1).strip(): try: keym.add((await ultroid_bot.get_entity(pat)).id) return await e.eor(f"Done, Added {pat} To Night Mode.") except BaseException: return await e.eor(get_string("nightm_5"), time=5) keym.add(e.chat_id) await e.eor(get_string("nightm_3"))
null
5,979
from . import LOGS from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from pyUltroid.dB.base import KeyManager from . import get_string, udB, ultroid_bot, ultroid_cmd keym = KeyManager("NIGHT_CHATS", cast=list) async def r_em_grp(e): if pat := e.pattern_match.group(1).strip(): try: keym.remove((await ultroid_bot.get_entity(pat)).id) return await e.eor(f"Done, Removed {pat} To Night Mode.") except BaseException: return await e.eor(get_string("nightm_5"), time=5) keym.remove(e.chat_id) await e.eor(get_string("nightm_4"))
null
5,980
from . import LOGS from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from pyUltroid.dB.base import KeyManager from . import get_string, udB, ultroid_bot, ultroid_cmd keym = KeyManager("NIGHT_CHATS", cast=list) async def rem_grp(e): chats = keym.get() name = "NightMode Groups Are-:\n\n" for x in chats: try: ok = await ultroid_bot.get_entity(x) name += f"@{ok.username}" if ok.username else ok.title except BaseException: name += str(x) await e.eor(name)
null
5,981
from . import LOGS from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from pyUltroid.dB.base import KeyManager from . import get_string, udB, ultroid_bot, ultroid_cmd keym = KeyManager("NIGHT_CHATS", cast=list) async def open_grp(): for chat in keym.get(): try: await ultroid_bot( EditChatDefaultBannedRightsRequest( chat, banned_rights=ChatBannedRights( until_date=None, send_messages=False, send_media=False, send_stickers=False, send_gifs=False, send_games=False, send_inline=False, send_polls=False, ), ) ) await ultroid_bot.send_message(chat, "**NightMode Off**\n\nGroup Opened 🥳.") except Exception as er: LOGS.info(er)
null
5,982
from . import LOGS from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from telethon.tl.types import ChatBannedRights from pyUltroid.dB.base import KeyManager from . import get_string, udB, ultroid_bot, ultroid_cmd keym = KeyManager("NIGHT_CHATS", cast=list) async def close_grp(): __, _, h2, m2 = 0, 0, 7, 0 if udB.get_key("NIGHT_TIME"): _, __, h2, m2 = eval(udB.get_key("NIGHT_TIME")) for chat in keym.get(): try: await ultroid_bot( EditChatDefaultBannedRightsRequest( chat, banned_rights=ChatBannedRights( until_date=None, send_messages=True, ), ) ) await ultroid_bot.send_message( chat, f"**NightMode : Group Closed**\n\nGroup Will Open At `{h2}:{m2}`" ) except Exception as er: LOGS.info(er)
null
5,983
from . import get_help import math import time from pyUltroid.fns.admins import ban_time from . import asyncio, get_string, ultroid_cmd def ban_time(time_str): """Simplify ban time from text""" if not any(time_str.endswith(unit) for unit in ("s", "m", "h", "d")): time_str += "s" unit = time_str[-1] time_int = time_str[:-1] if not time_int.isdigit(): raise Exception("Invalid time amount specified.") to_return = "" if unit == "s": to_return = int(time.time() + int(time_int)) elif unit == "m": to_return = int(time.time() + int(time_int) * 60) elif unit == "h": to_return = int(time.time() + int(time_int) * 60 * 60) elif unit == "d": to_return = int(time.time() + int(time_int) * 24 * 60 * 60) return to_return async def _(e): act = e.pattern_match.group(1).strip() t = e.pattern_match.group(2) if act in ["audio", "round", "video"]: act = f"record-{act}" if t.isdigit(): t = int(t) elif t.endswith(("s", "h", "d", "m")): t = math.ceil((ban_time(t)) - time.time()) else: t = 60 await e.eor(get_string("fka_1").format(str(t)), time=5) async with e.client.action(e.chat_id, act): await asyncio.sleep(t)
null
5,984
import os import time from datetime import datetime as dt from pyUltroid.fns.misc import rotate_image from pyUltroid.fns.tools import make_html_telegraph from . import ( LOGS, Telegraph, bash, downloader, get_string, is_url_ok, mediainfo, ultroid_cmd, ) from .. import * def make_html_telegraph(title, html=""): telegraph = telegraph_client() page = telegraph.create_page( title=title, html_content=html, ) return page["url"] async def mi(e): r = await e.get_reply_message() match = e.pattern_match.group(1).strip() taime = time.time() extra = "" if r and r.media: xx = mediainfo(r.media) murl = r.media.stringify() url = await make_html_telegraph("Mediainfo", f"<pre>{murl}</pre>") extra = f"**[{xx}]({url})**\n\n" e = await e.eor(f"{extra}`Loading More...`", link_preview=False) if hasattr(r.media, "document"): file = r.media.document mime_type = file.mime_type filename = r.file.name if not filename: if "audio" in mime_type: filename = "audio_" + dt.now().isoformat("_", "seconds") + ".ogg" elif "video" in mime_type: filename = "video_" + dt.now().isoformat("_", "seconds") + ".mp4" dl = await downloader( f"resources/downloads/{filename}", file, e, taime, f"{extra}`Loading More...`", ) naam = dl.name else: naam = await r.download_media() elif match and ( os.path.isfile(match) or (match.startswith("https://") and (await is_url_ok(match))) ): naam, xx = match, "file" else: return await e.eor(get_string("cvt_3"), time=5) out, er = await bash(f"mediainfo '{naam}'") if er: LOGS.info(er) out = extra or str(er) return await e.edit(out, link_preview=False) makehtml = "" if naam.endswith((".jpg", ".png")): if os.path.exists(naam): med = "https://graph.org" + Telegraph.upload_file(naam)[0]["src"] else: med = match makehtml += f"<img src='{med}'><br>" for line in out.split("\n"): line = line.strip() if not line: makehtml += "<br>" elif ":" not in line: makehtml += f"<h3>{line}</h3>" else: makehtml += f"<p>{line}</p>" try: urll = await make_html_telegraph("Mediainfo", makehtml) except Exception as er: LOGS.exception(er) return await e.eor(f"{extra}[{get_string('mdi_1')}]({urll})", link_preview=False) if not match: os.remove(naam)
null
5,985
import os import time from datetime import datetime as dt from pyUltroid.fns.misc import rotate_image from pyUltroid.fns.tools import make_html_telegraph from . import ( LOGS, Telegraph, bash, downloader, get_string, is_url_ok, mediainfo, ultroid_cmd, ) try: import cv2 except ImportError: LOGS.info("WARNING: 'cv2' not found!") cv2 = None from .. import * def rotate_image(image, angle): if not cv2: raise DependencyMissingError("This function needs 'cv2' to be installed!") image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) return cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) async def rotate_(ult): match = ult.pattern_match.group(1).strip() if not ult.is_reply: return await ult.eor("`Reply to a media...`") if match: try: match = int(match) except ValueError: match = None if not match: return await ult.eor("`Please provide a valid angle to rotate media..`") reply = await ult.get_reply_message() msg = await ult.eor(get_string("com_1")) photo = reply.game.photo if reply.game else None if reply.video: media = await reply.download_media() file = f"{media}.mp4" await bash( f'ffmpeg -i "{media}" -c copy -metadata:s:v:0 rotate={match} "{file}" -y' ) elif photo or reply.photo or reply.sticker: media = await ult.client.download_media(photo or reply) img = cv2.imread(media) new_ = rotate_image(img, match) file = "ult.png" cv2.imwrite(file, new_) else: return await msg.edit("`Unsupported Media..\nReply to Photo/Video`") if os.path.exists(file): await ult.client.send_file( ult.chat_id, file=file, video_note=bool(reply.video_note), reply_to=reply.id ) os.remove(media) await msg.try_delete()
null
5,986
from . import get_help import re from . import Button, asst, callback, get_string, in_pattern, udB, ultroid_cmd lst = list(zip(tultd[::4], tultd[1::4], tultd[2::4], tultd[3::4])) lst.append([Button.inline("=", data="calc=")]) async def icalc(e): udB.del_key("calc") if e.client._bot: return await e.reply(get_string("calc_1"), buttons=lst) results = await e.client.inline_query(asst.me.username, "calc") await results[0].click(e.chat_id, silent=True, hide_via=True) await e.delete()
null
5,987
from . import get_help import re from . import Button, asst, callback, get_string, in_pattern, udB, ultroid_cmd lst = list(zip(tultd[::4], tultd[1::4], tultd[2::4], tultd[3::4])) lst.append([Button.inline("=", data="calc=")]) async def _(e): calc = e.builder.article("Calc", text=get_string("calc_1"), buttons=lst) await e.answer([calc])
null
5,988
from . import get_help import re from . import Button, asst, callback, get_string, in_pattern, udB, ultroid_cmd CALC = {} async def _(e): x = (e.data_match.group(1)).decode() user = e.query.user_id get = None if x == "AC": if CALC.get(user): CALC.pop(user) await e.edit( get_string("calc_1"), buttons=[Button.inline(get_string("calc_2"), data="recalc")], ) elif x == "C": if CALC.get(user): CALC.pop(user) await e.answer("cleared") elif x == "⌫": if CALC.get(user): get = CALC[user] if get: CALC.update({user: get[:-1]}) await e.answer(str(get[:-1])) elif x == "%": if CALC.get(user): get = CALC[user] if get: CALC.update({user: f"{get}/100"}) await e.answer(str(f"{get}/100")) elif x == "÷": if CALC.get(user): get = CALC[user] if get: CALC.update({user: f"{get}/"}) await e.answer(str(f"{get}/")) elif x == "x": if CALC.get(user): get = CALC[user] if get: CALC.update({user: f"{get}*"}) await e.answer(str(f"{get}*")) elif x == "=": if CALC.get(user): get = CALC[user] if get: if get.endswith(("*", ".", "/", "-", "+")): get = get[:-1] out = eval(get) try: num = float(out) await e.answer(f"Answer : {num}", cache_time=0, alert=True) except BaseException: CALC.pop(user) await e.answer(get_string("sf_8"), cache_time=0, alert=True) await e.answer("None") else: if CALC.get(user): get = CALC[user] if get: CALC.update({user: get + x}) return await e.answer(str(get + x)) CALC.update({user: x}) await e.answer(str(x))
null
5,989
from . import get_help import re from . import Button, asst, callback, get_string, in_pattern, udB, ultroid_cmd m = [ "AC", "C", "⌫", "%", "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "x", "00", "0", ".", "÷", ] tultd = [Button.inline(f"{x}", data=f"calc{x}") for x in m] lst = list(zip(tultd[::4], tultd[1::4], tultd[2::4], tultd[3::4])) lst.append([Button.inline("=", data="calc=")]) async def _(e): m = [ "AC", "C", "⌫", "%", "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "x", "00", "0", ".", "÷", ] tultd = [Button.inline(f"{x}", data=f"calc{x}") for x in m] lst = list(zip(tultd[::4], tultd[1::4], tultd[2::4], tultd[3::4])) lst.append([Button.inline("=", data="calc=")]) await e.edit(get_string("calc_1"), buttons=lst)
null
5,990
from . import get_help from telethon import events from pyUltroid.dB.base import KeyManager from . import LOGS, asst, ultroid_bot, ultroid_cmd Keym = KeyManager("DND_CHATS", cast=list) def join_func(e): return e.user_joined and Keym.contains(e.chat_id) async def dnd_func(event): for user in event.users: try: await (await event.client.kick_participant(event.chat_id, user)).delete() except Exception as ex: LOGS.error("Error in DND:") LOGS.exception(ex) await event.delete() pattern="autokick (on|off)$", admins_only=True, manager=True, require="ban_users", fullsudo=True, if Keym.get(): ultroid_bot.add_handler(dnd_func, events.ChatAction(func=join_func)) asst.add_handler(dnd_func, events.ChatAction(func=join_func)) async def _(event): match = event.pattern_match.group(1) if match == "on": if Keym.contains(event.chat_id): return await event.eor("`Chat already in do not disturb mode.`", time=3) Keym.add(event.chat_id) event.client.add_handler(dnd_func, events.ChatAction(func=join_func)) await event.eor("`Do not disturb mode activated for this chat.`", time=3) elif match == "off": if not Keym.contains(event.chat_id): return await event.eor("`Chat is not in do not disturb mode.`", time=3) Keym.remove(event.chat_id) await event.eor("`Do not disturb mode deactivated for this chat.`", time=3)
null
5,991
from . import get_help from telethon.errors import ChatAdminRequiredError as no_admin from telethon.tl.functions.channels import ( CreateChannelRequest, DeleteChannelRequest, EditPhotoRequest, GetFullChannelRequest, UpdateUsernameRequest, ) from telethon.tl.functions.messages import ( CreateChatRequest, ExportChatInviteRequest, GetFullChatRequest, ) from telethon.tl.types import ( ChannelParticipantsKicked, User, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import HNDLR, LOGS, asst, con, get_string, mediainfo, os, types, udB, ultroid_cmd async def _(e): xx = await e.eor(get_string("com_1")) try: match = e.text.split(" ", maxsplit=1)[1] chat = await e.client.parse_id(match) except IndexError: chat = e.chat_id try: await e.client(DeleteChannelRequest(chat)) except TypeError: return await xx.eor(get_string("chats_1"), time=10) except no_admin: return await xx.eor(get_string("chats_2"), time=10) await e.client.send_message( int(udB.get_key("LOG_CHANNEL")), get_string("chats_6").format(e.chat_id) )
null
5,992
from . import get_help from telethon.errors import ChatAdminRequiredError as no_admin from telethon.tl.functions.channels import ( CreateChannelRequest, DeleteChannelRequest, EditPhotoRequest, GetFullChannelRequest, UpdateUsernameRequest, ) from telethon.tl.functions.messages import ( CreateChatRequest, ExportChatInviteRequest, GetFullChatRequest, ) from telethon.tl.types import ( ChannelParticipantsKicked, User, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import HNDLR, LOGS, asst, con, get_string, mediainfo, os, types, udB, ultroid_cmd async def _(e): reply = await e.get_reply_message() match = e.pattern_match.group(1).strip() if reply and not isinstance(reply.sender, User): chat = await reply.get_sender() else: chat = await e.get_chat() if hasattr(chat, "username") and chat.username: return await e.eor(f"Username: @{chat.username}") request, usage, title, link = None, None, None, None if match: split = match.split(maxsplit=1) request = split[0] in ["r", "request"] title = "Created by Ultroid" if len(split) > 1: match = split[1] spli = match.split(maxsplit=1) if spli[0].isdigit(): usage = int(spli[0]) if len(spli) > 1: title = spli[1] elif not request: if match.isdigit(): usage = int(match) else: title = match if request and usage: usage = 0 if request or title: try: r = await e.client( ExportChatInviteRequest( e.chat_id, request_needed=request, usage_limit=usage, title=title, ), ) except no_admin: return await e.eor(get_string("chats_2"), time=10) link = r.link else: if isinstance(chat, types.Chat): FC = await e.client(GetFullChatRequest(chat.id)) elif isinstance(chat, types.Channel): FC = await e.client(GetFullChannelRequest(chat.id)) else: return Inv = FC.full_chat.exported_invite if Inv and not Inv.revoked: link = Inv.link if link: return await e.eor(f"Link:- {link}") await e.eor("`Failed to getlink!\nSeems like link is inaccessible to you...`")
null
5,993
from . import get_help from telethon.errors import ChatAdminRequiredError as no_admin from telethon.tl.functions.channels import ( CreateChannelRequest, DeleteChannelRequest, EditPhotoRequest, GetFullChannelRequest, UpdateUsernameRequest, ) from telethon.tl.functions.messages import ( CreateChatRequest, ExportChatInviteRequest, GetFullChatRequest, ) from telethon.tl.types import ( ChannelParticipantsKicked, User, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import HNDLR, LOGS, asst, con, get_string, mediainfo, os, types, udB, ultroid_cmd async def _(e): type_of_group = e.pattern_match.group(1).strip() group_name = e.pattern_match.group(2) username = None if " ; " in group_name: group_ = group_name.split(" ; ", maxsplit=1) group_name = group_[0] username = group_[1] xx = await e.eor(get_string("com_1")) if type_of_group == "b": try: r = await e.client( CreateChatRequest( users=[asst.me.username], title=group_name, ), ) created_chat_id = r.chats[0].id result = await e.client( ExportChatInviteRequest( peer=created_chat_id, ), ) await xx.edit( get_string("chats_4").format(group_name, result.link), link_preview=False, ) except Exception as ex: await xx.edit(str(ex)) elif type_of_group in ["g", "c"]: try: r = await e.client( CreateChannelRequest( title=group_name, about=get_string("chats_5"), megagroup=type_of_group != "c", ) ) created_chat_id = r.chats[0].id if username: await e.client(UpdateUsernameRequest(created_chat_id, username)) result = f"https://t.me/{username}" else: result = ( await e.client( ExportChatInviteRequest( peer=created_chat_id, ), ) ).link await xx.edit( get_string("chats_6").format(f"[{group_name}]({result})"), link_preview=False, ) except Exception as ex: await xx.edit(str(ex))
null
5,994
from . import get_help from telethon.errors import ChatAdminRequiredError as no_admin from telethon.tl.functions.channels import ( CreateChannelRequest, DeleteChannelRequest, EditPhotoRequest, GetFullChannelRequest, UpdateUsernameRequest, ) from telethon.tl.functions.messages import ( CreateChatRequest, ExportChatInviteRequest, GetFullChatRequest, ) from telethon.tl.types import ( ChannelParticipantsKicked, User, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import HNDLR, LOGS, asst, con, get_string, mediainfo, os, types, udB, ultroid_cmd async def _(ult): if not ult.is_reply: return await ult.eor("`Reply to a Media..`", time=5) match = ult.pattern_match.group(1).strip() if not ult.client._bot and match: try: chat = await ult.client.parse_id(match) except Exception as ok: return await ult.eor(str(ok)) else: chat = ult.chat_id reply = await ult.get_reply_message() if reply.photo or reply.sticker or reply.video: replfile = await reply.download_media() elif reply.document and reply.document.thumbs: replfile = await reply.download_media(thumb=-1) else: return await ult.eor("Reply to a Photo or Video..") mediain = mediainfo(reply.media) if "animated" in mediain: replfile = await con.convert(replfile, convert_to="mp4") else: replfile = await con.convert( replfile, outname="chatphoto", allowed_formats=["jpg", "png", "mp4"] ) file = await ult.client.upload_file(replfile) try: if "pic" not in mediain: file = types.InputChatUploadedPhoto(video=file) await ult.client(EditPhotoRequest(chat, file)) await ult.eor("`Group Photo has Successfully Changed !`", time=5) except Exception as ex: await ult.eor(f"Error occured.\n`{str(ex)}`", time=5) os.remove(replfile)
null
5,995
from . import get_help from telethon.errors import ChatAdminRequiredError as no_admin from telethon.tl.functions.channels import ( CreateChannelRequest, DeleteChannelRequest, EditPhotoRequest, GetFullChannelRequest, UpdateUsernameRequest, ) from telethon.tl.functions.messages import ( CreateChatRequest, ExportChatInviteRequest, GetFullChatRequest, ) from telethon.tl.types import ( ChannelParticipantsKicked, User, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import HNDLR, LOGS, asst, con, get_string, mediainfo, os, types, udB, ultroid_cmd async def _(ult): match = ult.pattern_match.group(1).strip() chat = ult.chat_id if not ult.client._bot and match: chat = match try: await ult.client(EditPhotoRequest(chat, types.InputChatPhotoEmpty())) text = "`Removed Chat Photo..`" except Exception as E: text = str(E) return await ult.eor(text, time=5)
null
5,996
from . import get_help from telethon.errors import ChatAdminRequiredError as no_admin from telethon.tl.functions.channels import ( CreateChannelRequest, DeleteChannelRequest, EditPhotoRequest, GetFullChannelRequest, UpdateUsernameRequest, ) from telethon.tl.functions.messages import ( CreateChatRequest, ExportChatInviteRequest, GetFullChatRequest, ) from telethon.tl.types import ( ChannelParticipantsKicked, User, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import HNDLR, LOGS, asst, con, get_string, mediainfo, os, types, udB, ultroid_cmd async def _(event): xx = await event.eor("Searching Participant Lists.") p = 0 title = (await event.get_chat()).title async for i in event.client.iter_participants( event.chat_id, filter=ChannelParticipantsKicked, aggressive=True, ): try: await event.client.edit_permissions(event.chat_id, i, view_messages=True) p += 1 except no_admin: pass except BaseException as er: LOGS.exception(er) await xx.eor(f"{title}: {p} unbanned", time=5)
null
5,997
from . import get_help from telethon.errors import ChatAdminRequiredError as no_admin from telethon.tl.functions.channels import ( CreateChannelRequest, DeleteChannelRequest, EditPhotoRequest, GetFullChannelRequest, UpdateUsernameRequest, ) from telethon.tl.functions.messages import ( CreateChatRequest, ExportChatInviteRequest, GetFullChatRequest, ) from telethon.tl.types import ( ChannelParticipantsKicked, User, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import HNDLR, LOGS, asst, con, get_string, mediainfo, os, types, udB, ultroid_cmd async def _(event): xx = await event.eor(get_string("com_1")) input_str = event.pattern_match.group(1).strip() p, a, b, c, d, m, n, y, w, o, q, r = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 async for i in event.client.iter_participants(event.chat_id): p += 1 # Total Count if isinstance(i.status, UserStatusEmpty): if "empty" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: y += 1 if isinstance(i.status, UserStatusLastMonth): if "month" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: m += 1 if isinstance(i.status, UserStatusLastWeek): if "week" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: w += 1 if isinstance(i.status, UserStatusOffline): if "offline" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: o += 1 if isinstance(i.status, UserStatusOnline): if "online" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: q += 1 if isinstance(i.status, UserStatusRecently): if "recently" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: r += 1 if i.bot: if "bot" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: b += 1 elif i.deleted: if "deleted" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: d += 1 elif i.status is None: if "none" in input_str: try: await event.client.kick_participant(event.chat_id, i) c += 1 except BaseException: pass else: n += 1 if input_str: required_string = f"**>> Kicked** `{c} / {p}` **users**\n\n" else: required_string = f"**>> Total** `{p}` **users**\n\n" required_string += f" `{HNDLR}rmusers deleted` **••** `{d}`\n" required_string += f" `{HNDLR}rmusers empty` **••** `{y}`\n" required_string += f" `{HNDLR}rmusers month` **••** `{m}`\n" required_string += f" `{HNDLR}rmusers week` **••** `{w}`\n" required_string += f" `{HNDLR}rmusers offline` **••** `{o}`\n" required_string += f" `{HNDLR}rmusers online` **••** `{q}`\n" required_string += f" `{HNDLR}rmusers recently` **••** `{r}`\n" required_string += f" `{HNDLR}rmusers bot` **••** `{b}`\n" required_string += f" `{HNDLR}rmusers none` **••** `{n}`" await xx.eor(required_string)
null
5,998
import asyncio from telethon import events from telethon.errors.rpcerrorlist import UserNotParticipantError from telethon.tl.functions.channels import GetParticipantRequest from telethon.utils import get_display_name from pyUltroid.dB import stickers from pyUltroid.dB.echo_db import check_echo from pyUltroid.dB.forcesub_db import get_forcesetting from pyUltroid.dB.gban_mute_db import is_gbanned from pyUltroid.dB.greetings_db import get_goodbye, get_welcome, must_thank from pyUltroid.dB.nsfw_db import is_profan from pyUltroid.fns.helper import inline_mention from pyUltroid.fns.tools import async_searcher, create_tl_btn, get_chatbot_reply from . import LOG_CHANNEL, LOGS, asst, get_string, types, udB, ultroid_bot from ._inline import something async def DummyHandler(ult): # clean chat actions key = udB.get_key("CLEANCHAT") or [] if ult.chat_id in key: try: await ult.delete() except BaseException: pass # thank members if must_thank(ult.chat_id): chat_count = (await ult.client.get_participants(ult.chat_id, limit=0)).total if chat_count % 100 == 0: stik_id = chat_count / 100 - 1 sticker = stickers[stik_id] await ult.respond(file=sticker) # force subscribe if ( udB.get_key("FORCESUB") and ((ult.user_joined or ult.user_added)) and get_forcesetting(ult.chat_id) ): user = await ult.get_user() if not user.bot: joinchat = get_forcesetting(ult.chat_id) try: await ultroid_bot(GetParticipantRequest(int(joinchat), user.id)) except UserNotParticipantError: await ultroid_bot.edit_permissions( ult.chat_id, user.id, send_messages=False ) res = await ultroid_bot.inline_query( asst.me.username, f"fsub {user.id}_{joinchat}" ) await res[0].click(ult.chat_id, reply_to=ult.action_message.id) if ult.user_joined or ult.added_by: user = await ult.get_user() chat = await ult.get_chat() # gbans and @UltroidBans checks if udB.get_key("ULTROID_BANS"): try: is_banned = await async_searcher( "https://bans.ultroid.tech/api/status", json={"userId": user.id}, post=True, re_json=True, ) if is_banned["is_banned"]: await ult.client.edit_permissions( chat.id, user.id, view_messages=False, ) await ult.respond( f'**@UltroidBans:** Banned user detected and banned!\n`{str(is_banned)}`.\nBan reason: {is_banned["reason"]}', ) except BaseException: pass reason = is_gbanned(user.id) if reason and chat.admin_rights: try: await ult.client.edit_permissions( chat.id, user.id, view_messages=False, ) gban_watch = get_string("can_1").format(inline_mention(user), reason) await ult.reply(gban_watch) except Exception as er: LOGS.exception(er) # greetings elif get_welcome(ult.chat_id): user = await ult.get_user() chat = await ult.get_chat() title = chat.title or "this chat" count = ( chat.participants_count or (await ult.client.get_participants(chat, limit=0)).total ) mention = inline_mention(user) name = user.first_name fullname = get_display_name(user) uu = user.username username = f"@{uu}" if uu else mention wel = get_welcome(ult.chat_id) msgg = wel["welcome"] med = wel["media"] or None userid = user.id msg = None if msgg: msg = msgg.format( mention=mention, group=title, count=count, name=name, fullname=fullname, username=username, userid=userid, ) if wel.get("button"): btn = create_tl_btn(wel["button"]) await something(ult, msg, med, btn) elif msg: send = await ult.reply( msg, file=med, ) await asyncio.sleep(150) await send.delete() else: await ult.reply(file=med) elif (ult.user_left or ult.user_kicked) and get_goodbye(ult.chat_id): user = await ult.get_user() chat = await ult.get_chat() title = chat.title or "this chat" count = ( chat.participants_count or (await ult.client.get_participants(chat, limit=0)).total ) mention = inline_mention(user) name = user.first_name fullname = get_display_name(user) uu = user.username username = f"@{uu}" if uu else mention wel = get_goodbye(ult.chat_id) msgg = wel["goodbye"] med = wel["media"] userid = user.id msg = None if msgg: msg = msgg.format( mention=mention, group=title, count=count, name=name, fullname=fullname, username=username, userid=userid, ) if wel.get("button"): btn = create_tl_btn(wel["button"]) await something(ult, msg, med, btn) elif msg: send = await ult.reply( msg, file=med, ) await asyncio.sleep(150) await send.delete() else: await ult.reply(file=med) async def Function(event): try: await DummyHandler(event) except Exception as er: LOGS.exception(er)
null
5,999
import asyncio from telethon import events from telethon.errors.rpcerrorlist import UserNotParticipantError from telethon.tl.functions.channels import GetParticipantRequest from telethon.utils import get_display_name from pyUltroid.dB import stickers from pyUltroid.dB.echo_db import check_echo from pyUltroid.dB.forcesub_db import get_forcesetting from pyUltroid.dB.gban_mute_db import is_gbanned from pyUltroid.dB.greetings_db import get_goodbye, get_welcome, must_thank from pyUltroid.dB.nsfw_db import is_profan from pyUltroid.fns.helper import inline_mention from pyUltroid.fns.tools import async_searcher, create_tl_btn, get_chatbot_reply from . import LOG_CHANNEL, LOGS, asst, get_string, types, udB, ultroid_bot from ._inline import something async def uname_stuff(id, uname, name): if udB.get_key("USERNAME_LOG"): old_ = udB.get_key("USERNAME_DB") or {} old = old_.get(id) # Ignore Name Logs if old and old == uname: return if old and uname: await asst.send_message( LOG_CHANNEL, get_string("can_2").format(old, uname), ) elif old: await asst.send_message( LOG_CHANNEL, get_string("can_3").format(f"[{name}](tg://user?id={id})", old), ) elif uname: await asst.send_message( LOG_CHANNEL, get_string("can_4").format(f"[{name}](tg://user?id={id})", uname), ) old_[id] = uname udB.set_key("USERNAME_DB", old_) def check_echo(chat, user): x = get_stuff() if (k := x.get(int(chat))) and int(user) in k: return True def is_profan(chat): x = get_stuff("PROFANITY") if x.get(chat): return x[chat] from .. import * async def get_chatbot_reply(message): chatbot_base = "https://kuki-api-lac.vercel.app/message={}" req_link = chatbot_base.format( message, ) try: return (await async_searcher(req_link, re_json=True)).get("reply") except Exception: LOGS.info(f"**ERROR:**`{format_exc()}`") async def chatBot_replies(e): sender = await e.get_sender() if not isinstance(sender, types.User) or sender.bot: return if check_echo(e.chat_id, e.sender_id): try: await e.respond(e.message) except Exception as er: LOGS.exception(er) key = udB.get_key("CHATBOT_USERS") or {} if e.text and key.get(e.chat_id) and sender.id in key[e.chat_id]: msg = await get_chatbot_reply(e.message.message) if msg: sleep = udB.get_key("CHATBOT_SLEEP") or 1.5 await asyncio.sleep(sleep) await e.reply(msg) chat = await e.get_chat() if e.is_group and sender.username: await uname_stuff(e.sender_id, sender.username, sender.first_name) elif e.is_private and chat.username: await uname_stuff(e.sender_id, chat.username, chat.first_name) if detector and is_profan(e.chat_id) and e.text: x, y = detector(e.text) if y: await e.delete()
null
6,000
import asyncio from telethon import events from telethon.errors.rpcerrorlist import UserNotParticipantError from telethon.tl.functions.channels import GetParticipantRequest from telethon.utils import get_display_name from pyUltroid.dB import stickers from pyUltroid.dB.echo_db import check_echo from pyUltroid.dB.forcesub_db import get_forcesetting from pyUltroid.dB.gban_mute_db import is_gbanned from pyUltroid.dB.greetings_db import get_goodbye, get_welcome, must_thank from pyUltroid.dB.nsfw_db import is_profan from pyUltroid.fns.helper import inline_mention from pyUltroid.fns.tools import async_searcher, create_tl_btn, get_chatbot_reply from . import LOG_CHANNEL, LOGS, asst, get_string, types, udB, ultroid_bot from ._inline import something async def uname_stuff(id, uname, name): if udB.get_key("USERNAME_LOG"): old_ = udB.get_key("USERNAME_DB") or {} old = old_.get(id) # Ignore Name Logs if old and old == uname: return if old and uname: await asst.send_message( LOG_CHANNEL, get_string("can_2").format(old, uname), ) elif old: await asst.send_message( LOG_CHANNEL, get_string("can_3").format(f"[{name}](tg://user?id={id})", old), ) elif uname: await asst.send_message( LOG_CHANNEL, get_string("can_4").format(f"[{name}](tg://user?id={id})", uname), ) old_[id] = uname udB.set_key("USERNAME_DB", old_) async def uname_change(e): await uname_stuff(e.user_id, e.usernames[0] if e.usernames else None, e.first_name)
null
6,001
from . import get_help import os import time from . import LOGS from telegraph import upload_file as uf from . import ( ULTConfig, bash, con, downloader, get_paste, get_string, udB, ultroid_cmd, uploader, ) async def _(e): r = await e.get_reply_message() if r.photo: dl = await r.download_media() elif r.document and r.document.thumbs: dl = await r.download_media(thumb=-1) else: return await e.eor("`Reply to Photo or media with thumb...`") variable = uf(dl) os.remove(dl) nn = f"https://graph.org{variable[0]}" udB.set_key("CUSTOM_THUMBNAIL", str(nn)) await bash(f"wget {nn} -O resources/extras/ultroid.jpg") await e.eor(get_string("cvt_6").format(nn), link_preview=False)
null
6,002
from . import get_help import os import time from . import LOGS from telegraph import upload_file as uf from . import ( ULTConfig, bash, con, downloader, get_paste, get_string, udB, ultroid_cmd, uploader, ) async def imak(event): reply = await event.get_reply_message() t = time.time() if not reply: return await event.eor(get_string("cvt_1")) inp = event.pattern_match.group(1).strip() if not inp: return await event.eor(get_string("cvt_2")) xx = await event.eor(get_string("com_1")) if reply.media: if hasattr(reply.media, "document"): file = reply.media.document image = await downloader( reply.file.name or str(time.time()), reply.media.document, xx, t, get_string("com_5"), ) file = image.name else: file = await event.client.download_media(reply.media) if os.path.exists(inp): os.remove(inp) await bash(f'mv """{file}""" """{inp}"""') if not os.path.exists(inp) or os.path.exists(inp) and not os.path.getsize(inp): os.rename(file, inp) k = time.time() xxx = await uploader(inp, inp, k, xx, get_string("com_6")) await event.reply( f"`{xxx.name}`", file=xxx, force_document=True, thumb=ULTConfig.thumb, ) os.remove(inp) await xx.delete()
null
6,003
from . import get_help import os import time from . import LOGS from telegraph import upload_file as uf from . import ( ULTConfig, bash, con, downloader, get_paste, get_string, udB, ultroid_cmd, uploader, ) conv_keys = { "img": "png", "sticker": "webp", "webp": "webp", "image": "png", "webm": "webm", "gif": "gif", "json": "json", "tgs": "tgs", } async def uconverter(event): xx = await event.eor(get_string("com_1")) a = await event.get_reply_message() if a is None: return await event.eor("`Reply to Photo or media with thumb...`") input_ = event.pattern_match.group(1).strip() b = await a.download_media("resources/downloads/") if not b and (a.document and a.document.thumbs): b = await a.download_media(thumb=-1) if not b: return await xx.edit(get_string("cvt_3")) try: convert = conv_keys[input_] except KeyError: return await xx.edit(get_string("sts_3").format("gif/img/sticker/webm")) file = await con.convert(b, outname="ultroid", convert_to=convert) if file: await event.client.send_file( event.chat_id, file, reply_to=event.reply_to_msg_id or event.id ) os.remove(file) await xx.delete()
null
6,004
from . import get_help import os import time from . import LOGS from telegraph import upload_file as uf from . import ( ULTConfig, bash, con, downloader, get_paste, get_string, udB, ultroid_cmd, uploader, ) async def _(event): input_str = event.pattern_match.group(1).strip() if not (input_str and event.is_reply): return await event.eor(get_string("cvt_1"), time=5) xx = await event.eor(get_string("com_1")) a = await event.get_reply_message() if not a.message: return await xx.edit(get_string("ex_1")) with open(input_str, "w") as b: b.write(str(a.message)) await xx.edit(f"**Packing into** `{input_str}`") await event.reply(file=input_str, thumb=ULTConfig.thumb) await xx.delete() os.remove(input_str)
null
6,005
from . import get_help import os import time from . import LOGS from telegraph import upload_file as uf from . import ( ULTConfig, bash, con, downloader, get_paste, get_string, udB, ultroid_cmd, uploader, ) async def _(event): a = await event.get_reply_message() b = event.pattern_match.group(1).strip() if not ((a and a.media) or (b and os.path.exists(b))): return await event.eor(get_string("cvt_7"), time=5) xx = await event.eor(get_string("com_1")) rem = None if not b: b = await a.download_media() rem = True try: with open(b) as c: d = c.read() except UnicodeDecodeError: return await xx.eor(get_string("cvt_8"), time=5) try: await xx.edit(f"```{d}```") except BaseException: what, key = await get_paste(d) await xx.edit( f"**MESSAGE EXCEEDS TELEGRAM LIMITS**\n\nSo Pasted It On [SPACEBIN](https://spaceb.in/{key})" ) if rem: os.remove(b)
null
6,006
import os from pyUltroid.fns.tools import _webupload_cache from . import Button, asst, get_string, ultroid_cmd from .. import * _webupload_cache = {} async def _(event): xx = await event.eor(get_string("com_1")) match = event.pattern_match.group(1).strip() if event.chat_id not in _webupload_cache: _webupload_cache.update({int(event.chat_id): {}}) if match: if not os.path.exists(match): return await xx.eor("`File doesn't exist.`") _webupload_cache[event.chat_id][event.id] = match elif event.reply_to_msg_id: reply = await event.get_reply_message() if reply.photo: file = await reply.download_media("resources/downloads/") _webupload_cache[int(event.chat_id)][int(event.id)] = file else: file, _ = await event.client.fast_downloader( reply.document, show_progress=True, event=xx ) _webupload_cache[int(event.chat_id)][int(event.id)] = file.name else: return await xx.eor("`Reply to file or give file path...`") if not event.client._bot: results = await event.client.inline_query( asst.me.username, f"fl2lnk {event.chat_id}:{event.id}" ) await results[0].click(event.chat_id, reply_to=event.reply_to_msg_id) await xx.delete() else: __cache = f"{event.chat_id}:{event.id}" buttons = [ [ Button.inline("anonfiles", data=f"flanonfiles//{__cache}"), Button.inline("transfer", data=f"fltransfer//{__cache}"), ], [ Button.inline("bayfiles", data=f"flbayfiles//{__cache}"), Button.inline("x0.at", data=f"flx0.at//{__cache}"), ], [ Button.inline("file.io", data=f"flfile.io//{__cache}"), Button.inline("siasky", data=f"flsiasky//{__cache}"), ], ] await xx.edit("**Choose Server to Upload File...**", buttons=buttons)
null
6,007
import os from pyUltroid import ULTConfig import qrcode from PIL import Image from telethon.tl.types import MessageMediaDocument as doc from . import check_filename, get_string, ultroid_bot, ultroid_cmd class ULTConfig: import qrcode async def cd(e): reply = await e.get_reply_message() msg = e.pattern_match.group(1).strip() if reply and reply.text: msg = reply.text elif not msg: return await e.eor("`Give Some Text or Reply", time=5) default, cimg = ULTConfig.thumb, None if reply and (reply.sticker or reply.photo): cimg = await reply.download_media() elif ultroid_bot.me.photo and not ultroid_bot.me.photo.has_video: cimg = (await e.client.get_profile_photos(ultroid_bot.uid, limit=1))[0] kk = await e.eor(get_string("com_1")) img = cimg or default ok = Image.open(img) logo = ok.resize((60, 60)) cod = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H) cod.add_data(msg) cod.make() imgg = cod.make_image().convert("RGB") pstn = ((imgg.size[0] - logo.size[0]) // 2, (imgg.size[1] - logo.size[1]) // 2) imgg.paste(logo, pstn) newname = check_filename("qr.jpg") imgg.save(newname) await e.client.send_file(e.chat_id, newname, supports_streaming=True) await kk.delete() os.remove(newname) if cimg: os.remove(cimg)
null