id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
5,708
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable def run_async(function): @wraps(function) async def wrapper(*args, **kwargs): return await asyncio.get_event_loop().run_in_executor( ThreadPoolExecutor(max_workers=multiprocessing.cpu_count() * 5), partial(function, *args, **kwargs), ) return wrapper
null
5,709
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable def inline_mention(user, custom=None, html=False): mention_text = get_display_name(user) or "Deleted Account" if not custom else custom if isinstance(user, types.User): if html: return f"<a href=tg://user?id={user.id}>{mention_text}</a>" return f"[{mention_text}](tg://user?id={user.id})" if isinstance(user, types.Channel) and user.username: if html: return f"<a href=https://t.me/{user.username}>{mention_text}</a>" return f"[{mention_text}](https://t.me/{user.username})" return mention_text def make_mention(user, custom=None): if user.username: return f"@{user.username}" return inline_mention(user, custom=custom)
null
5,710
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable ADDONS = [] LOADED = {} LIST = {} def un_plug(shortname): from .. import asst, ultroid_bot try: all_func = LOADED[shortname] for client in [ultroid_bot, asst]: for x, _ in client.list_event_handlers(): if x in all_func: client.remove_event_handler(x) del LOADED[shortname] del LIST[shortname] ADDONS.remove(shortname) except (ValueError, KeyError): name = f"addons.{shortname}" for client in [ultroid_bot, asst]: for i in reversed(range(len(client._event_builders))): ev, cb = client._event_builders[i] if cb.__module__ == name: del client._event_builders[i] try: del LOADED[shortname] del LIST[shortname] ADDONS.remove(shortname) except KeyError: pass
null
5,711
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable from .. import * CMD_HELP = {} async def eor(event, text=None, time=None, link_preview=False, edit_time=None, **args): reply_to = event.reply_to_msg_id or event if event.out and not isinstance(event, MessageService): if edit_time: await sleep(edit_time) if args.get("file") and not event.media: await event.delete() ok = await event.client.send_message( event.chat_id, text, link_preview=link_preview, reply_to=reply_to, **args ) else: try: ok = await event.edit(text, link_preview=link_preview, **args) except MessageNotModifiedError: ok = event else: ok = await event.client.send_message( event.chat_id, text, link_preview=link_preview, reply_to=reply_to, **args ) if time: await sleep(time) return await ok.delete() return ok async def eod(event, text=None, **kwargs): kwargs["time"] = kwargs.get("time", 8) return await eor(event, text, **kwargs) HELP = {} LOADED = {} LIST = {} def load_addons(plugin_name): base_name = plugin_name.split("/")[-1].split("\\")[-1].replace(".py", "") if base_name.startswith("__"): return from pyUltroid import fns from .. import HNDLR, LOGS, asst, udB, ultroid_bot from .._misc import _supporter as config from .._misc._assistant import asst_cmd, callback, in_pattern from .._misc._decorators import ultroid_cmd from .._misc._supporter import Config, admin_cmd, sudo_cmd from .._misc._wrappers import eod, eor from ..configs import Var from ..dB._core import HELP name = plugin_name.replace("/", ".").replace("\\", ".").replace(".py", "") spec = util.spec_from_file_location(name, plugin_name) mod = util.module_from_spec(spec) for path in configPaths: modules[path] = config modules["pyUltroid.functions"] = fns mod.LOG_CHANNEL = udB.get_key("LOG_CHANNEL") mod.udB = udB mod.asst = asst mod.tgbot = asst mod.ultroid_bot = ultroid_bot mod.ub = ultroid_bot mod.bot = ultroid_bot mod.ultroid = ultroid_bot mod.borg = ultroid_bot mod.telebot = ultroid_bot mod.jarvis = ultroid_bot mod.friday = ultroid_bot mod.eod = eod mod.edit_delete = eod mod.LOGS = LOGS mod.in_pattern = in_pattern mod.hndlr = HNDLR mod.handler = HNDLR mod.HNDLR = HNDLR mod.CMD_HNDLR = HNDLR mod.Config = Config mod.Var = Var mod.eor = eor mod.edit_or_reply = eor mod.asst_cmd = asst_cmd mod.ultroid_cmd = ultroid_cmd mod.on_cmd = ultroid_cmd mod.callback = callback mod.Redis = udB.get_key mod.admin_cmd = admin_cmd mod.sudo_cmd = sudo_cmd mod.HELP = HELP.get("Addons", {}) mod.CMD_HELP = HELP.get("Addons", {}) spec.loader.exec_module(mod) modules[name] = mod doc = modules[name].__doc__.format(i=HNDLR) if modules[name].__doc__ else "" if "Addons" in HELP.keys(): update_cmd = HELP["Addons"] try: update_cmd.update({base_name: doc}) except BaseException: pass else: try: HELP.update({"Addons": {base_name: doc}}) except BaseException as em: pass async def safeinstall(event): from .. import HNDLR from ..startup.utils import load_addons if not event.reply_to: return await eod( event, f"Please use `{HNDLR}install` as reply to a .py file." ) ok = await eor(event, "`Installing...`") reply = await event.get_reply_message() if not ( reply.media and hasattr(reply.media, "document") and reply.file.name and reply.file.name.endswith(".py") ): return await eod(ok, "`Please reply to any python plugin`") plug = reply.file.name.replace(".py", "") if plug in list(LOADED): return await eod(ok, f"Plugin `{plug}` is already installed.") sm = reply.file.name.replace("_", "-").replace("|", "-") dl = await reply.download_media(f"addons/{sm}") if event.text[9:] != "f": read = open(dl).read() for dan in KEEP_SAFE().All: if re.search(dan, read): os.remove(dl) return await ok.edit( f"**Installation Aborted.**\n**Reason:** Occurance of `{dan}` in `{reply.file.name}`.\n\nIf you trust the provider and/or know what you're doing, use `{HNDLR}install f` to force install.", ) try: load_addons(dl) # dl.split("/")[-1].replace(".py", "")) except BaseException: os.remove(dl) return await eor(ok, f"**ERROR**\n\n`{format_exc()}`", time=30) plug = sm.replace(".py", "") if plug in HELP: output = "**Plugin** - `{}`\n".format(plug) for i in HELP[plug]: output += i output += "\n© @TeamUltroid" await eod(ok, f"✓ `Ultroid - Installed`: `{plug}` ✓\n\n{output}") elif plug in CMD_HELP: output = f"Plugin Name-{plug}\n\n✘ Commands Available-\n\n" output += str(CMD_HELP[plug]) await eod(ok, f"✓ `Ultroid - Installed`: `{plug}` ✓\n\n{output}") else: try: x = f"Plugin Name-{plug}\n\n✘ Commands Available-\n\n" for d in LIST[plug]: x += HNDLR + d + "\n" await eod(ok, f"✓ `Ultroid - Installed`: `{plug}` ✓\n\n`{x}`") except BaseException: await eod(ok, f"✓ `Ultroid - Installed`: `{plug}` ✓")
null
5,712
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module try: import heroku3 except ImportError: heroku3 = None import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable class Var: # mandatory API_ID = ( int(sys.argv[1]) if len(sys.argv) > 1 else config("API_ID", default=6, cast=int) ) API_HASH = ( sys.argv[2] if len(sys.argv) > 2 else config("API_HASH", default="eb06d4abfb49dc3eeb1aeb98ae0f581e") ) SESSION = sys.argv[3] if len(sys.argv) > 3 else config("SESSION", default=None) REDIS_URI = ( sys.argv[4] if len(sys.argv) > 4 else (config("REDIS_URI", default=None) or config("REDIS_URL", default=None)) ) REDIS_PASSWORD = ( sys.argv[5] if len(sys.argv) > 5 else config("REDIS_PASSWORD", default=None) ) # extras BOT_TOKEN = config("BOT_TOKEN", default=None) LOG_CHANNEL = config("LOG_CHANNEL", default=0, cast=int) HEROKU_APP_NAME = config("HEROKU_APP_NAME", default=None) HEROKU_API = config("HEROKU_API", default=None) VC_SESSION = config("VC_SESSION", default=None) ADDONS = config("ADDONS", default=False, cast=bool) VCBOT = config("VCBOT", default=False, cast=bool) # for railway REDISPASSWORD = config("REDISPASSWORD", default=None) REDISHOST = config("REDISHOST", default=None) REDISPORT = config("REDISPORT", default=None) REDISUSER = config("REDISUSER", default=None) # for sql DATABASE_URL = config("DATABASE_URL", default=None) # for MONGODB users MONGO_URI = config("MONGO_URI", default=None) async def eor(event, text=None, time=None, link_preview=False, edit_time=None, **args): reply_to = event.reply_to_msg_id or event if event.out and not isinstance(event, MessageService): if edit_time: await sleep(edit_time) if args.get("file") and not event.media: await event.delete() ok = await event.client.send_message( event.chat_id, text, link_preview=link_preview, reply_to=reply_to, **args ) else: try: ok = await event.edit(text, link_preview=link_preview, **args) except MessageNotModifiedError: ok = event else: ok = await event.client.send_message( event.chat_id, text, link_preview=link_preview, reply_to=reply_to, **args ) if time: await sleep(time) return await ok.delete() return ok The provided code snippet includes necessary dependencies for implementing the `heroku_logs` function. Write a Python function `async def heroku_logs(event)` to solve the following problem: post heroku logs Here is the function: async def heroku_logs(event): """ post heroku logs """ from .. import LOGS xx = await eor(event, "`Processing...`") if not (Var.HEROKU_API and Var.HEROKU_APP_NAME): return await xx.edit( "Please set `HEROKU_APP_NAME` and `HEROKU_API` in vars." ) try: app = (heroku3.from_key(Var.HEROKU_API)).app(Var.HEROKU_APP_NAME) except BaseException as se: LOGS.info(se) return await xx.edit( "`HEROKU_API` and `HEROKU_APP_NAME` is wrong! Kindly re-check in config vars." ) await xx.edit("`Downloading Logs...`") ok = app.get_log() with open("ultroid-heroku.log", "w") as log: log.write(ok) await event.client.send_file( event.chat_id, file="ultroid-heroku.log", thumb=ULTConfig.thumb, caption="**Ultroid Heroku Logs.**", ) os.remove("ultroid-heroku.log") await xx.delete()
post heroku logs
5,713
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable async def def_logs(ult, file): await ult.respond( "**Ultroid Logs.**", file=file, thumb=ULTConfig.thumb, )
null
5,714
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable async def bash(cmd, run_code=0): """ run any command in subprocess and get output or error.""" process = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await process.communicate() err = stderr.decode().strip() or None out = stdout.decode().strip() if not run_code and err: if match := re.match("\/bin\/sh: (.*): ?(\w+): not found", err): return out, f"{match.group(2).upper()}_NOT_FOUND" return out, err The provided code snippet includes necessary dependencies for implementing the `updateme_requirements` function. Write a Python function `async def updateme_requirements()` to solve the following problem: Update requirements.. Here is the function: async def updateme_requirements(): """Update requirements..""" await bash( f"{sys.executable} -m pip install --no-cache-dir -r requirements.txt" )
Update requirements..
5,715
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable async def progress(current, total, event, start, type_of_ps, file_name=None): now = time.time() if No_Flood.get(event.chat_id): if No_Flood[event.chat_id].get(event.id): if (now - No_Flood[event.chat_id][event.id]) < 1.1: return else: No_Flood[event.chat_id].update({event.id: now}) else: No_Flood.update({event.chat_id: {event.id: now}}) diff = time.time() - start if round(diff % 10.00) == 0 or current == total: percentage = current * 100 / total speed = current / diff time_to_completion = round((total - current) / speed) * 1000 progress_str = "`[{0}{1}] {2}%`\n\n".format( "".join("●" for i in range(math.floor(percentage / 5))), "".join("" for i in range(20 - math.floor(percentage / 5))), round(percentage, 2), ) tmp = ( progress_str + "`{0} of {1}`\n\n`✦ Speed: {2}/s`\n\n`✦ ETA: {3}`\n\n".format( humanbytes(current), humanbytes(total), humanbytes(speed), time_formatter(time_to_completion), ) ) if file_name: await event.edit( "`✦ {}`\n\n`File Name: {}`\n\n{}".format(type_of_ps, file_name, tmp) ) else: await event.edit("`✦ {}`\n\n{}".format(type_of_ps, tmp)) async def uploader(file, name, taime, event, msg): with open(file, "rb") as f: result = await uploadable( client=event.client, file=f, filename=name, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, event, taime, msg, ), ), ) return result
null
5,716
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable def mediainfo(media): xx = str((str(media)).split("(", maxsplit=1)[0]) m = "" if xx == "MessageMediaDocument": mim = media.document.mime_type if mim == "application/x-tgsticker": m = "sticker animated" elif "image" in mim: if mim == "image/webp": m = "sticker" elif mim == "image/gif": m = "gif as doc" else: m = "pic as doc" elif "video" in mim: if "DocumentAttributeAnimated" in str(media): m = "gif" elif "DocumentAttributeVideo" in str(media): i = str(media.document.attributes[0]) if "supports_streaming=True" in i: m = "video" m = "video as doc" else: m = "video" elif "audio" in mim: m = "audio" else: m = "document" elif xx == "MessageMediaPhoto": m = "pic" elif xx == "MessageMediaWebPage": m = "web" return m
null
5,717
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module try: import heroku3 except ImportError: heroku3 = None import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable class Var: async def eor(event, text=None, time=None, link_preview=False, edit_time=None, **args): async def restart(ult=None): if Var.HEROKU_APP_NAME and Var.HEROKU_API: try: Heroku = heroku3.from_key(Var.HEROKU_API) app = Heroku.apps()[Var.HEROKU_APP_NAME] if ult: await ult.edit("`Restarting your app, please wait for a minute!`") app.restart() except BaseException as er: if ult: return await eor( ult, "`HEROKU_API` or `HEROKU_APP_NAME` is wrong! Kindly re-check in config vars.", ) LOGS.exception(er) else: if len(sys.argv) == 1: os.execl(sys.executable, sys.executable, "-m", "pyUltroid") else: os.execl( sys.executable, sys.executable, "-m", "pyUltroid", sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], )
null
5,718
import asyncio import math import os import re import sys import time from traceback import format_exc from urllib.parse import unquote from urllib.request import urlretrieve from .. import run_as_module try: import heroku3 except ImportError: heroku3 = None import asyncio import multiprocessing from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from telethon.helpers import _maybe_await from telethon.tl import types from telethon.utils import get_display_name from .._misc import CMD_HELP from .._misc._wrappers import eod, eor from ..exceptions import DependencyMissingError from . import * from ..version import ultroid_version from .FastTelethon import download_file as downloadable from .FastTelethon import upload_file as uploadable class Var: async def eor(event, text=None, time=None, link_preview=False, edit_time=None, **args): async def shutdown(ult): from .. import HOSTED_ON, LOGS ult = await eor(ult, "Shutting Down") if HOSTED_ON == "heroku": if not (Var.HEROKU_APP_NAME and Var.HEROKU_API): return await ult.edit("Please Fill `HEROKU_APP_NAME` and `HEROKU_API`") dynotype = os.getenv("DYNO").split(".")[0] try: Heroku = heroku3.from_key(Var.HEROKU_API) app = Heroku.apps()[Var.HEROKU_APP_NAME] await ult.edit("`Shutting Down your app, please wait for a minute!`") app.process_formation()[dynotype].scale(0) except BaseException as e: LOGS.exception(e) return await ult.edit( "`HEROKU_API` and `HEROKU_APP_NAME` is wrong! Kindly re-check in config vars." ) else: sys.exit()
null
5,719
import glob import os import re import time from telethon import Button from yt_dlp import YoutubeDL from .. import LOGS, udB from .helper import download_file, humanbytes, run_async, time_formatter from .tools import set_attributes 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 def humanbytes(size): if not size: return "0 B" for unit in ["", "K", "M", "G", "T"]: if size < 1024: break size /= 1024 if isinstance(size, int): size = f"{size}{unit}B" elif isinstance(size, float): size = f"{size:.2f}{unit}B" return size async def ytdl_progress(k, start_time, event): if k["status"] == "error": return await event.edit("error") while k["status"] == "downloading": text = ( f"`Downloading: {k['filename']}\n" + f"Total Size: {humanbytes(k['total_bytes'])}\n" + f"Downloaded: {humanbytes(k['downloaded_bytes'])}\n" + f"Speed: {humanbytes(k['speed'])}/s\n" + f"ETA: {time_formatter(k['eta']*1000)}`" ) if round((time.time() - start_time) % 10.0) == 0: try: await event.edit(text) except Exception as ex: LOGS.error(f"ytdl_progress: {ex}")
null
5,720
import glob import os import re import time from telethon import Button from yt_dlp import YoutubeDL from .. import LOGS, udB from .helper import download_file, humanbytes, run_async, time_formatter from .tools import set_attributes def get_videos_link(url): to_return = [] regex = re.search(r"\?list=([(\w+)\-]*)", url) if not regex: return to_return playlist_id = regex.group(1) videos = Playlist(playlist_id) for vid in videos.videos: link = re.search(r"\?v=([(\w+)\-]*)", vid["link"]).group(1) to_return.append(f"https://youtube.com/watch?v={link}") return to_return
null
5,721
from . import get_help import os from pyUltroid.startup.loader import load_addons from . import LOGS, async_searcher, eod, get_string, safeinstall, ultroid_cmd, un_plug async def install(event): await safeinstall(event)
null
5,722
from . import get_help import os from pyUltroid.startup.loader import load_addons from . import LOGS, async_searcher, eod, get_string, safeinstall, ultroid_cmd, un_plug async def unload(event): shortname = event.pattern_match.group(1).strip() if not shortname: await event.eor(get_string("core_9")) return lsd = os.listdir("addons") zym = f"{shortname}.py" if zym in lsd: try: un_plug(shortname) await event.eor(f"**Uɴʟᴏᴀᴅᴇᴅ** `{shortname}` **Sᴜᴄᴄᴇssғᴜʟʟʏ.**", time=3) except Exception as ex: LOGS.exception(ex) return await event.eor(str(ex)) elif zym in os.listdir("plugins"): return await event.eor(get_string("core_11"), time=3) else: await event.eor(f"**Nᴏ Pʟᴜɢɪɴ Nᴀᴍᴇᴅ** `{shortname}`", time=3)
null
5,723
from . import get_help import os from pyUltroid.startup.loader import load_addons from . import LOGS, async_searcher, eod, get_string, safeinstall, ultroid_cmd, un_plug async def uninstall(event): shortname = event.pattern_match.group(1).strip() if not shortname: await event.eor(get_string("core_13")) return lsd = os.listdir("addons") zym = f"{shortname}.py" if zym in lsd: try: un_plug(shortname) await event.eor(f"**Uɴɪɴsᴛᴀʟʟᴇᴅ** `{shortname}` **Sᴜᴄᴄᴇssғᴜʟʟʏ.**", time=3) os.remove(f"addons/{shortname}.py") except Exception as ex: return await event.eor(str(ex)) elif zym in os.listdir("plugins"): return await event.eor(get_string("core_15"), time=3) else: return await event.eor(f"**Nᴏ Pʟᴜɢɪɴ Nᴀᴍᴇᴅ** `{shortname}`", time=3)
null
5,724
from . import get_help import os from pyUltroid.startup.loader import load_addons from . import LOGS, async_searcher, eod, get_string, safeinstall, ultroid_cmd, un_plug async def load(event): shortname = event.pattern_match.group(1).strip() if not shortname: await event.eor(get_string("core_16")) return try: try: un_plug(shortname) except BaseException: pass load_addons(f"addons/{shortname}.py") await event.eor(get_string("core_17").format(shortname), time=3) except Exception as e: LOGS.exception(e) await eod( event, get_string("core_18").format(shortname, e), time=3, )
null
5,725
from . import get_help import os from pyUltroid.startup.loader import load_addons from . import LOGS, async_searcher, eod, get_string, safeinstall, ultroid_cmd, un_plug async def get_the_addons_lol(event): thelink = event.pattern_match.group(1).strip() xx = await event.eor(get_string("com_1")) fool = get_string("gas_1") if thelink is None: return await xx.eor(fool, time=10) split_thelink = thelink.split("/") if not ("raw" in thelink and thelink.endswith(".py")): return await xx.eor(fool, time=10) name_of_it = split_thelink[-1] plug = await async_searcher(thelink) fil = f"addons/{name_of_it}" await xx.edit("Packing the codes...") with open(fil, "w", encoding="utf-8") as uult: uult.write(plug) await xx.edit("Packed. Now loading the plugin..") shortname = name_of_it.split(".")[0] try: load_addons(fil) await xx.eor(get_string("core_17").format(shortname), time=15) except Exception as e: LOGS.exception(e) await eod( xx, get_string("core_18").format(shortname, e), time=3, )
null
5,726
import os import time from datetime import datetime as dt from random import choice import pytz from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeVideo from pyUltroid.fns.tools import get_google_images, metadata from . import ( HNDLR, ULTConfig, async_searcher, bash, downloader, eod, get_string, mediainfo, quotly, ultroid_bot, ultroid_cmd, uploader, ) from .beautify import all_col File = [] async def daudtoid(e): if not e.reply_to: return await eod(e, get_string("spcltool_1")) r = await e.get_reply_message() if not mediainfo(r.media).startswith(("audio", "video")): return await eod(e, get_string("spcltool_1")) xxx = await e.eor(get_string("com_1")) dl = r.file.name or "input.mp4" c_time = time.time() file = await downloader( f"resources/downloads/{dl}", r.media.document, xxx, c_time, f"Downloading {dl}...", ) File.append(file.name) await xxx.edit(get_string("spcltool_2"))
null
5,727
import os import time from datetime import datetime as dt from random import choice import pytz from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeVideo from pyUltroid.fns.tools import get_google_images, metadata from . import ( HNDLR, ULTConfig, async_searcher, bash, downloader, eod, get_string, mediainfo, quotly, ultroid_bot, ultroid_cmd, uploader, ) from .beautify import all_col File = [] from .. import * async def metadata(file): out, _ = await bash(f'mediainfo "{_unquote_text(file)}" --Output=JSON') if _ and _.endswith("NOT_FOUND"): raise DependencyMissingError( f"'{_}' is not installed!\nInstall it to use this command." ) data = {} _info = json.loads(out)["media"]["track"] info = _info[0] if info.get("Format") in ["GIF", "PNG"]: return { "height": _info[1]["Height"], "width": _info[1]["Width"], "bitrate": _info[1].get("BitRate", 320), } if info.get("AudioCount"): data["title"] = info.get("Title", file) data["performer"] = info.get("Performer") or udB.get_key("artist") or "" if info.get("VideoCount"): data["height"] = int(float(_info[1].get("Height", 720))) data["width"] = int(float(_info[1].get("Width", 1280))) data["bitrate"] = int(_info[1].get("BitRate", 320)) data["duration"] = int(float(info.get("Duration", 0))) return data async def adaudroid(e): if not e.reply_to: return await eod(e, get_string("spcltool_3")) r = await e.get_reply_message() if not mediainfo(r.media).startswith("video"): return await eod(e, get_string("spcltool_3")) if not (File and os.path.exists(File[0])): return await e.edit(f"`First reply an audio with {HNDLR}addaudio`") xxx = await e.eor(get_string("com_1")) dl = r.file.name or "input.mp4" c_time = time.time() file = await downloader( f"resources/downloads/{dl}", r.media.document, xxx, c_time, f"Downloading {dl}...", ) await xxx.edit(get_string("spcltool_5")) await bash( f'ffmpeg -i "{file.name}" -i "{File[0]}" -shortest -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 output.mp4' ) out = "output.mp4" mmmm = await uploader(out, out, time.time(), xxx, f"Uploading {out}...") data = await metadata(out) width = data["width"] height = data["height"] duration = data["duration"] attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, supports_streaming=True ) ] await e.client.send_file( e.chat_id, mmmm, thumb=ULTConfig.thumb, attributes=attributes, force_document=False, reply_to=e.reply_to_msg_id, ) await xxx.delete() os.remove(out) os.remove(file.name) File.clear() os.remove(File[0])
null
5,728
import os import time from datetime import datetime as dt from random import choice import pytz from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeVideo from pyUltroid.fns.tools import get_google_images, metadata from . import ( HNDLR, ULTConfig, async_searcher, bash, downloader, eod, get_string, mediainfo, quotly, ultroid_bot, ultroid_cmd, uploader, ) from .beautify import all_col async def hbd(event): match = event.pattern_match.group(1).strip() if not match: return await event.eor(get_string("spcltool_6")) if event.reply_to_msg_id: kk = await event.get_reply_message() nam = await kk.get_sender() name = nam.first_name else: name = ultroid_bot.me.first_name zn = pytz.timezone("Asia/Kolkata") abhi = dt.now(zn) kk = match.split("/") p = kk[0] r = kk[1] s = kk[2] day = int(p) month = r try: jn = dt.strptime(match, "%d/%m/%Y") except BaseException: return await event.eor(get_string("spcltool_6")) jnm = zn.localize(jn) zinda = abhi - jnm barsh = (zinda.total_seconds()) / (365.242 * 24 * 3600) saal = int(barsh) mash = (barsh - saal) * 12 mahina = int(mash) divas = (mash - mahina) * (365.242 / 12) din = int(divas) samay = (divas - din) * 24 ghanta = int(samay) pehl = (samay - ghanta) * 60 mi = int(pehl) sec = (pehl - mi) * 60 slive = int(sec) y = int(s) + saal + 1 m = int(r) brth = dt(y, m, day) cm = dt(abhi.year, brth.month, brth.day) ish = (cm - abhi.today()).days + 1 dan = ish if dan == 0: hp = "`Happy BirthDay To U🎉🎊`" elif dan < 0: okk = 365 + ish hp = f"{okk} Days Left 🥳" elif dan > 0: hp = f"{ish} Days Left 🥳" if month == "01": sign = "Capricorn" if (day < 20) else "Aquarius" elif month == "02": sign = "Aquarius" if (day < 19) else "Pisces" elif month == "03": sign = "Pisces" if (day < 21) else "Aries" elif month == "04": sign = "Aries" if (day < 20) else "Taurus" elif month == "05": sign = "Taurus" if (day < 21) else "Gemini" elif month == "06": sign = "Gemini" if (day < 21) else "Cancer" elif month == "07": sign = "Cancer" if (day < 23) else "Leo" elif month == "08": sign = "Leo" if (day < 23) else "Virgo" elif month == "09": sign = "Virgo" if (day < 23) else "Libra" elif month == "10": sign = "Libra" if (day < 23) else "Scorpio" elif month == "11": sign = "Scorpio" if (day < 22) else "Sagittarius" elif month == "12": sign = "Sagittarius" if (day < 22) else "Capricorn" json = await async_searcher( f"https://aztro.sameerkumar.website/?sign={sign}&day=today", post=True, re_json=True, ) dd = json.get("current_date") ds = json.get("description") lt = json.get("lucky_time") md = json.get("mood") cl = json.get("color") ln = json.get("lucky_number") await event.delete() await event.client.send_message( event.chat_id, f""" Name -: {name} D.O.B -: {match} Lived -: {saal}yr, {mahina}m, {din}d, {ghanta}hr, {mi}min, {slive}sec Birthday -: {hp} Zodiac -: {sign} **Horoscope On {dd} -** `{ds}` Lucky Time :- {lt} Lucky Number :- {ln} Lucky Color :- {cl} Mood :- {md} """, reply_to=event.reply_to_msg_id, )
null
5,729
import os import time from datetime import datetime as dt from random import choice import pytz from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeVideo from pyUltroid.fns.tools import get_google_images, metadata from . import ( HNDLR, ULTConfig, async_searcher, bash, downloader, eod, get_string, mediainfo, quotly, ultroid_bot, ultroid_cmd, uploader, ) from .beautify import all_col async def _(event): x = event.pattern_match.group(1).strip() if not x: return await event.eor("`Give something to search`") uu = await event.eor(get_string("com_1")) z = bs( await async_searcher(f"https://combot.org/telegram/stickers?q={x}"), "html.parser", ) packs = z.find_all("div", "sticker-pack__header") sticks = { c.a["href"]: c.find("div", {"class": "sticker-pack__title"}).text for c in packs } if not sticks: return await uu.edit(get_string("spcltool_9")) a = "SᴛɪᴄᴋEʀs Aᴠᴀɪʟᴀʙʟᴇ ~\n\n" for _, value in sticks.items(): a += f"<a href={_}>{value}</a>\n" await uu.edit(a, parse_mode="html")
null
5,730
import os import time from datetime import datetime as dt from random import choice import pytz from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeVideo from pyUltroid.fns.tools import get_google_images, metadata from . import ( HNDLR, ULTConfig, async_searcher, bash, downloader, eod, get_string, mediainfo, quotly, ultroid_bot, ultroid_cmd, uploader, ) from .beautify import all_col 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 wall(event): inp = event.pattern_match.group(1).strip() if not inp: return await event.eor("`Give me something to search..`") nn = await event.eor(get_string("com_1")) query = f"hd {inp}" images = await get_google_images(query) for z in range(5): await event.client.send_file(event.chat_id, file=images[z]["original"]) await nn.delete()
null
5,731
import os import time from datetime import datetime as dt from random import choice import pytz from bs4 import BeautifulSoup as bs from telethon.tl.types import DocumentAttributeVideo from pyUltroid.fns.tools import get_google_images, metadata from . import ( HNDLR, ULTConfig, async_searcher, bash, downloader, eod, get_string, mediainfo, quotly, ultroid_bot, ultroid_cmd, uploader, ) from .beautify import all_col ) ) async def quott_(event): match = event.pattern_match.group(1).strip() if not event.is_reply: return await event.eor("`Reply to Message..`") msg = await event.eor(get_string("com_1")) reply = await event.get_reply_message() replied_to, reply_ = None, None if match: spli_ = match.split(maxsplit=1) if (spli_[0] in ["r", "reply"]) or ( spli_[0].isdigit() and int(spli_[0]) in range(1, 21) ): if spli_[0].isdigit(): if not event.client._bot: reply_ = await event.client.get_messages( event.chat_id, min_id=event.reply_to_msg_id - 1, reverse=True, limit=int(spli_[0]), ) else: id_ = reply.id reply_ = [] for msg_ in range(id_, id_ + int(spli_[0])): msh = await event.client.get_messages(event.chat_id, ids=msg_) if msh: reply_.append(msh) else: replied_to = await reply.get_reply_message() try: match = spli_[1] except IndexError: match = None user = None if not reply_: reply_ = reply if match: match = match.split(maxsplit=1) if match: if match[0].startswith("@") or match[0].isdigit(): try: match_ = await event.client.parse_id(match[0]) user = await event.client.get_entity(match_) except ValueError: pass match = match[1] if len(match) == 2 else None else: match = match[0] if match == "random": match = choice(all_col) try: file = await quotly.create_quotly( reply_, bg=match, reply=replied_to, sender=user ) except Exception as er: return await msg.edit(str(er)) message = await reply.reply("Quotly by Ultroid", file=file) os.remove(file) await msg.delete() return message
null
5,732
import os from htmlwebshot import WebShot from PIL import Image, ImageDraw, ImageFont from . import async_searcher, eod, get_string, text_set, ultroid_cmd async def ghtml(e): if txt := e.pattern_match.group(1).strip(): link = e.text.split(maxsplit=1)[1] else: return await eod(e, "`Either reply to any file or give any text`") k = await async_searcher(link) with open("file.html", "w+") as f: f.write(k) await e.reply(file="file.html")
null
5,733
import os from htmlwebshot import WebShot from PIL import Image, ImageDraw, ImageFont from . import async_searcher, eod, get_string, text_set, ultroid_cmd async def f2i(e): txt = e.pattern_match.group(1).strip() html = None if txt: html = e.text.split(maxsplit=1)[1] elif e.reply_to: r = await e.get_reply_message() if r.media: html = await e.client.download_media(r.media) elif r.text: html = r.text if not html: return await eod(e, "`Either reply to any file or give any text`") html = html.replace("\n", "<br>") shot = WebShot(quality=85) css = "body {background: white;} p {color: red;}" pic = await shot.create_pic_async(html=html, css=css) await e.reply(file=pic, force_document=True) os.remove(pic) if os.path.exists(html): os.remove(html)
null
5,734
import os from htmlwebshot import WebShot from PIL import Image, ImageDraw, ImageFont from . import async_searcher, eod, get_string, text_set, ultroid_cmd async def writer(e): if e.reply_to: reply = await e.get_reply_message() text = reply.message elif e.pattern_match.group(1).strip(): text = e.text.split(maxsplit=1)[1] else: return await eod(e, get_string("writer_1")) k = await e.eor(get_string("com_1")) img = Image.open("resources/extras/template.jpg") draw = ImageDraw.Draw(img) font = ImageFont.truetype("resources/fonts/assfont.ttf", 30) x, y = 150, 140 lines = text_set(text) line_height = font.getsize("hg")[1] for line in lines: draw.text((x, y), line, fill=(1, 22, 55), font=font) y = y + line_height - 5 file = "ult.jpg" img.save(file) await e.reply(file=file) os.remove(file) await k.delete()
null
5,735
from . import get_help import asyncio from telegraph import upload_file as uf from telethon import events from pyUltroid.dB.afk_db import add_afk, del_afk, is_afk from pyUltroid.dB.base import KeyManager from . import ( LOG_CHANNEL, NOSPAM_CHAT, Redis, asst, get_string, mediainfo, udB, ultroid_bot, ultroid_cmd, ) old_afk_msg = [] async def remove_afk(event): if event.is_private and udB.get_key("PMSETTING") and not is_approved(event.chat_id): return elif "afk" in event.text.lower(): return elif event.chat_id in NOSPAM_CHAT: return if is_afk(): _, _, _, afk_time = is_afk() del_afk() off = await event.reply(get_string("afk_1").format(afk_time)) await asst.send_message(LOG_CHANNEL, get_string("afk_2").format(afk_time)) for x in old_afk_msg: try: await x.delete() except BaseException: pass await asyncio.sleep(10) await off.delete() async def on_afk(event): if event.is_private and Redis("PMSETTING") and not is_approved(event.chat_id): return elif "afk" in event.text.lower(): return elif not is_afk(): return if event.chat_id in NOSPAM_CHAT: return sender = await event.get_sender() if sender.bot or sender.verified: return text, media_type, media, afk_time = is_afk() msg1, msg2 = None, None if text and media: if "sticker" in media_type: msg1 = await event.reply(file=media) msg2 = await event.reply(get_string("afk_3").format(afk_time, text)) else: msg1 = await event.reply( get_string("afk_3").format(afk_time, text), file=media ) elif media: if "sticker" in media_type: msg1 = await event.reply(file=media) msg2 = await event.reply(get_string("afk_4").format(afk_time)) else: msg1 = await event.reply(get_string("afk_4").format(afk_time), file=media) elif text: msg1 = await event.reply(get_string("afk_3").format(afk_time, text)) else: msg1 = await event.reply(get_string("afk_4").format(afk_time)) for x in old_afk_msg: try: await x.delete() except BaseException: pass old_afk_msg.append(msg1) if msg2: old_afk_msg.append(msg2) def add_afk(msg, media_type, media): time = dt.now().strftime("%b %d %Y %I:%M:%S%p") udB.set_key("AFK_DB", [msg, media_type, media, time]) return def is_afk(): afk = get_stuff() if afk: start_time = dt.strptime(afk[3], "%b %d %Y %I:%M:%S%p") afk_since = str(dt.now().replace(microsecond=0) - start_time) return afk[0], afk[1], afk[2], afk_since return False async def set_afk(event): if event.client._bot or is_afk(): return text, media, media_type = None, None, None if event.pattern_match.group(1).strip(): text = event.text.split(maxsplit=1)[1] reply = await event.get_reply_message() if reply: if reply.text and not text: text = reply.text if reply.media: media_type = mediainfo(reply.media) if media_type.startswith(("pic", "gif")): file = await event.client.download_media(reply.media) iurl = uf(file) media = f"https://graph.org{iurl[0]}" else: media = reply.file.id await event.eor("`Done`", time=2) add_afk(text, media_type, media) ultroid_bot.add_handler(remove_afk, events.NewMessage(outgoing=True)) ultroid_bot.add_handler( on_afk, events.NewMessage( incoming=True, func=lambda e: bool(e.mentioned or e.is_private) ), ) msg1, msg2 = None, None if text and media: if "sticker" in media_type: msg1 = await ultroid_bot.send_file(event.chat_id, file=media) msg2 = await ultroid_bot.send_message( event.chat_id, get_string("afk_5").format(text) ) else: msg1 = await ultroid_bot.send_message( event.chat_id, get_string("afk_5").format(text), file=media ) elif media: if "sticker" in media_type: msg1 = await ultroid_bot.send_file(event.chat_id, file=media) msg2 = await ultroid_bot.send_message(event.chat_id, get_string("afk_6")) else: msg1 = await ultroid_bot.send_message( event.chat_id, get_string("afk_6"), file=media ) elif text: msg1 = await event.respond(get_string("afk_5").format(text)) else: msg1 = await event.respond(get_string("afk_6")) old_afk_msg.append(msg1) if msg2: old_afk_msg.append(msg2) return await asst.send_message(LOG_CHANNEL, msg2.text) await asst.send_message(LOG_CHANNEL, msg1.text)
null
5,736
import glob import os from pyUltroid.fns.tools import set_attributes from . import ( ULTConfig, bash, duration_s, eod, genss, get_string, mediainfo, stdr, ultroid_cmd, ) from .. import * async def set_attributes(file): async def gen_sample(e): sec = e.pattern_match.group(1).strip() stime = int(sec) if sec and sec.isdigit() else 30 vido = await e.get_reply_message() if vido and vido.media and "video" in mediainfo(vido.media): msg = await e.eor(get_string("com_1")) file, _ = await e.client.fast_downloader( vido.document, show_progress=True, event=msg ) file_name = (file.name).split("/")[-1] out = file_name.replace(file_name.split(".")[-1], "_sample.mkv") xxx = await msg.edit(f"Generating Sample of `{stime}` seconds...") ss, dd = await duration_s(file.name, stime) cmd = f'ffmpeg -i "{file.name}" -preset ultrafast -ss {ss} -to {dd} -codec copy -map 0 "{out}" -y' await bash(cmd) os.remove(file.name) attributes = await set_attributes(out) mmmm, _ = await e.client.fast_uploader( out, show_progress=True, event=xxx, to_delete=True ) caption = f"A Sample Video Of `{stime}` seconds" await e.client.send_file( e.chat_id, mmmm, thumb=ULTConfig.thumb, caption=caption, attributes=attributes, force_document=False, reply_to=e.reply_to_msg_id, ) await xxx.delete() else: await e.eor(get_string("audiotools_8"), time=5)
null
5,737
import glob import os from pyUltroid.fns.tools import set_attributes from . import ( ULTConfig, bash, duration_s, eod, genss, get_string, mediainfo, stdr, ultroid_cmd, ) async def gen_shots(e): ss = e.pattern_match.group(1).strip() shot = int(ss) if ss and ss.isdigit() else 5 vido = await e.get_reply_message() if vido and vido.media and "video" in mediainfo(vido.media): msg = await e.eor(get_string("com_1")) file, _ = await e.client.fast_downloader( vido.document, show_progress=True, event=msg ) xxx = await msg.edit(f"Generating `{shot}` screenshots...") await bash("rm -rf ss && mkdir ss") cmd = f'ffmpeg -i "{file.name}" -vf fps=0.009 -vframes {shot} "ss/pic%01d.png"' await bash(cmd) os.remove(file.name) pic = glob.glob("ss/*") text = f"Uploaded {len(pic)}/{shot} screenshots" if not pic: text = "`Failed to Take Screenshots..`" pic = None await e.respond(text, file=pic) await bash("rm -rf ss") await xxx.delete()
null
5,738
import glob import os from pyUltroid.fns.tools import set_attributes from . import ( ULTConfig, bash, duration_s, eod, genss, get_string, mediainfo, stdr, ultroid_cmd, ) from .. import * async def set_attributes(file): async def gen_sample(e): sec = e.pattern_match.group(1).strip() if not sec or "-" not in sec: return await eod(e, get_string("audiotools_3")) a, b = sec.split("-") if int(a) >= int(b): return await eod(e, get_string("audiotools_4")) vido = await e.get_reply_message() if vido and vido.media and "video" in mediainfo(vido.media): msg = await e.eor(get_string("audiotools_5")) file, _ = await e.client.fast_downloader( vido.document, show_progress=True, event=msg ) file_name = (file.name).split("/")[-1] out = file_name.replace(file_name.split(".")[-1], "_trimmed.mkv") if int(b) > int(await genss(file.name)): os.remove(file.name) return await eod(msg, get_string("audiotools_6")) ss, dd = stdr(int(a)), stdr(int(b)) xxx = await msg.edit(f"Trimming Video from `{ss}` to `{dd}`...") cmd = f'ffmpeg -i "{file.name}" -preset ultrafast -ss {ss} -to {dd} -codec copy -map 0 "{out}" -y' await bash(cmd) os.remove(file.name) attributes = await set_attributes(out) mmmm, _ = await e.client.fast_uploader( out, show_progress=True, event=msg, to_delete=True ) caption = f"Trimmed Video From `{ss}` To `{dd}`" await e.client.send_file( e.chat_id, mmmm, thumb=ULTConfig.thumb, caption=caption, attributes=attributes, force_document=False, reply_to=e.reply_to_msg_id, ) await xxx.delete() else: await e.eor(get_string("audiotools_8"), time=5)
null
5,739
from . import get_help import os from pyUltroid.dB.filestore_db import del_stored, get_stored_msg, list_all_stored_msgs from pyUltroid.fns.tools import get_file_link from . import HNDLR, asst, get_string, in_pattern, udB, ultroid_bot, ultroid_cmd from .. import * async def get_file_link(msg): from .. import udB msg_id = await msg.forward_to(udB.get_key("LOG_CHANNEL")) await msg_id.reply( "**Message has been stored to generate a shareable link. Do not delete it.**" ) msg_id = msg_id.id msg_hash = secrets.token_hex(nbytes=8) store_msg(msg_hash, msg_id) return msg_hash async def filestoreplg(event): msg = await event.get_reply_message() if not msg: return await event.eor(get_string("fsh_3"), time=10) # allow storing both messages and media. filehash = await get_file_link(msg) link_to_file = f"https://t.me/{asst.me.username}?start={filehash}" await event.eor( get_string("fsh_2").format(link_to_file), link_preview=False, )
null
5,740
from . import get_help import os from pyUltroid.dB.filestore_db import del_stored, get_stored_msg, list_all_stored_msgs from pyUltroid.fns.tools import get_file_link from . import HNDLR, asst, get_string, in_pattern, udB, ultroid_bot, ultroid_cmd def get_stored_msg(hash): def del_stored(hash): async def _(event): match = event.pattern_match.group(1) if not match: return await event.eor("`Give stored film's link to delete.`", time=5) match = match.split("?start=") botusername = match[0].split("/")[-1] if botusername != asst.me.username: return await event.eor( "`Message/Media of provided link was not stored by this bot.`", time=5 ) msg_id = get_stored_msg(match[1]) if not msg_id: return await event.eor( "`Message/Media of provided link was already deleted.`", time=5 ) del_stored(match[1]) await ultroid_bot.delete_messages(udB.get_key("LOG_CHANNEL"), int(msg_id)) await event.eor("__Deleted__")
null
5,741
from . import get_help import os from pyUltroid.dB.filestore_db import del_stored, get_stored_msg, list_all_stored_msgs from pyUltroid.fns.tools import get_file_link from . import HNDLR, asst, get_string, in_pattern, udB, ultroid_bot, ultroid_cmd def list_all_stored_msgs(): all = get_stored() return list(all.keys()) async def liststored(event): files = list_all_stored_msgs() if not files: return await event.eor(get_string("fsh_4"), time=5) msg = "**Stored files:**\n" for c, i in enumerate(files, start=1): msg += f"`{c}`. https://t.me/{asst.me.username}?start={i}\n" if len(msg) > 4095: with open("liststored.txt", "w") as f: f.write(msg.replace("**", "").replace("`", "")) await event.reply(get_string("fsh_1"), file="liststored.txt") os.remove("liststored.txt") return await event.eor(msg, link_preview=False)
null
5,742
from . import get_help import os from pyUltroid.dB.filestore_db import del_stored, get_stored_msg, list_all_stored_msgs from pyUltroid.fns.tools import get_file_link from . import HNDLR, asst, get_string, in_pattern, udB, ultroid_bot, ultroid_cmd def list_all_stored_msgs(): all = get_stored() return list(all.keys()) def get_stored_msg(hash): all = get_stored() if all.get(hash): return all[hash] async def file_short(event): all_ = list_all_stored_msgs() res = [] if all_: LOG_CHA = udB.get_key("LOG_CHANNEL") for msg in all_[:50]: m_id = get_stored_msg(msg) if not m_id: continue message = await asst.get_messages(LOG_CHA, ids=m_id) if not message: continue if message.media: res.append(await event.builder.document(title=msg, file=message.media)) elif message.text: res.append( await event.builder.article(title=message.text, text=message.text) ) if not res: title = "You have no stored file :(" text = f"{title}\n\nRead `{HNDLR}help fileshare` to know how to store." return await event.answer([await event.builder.article(title=title, text=text)]) await event.answer(res, switch_pm="• File Store •", switch_pm_param="start")
null
5,743
import os from . import LOGS from pyUltroid.dB.nsfw_db import is_nsfw, nsfw_chat, rem_nsfw from . import HNDLR, async_searcher, eor, events, udB, ultroid_bot, ultroid_cmd async def nsfw_check(e): if udB.get_key("NSFW"): ultroid_bot.add_handler(nsfw_check, events.NewMessage(incoming=True)) def nsfw_chat(chat, action): async def addnsfw(e): if not udB.get_key("DEEP_API"): return await eor( e, f"Get Api from deepai.org and Add It `{HNDLR}setdb DEEP_API your-api`" ) action = e.pattern_match.group(1).strip() if not action or ("ban" or "kick" or "mute") not in action: action = "mute" nsfw_chat(e.chat_id, action) ultroid_bot.add_handler(nsfw_check, events.NewMessage(incoming=True)) await e.eor("Added This Chat To Nsfw Filter")
null
5,744
import os from . import LOGS from pyUltroid.dB.nsfw_db import is_nsfw, nsfw_chat, rem_nsfw from . import HNDLR, async_searcher, eor, events, udB, ultroid_bot, ultroid_cmd def rem_nsfw(chat): x = get_stuff() if x.get(chat): x.pop(chat) return udB.set_key("NSFW", x) async def remnsfw(e): rem_nsfw(e.chat_id) await e.eor("Removed This Chat from Nsfw Filter.")
null
5,745
from . import get_help import asyncio import glob import os import time from datetime import datetime as dt from aiohttp.client_exceptions import InvalidURL from telethon.errors.rpcerrorlist import MessageNotModifiedError from pyUltroid.fns.helper import time_formatter from pyUltroid.fns.tools import get_chat_and_msgid, set_attributes from . import ( LOGS, ULTConfig, downloader, eor, fast_download, get_all_files, get_string, progress, time_formatter, ultroid_cmd, ) 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 down(event): matched = event.pattern_match.group(1).strip() msg = await event.eor(get_string("udl_4")) if not matched: return await eor(msg, get_string("udl_5"), time=5) try: splited = matched.split(" | ") link = splited[0] filename = splited[1] except IndexError: filename = None s_time = time.time() try: filename, d = await fast_download( link, filename, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, msg, s_time, f"Downloading from {link}", ) ), ) except InvalidURL: return await msg.eor("`Invalid URL provided :(`", time=5) await msg.eor(f"`{filename}` `downloaded in {time_formatter(d*1000)}.`")
null
5,746
from . import get_help import asyncio import glob import os import time from datetime import datetime as dt from aiohttp.client_exceptions import InvalidURL from telethon.errors.rpcerrorlist import MessageNotModifiedError from pyUltroid.fns.helper import time_formatter from pyUltroid.fns.tools import get_chat_and_msgid, set_attributes from . import ( LOGS, ULTConfig, downloader, eor, fast_download, get_all_files, get_string, progress, time_formatter, ultroid_cmd, ) from . import * def time_formatter(milliseconds): from .. import * def get_chat_and_msgid(link): async def download(event): match = event.pattern_match.group(1).strip() if match and "t.me/" in match: chat, msg = get_chat_and_msgid(match) if not (chat and msg): return await event.eor(get_string("gms_1")) match = "" ok = await event.client.get_messages(chat, ids=msg) elif event.reply_to_msg_id: ok = await event.get_reply_message() else: return await event.eor(get_string("cvt_3"), time=8) xx = await event.eor(get_string("com_1")) if not (ok and ok.media): return await xx.eor(get_string("udl_1"), time=5) s = dt.now() k = time.time() if hasattr(ok.media, "document"): file = ok.media.document mime_type = file.mime_type filename = match or ok.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" try: result = await downloader( f"resources/downloads/{filename}", file, xx, k, f"Downloading {filename}...", ) except MessageNotModifiedError as err: return await xx.edit(str(err)) file_name = result.name else: d = "resources/downloads/" file_name = await event.client.download_media( ok, d, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, xx, k, get_string("com_5"), ), ), ) e = dt.now() t = time_formatter(((e - s).seconds) * 1000) await xx.eor(get_string("udl_2").format(file_name, t))
null
5,747
from . import get_help import asyncio import glob import os import time from datetime import datetime as dt from aiohttp.client_exceptions import InvalidURL from telethon.errors.rpcerrorlist import MessageNotModifiedError from pyUltroid.fns.helper import time_formatter from pyUltroid.fns.tools import get_chat_and_msgid, set_attributes from . import ( LOGS, ULTConfig, downloader, eor, fast_download, get_all_files, get_string, progress, time_formatter, ultroid_cmd, ) 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 from .. import * async def set_attributes(file): data = await metadata(file) if not data: return None if "width" in data: return [ DocumentAttributeVideo( duration=data.get("duration", 0), w=data.get("width", 512), h=data.get("height", 512), supports_streaming=True, ) ] ext = "." + file.split(".")[-1] return [ DocumentAttributeAudio( duration=data.get("duration", 0), title=data.get("title", file.split("/")[-1].replace(ext, "")), performer=data.get("performer"), ) ] async def _(event): msg = await event.eor(get_string("com_1")) match = event.pattern_match.group(1) if match: match = match.strip() if not event.out and match == ".env": return await event.reply("`You can't do this...`") stream, force_doc, delete, thumb = ( False, True, False, ULTConfig.thumb, ) if "--stream" in match: stream = True force_doc = False if "--delete" in match: delete = True if "--no-thumb" in match: thumb = None arguments = ["--stream", "--delete", "--no-thumb"] if any(item in match for item in arguments): match = ( match.replace("--stream", "") .replace("--delete", "") .replace("--no-thumb", "") .strip() ) if match.endswith("/"): match += "*" results = glob.glob(match) if not results and os.path.exists(match): results = [match] if not results: try: await event.reply(file=match) return await event.try_delete() except Exception as er: LOGS.exception(er) return await msg.eor(get_string("ls1")) for result in results: if os.path.isdir(result): c, s = 0, 0 for files in get_all_files(result): attributes = None if stream: try: attributes = await set_attributes(files) except KeyError as er: LOGS.exception(er) try: file, _ = await event.client.fast_uploader( files, show_progress=True, event=msg, to_delete=delete ) await event.client.send_file( event.chat_id, file, supports_streaming=stream, force_document=force_doc, thumb=thumb, attributes=attributes, caption=f"`Uploaded` `{files}` `in {time_formatter(_*1000)}`", reply_to=event.reply_to_msg_id or event, ) s += 1 except (ValueError, IsADirectoryError): c += 1 break attributes = None if stream: try: attributes = await set_attributes(result) except KeyError as er: LOGS.exception(er) file, _ = await event.client.fast_uploader( result, show_progress=True, event=msg, to_delete=delete ) await event.client.send_file( event.chat_id, file, supports_streaming=stream, force_document=force_doc, thumb=thumb, attributes=attributes, caption=f"`Uploaded` `{result}` `in {time_formatter(_*1000)}`", ) await msg.try_delete()
null
5,748
from . import get_help import re from . import Redis, eor, get_string, udB, ultroid_cmd async def _(ult): match = ult.pattern_match.group(1).strip() if not match: return await ult.eor("Provide key and value to set!") try: delim = " " if re.search("[|]", match) is None else " | " data = match.split(delim, maxsplit=1) if data[0] in ["--extend", "-e"]: data = data[1].split(maxsplit=1) data[1] = f"{str(udB.get_key(data[0]))} {data[1]}" udB.set_key(data[0], data[1]) await ult.eor( f"**DB Key Value Pair Updated\nKey :** `{data[0]}`\n**Value :** `{data[1]}`" ) except BaseException: await ult.eor(get_string("com_7"))
null
5,749
from . import get_help import re from . import Redis, eor, get_string, udB, ultroid_cmd async def _(ult): key = ult.pattern_match.group(1).strip() if not key: return await ult.eor("Give me a key name to delete!", time=5) _ = key.split(maxsplit=1) try: if _[0] == "-m": for key in _[1].split(): k = udB.del_key(key) key = _[1] else: k = udB.del_key(key) if k == 0: return await ult.eor("`No Such Key.`") await ult.eor(f"`Successfully deleted key {key}`") except BaseException: await ult.eor(get_string("com_7"))
null
5,750
from . import get_help import re from . import Redis, eor, get_string, udB, ultroid_cmd async def _(ult): match = ult.pattern_match.group(1).strip() if not match: return await ult.eor("`Provide Keys name to rename..`") delim = " " if re.search("[|]", match) is None else " | " data = match.split(delim) if Redis(data[0]): try: udB.rename(data[0], data[1]) await eor( ult, f"**DB Key Rename Successful\nOld Key :** `{data[0]}`\n**New Key :** `{data[1]}`", ) except BaseException: await ult.eor(get_string("com_7")) else: await ult.eor("Key not found")
null
5,751
import os import time from datetime import datetime as dt from pyUltroid.fns.tools import set_attributes from . import ( LOGS, ULTConfig, bash, downloader, eod, eor, genss, get_help, get_string, humanbytes, mediainfo, stdr, time_formatter, ultroid_cmd, uploader, ) async def vnc(e): if not e.reply_to: return await eod(e, get_string("audiotools_1")) r = await e.get_reply_message() if not mediainfo(r.media).startswith(("audio", "video")): return await eod(e, get_string("spcltool_1")) xxx = await e.eor(get_string("com_1")) file, _ = await e.client.fast_downloader( r.document, ) await xxx.edit(get_string("audiotools_2")) await bash( f"ffmpeg -i '{file.name}' -map 0:a -codec:a libopus -b:a 100k -vbr on out.opus" ) try: await e.client.send_message( e.chat_id, file="out.opus", force_document=False, reply_to=r ) except Exception as er: LOGS.exception(er) return await xxx.edit("`Failed to convert in Voice...`") await xxx.delete() os.remove(file.name) os.remove("out.opus")
null
5,752
import os import time from datetime import datetime as dt from pyUltroid.fns.tools import set_attributes from . import ( LOGS, ULTConfig, bash, downloader, eod, eor, genss, get_help, get_string, humanbytes, mediainfo, stdr, time_formatter, ultroid_cmd, uploader, ) from .. import * async def set_attributes(file): data = await metadata(file) if not data: return None if "width" in data: return [ DocumentAttributeVideo( duration=data.get("duration", 0), w=data.get("width", 512), h=data.get("height", 512), supports_streaming=True, ) ] ext = "." + file.split(".")[-1] return [ DocumentAttributeAudio( duration=data.get("duration", 0), title=data.get("title", file.split("/")[-1].replace(ext, "")), performer=data.get("performer"), ) ] async def trim_aud(e): sec = e.pattern_match.group(1).strip() if not sec or "-" not in sec: return await eod(e, get_string("audiotools_3")) a, b = sec.split("-") if int(a) >= int(b): return await eod(e, get_string("audiotools_4")) vido = await e.get_reply_message() if vido and vido.media and mediainfo(vido.media).startswith(("video", "audio")): if hasattr(vido.media, "document"): vfile = vido.media.document name = vido.file.name else: vfile = vido.media name = "" if not name: name = dt.now().isoformat("_", "seconds") + ".mp4" xxx = await e.eor(get_string("audiotools_5")) c_time = time.time() file = await downloader( f"resources/downloads/{name}", vfile, xxx, c_time, f"Downloading {name}...", ) o_size = os.path.getsize(file.name) d_time = time.time() diff = time_formatter((d_time - c_time) * 1000) file_name = (file.name).split("/")[-1] out = file_name.replace(file_name.split(".")[-1], "_trimmed.aac") if int(b) > int(await genss(file.name)): os.remove(file.name) return await eod(xxx, get_string("audiotools_6")) ss, dd = stdr(int(a)), stdr(int(b)) xxx = await xxx.edit( f"Downloaded `{file.name}` of `{humanbytes(o_size)}` in `{diff}`.\n\nNow Trimming Audio from `{ss}` to `{dd}`..." ) cmd = f'ffmpeg -i "{file.name}" -preset ultrafast -ss {ss} -to {dd} -vn -acodec copy "{out}" -y' await bash(cmd) os.remove(file.name) f_time = time.time() mmmm = await uploader(out, out, f_time, xxx, f"Uploading {out}...") attributes = await set_attributes(out) caption = get_string("audiotools_7").format(ss, dd) await e.client.send_file( e.chat_id, mmmm, thumb=ULTConfig.thumb, caption=caption, attributes=attributes, force_document=False, reply_to=e.reply_to_msg_id, ) await xxx.delete() else: await e.eor(get_string("audiotools_1"), time=5)
null
5,753
import os import time from datetime import datetime as dt from pyUltroid.fns.tools import set_attributes from . import ( LOGS, ULTConfig, bash, downloader, eod, eor, genss, get_help, get_string, humanbytes, mediainfo, stdr, time_formatter, ultroid_cmd, uploader, ) from .. import * async def set_attributes(file): data = await metadata(file) if not data: return None if "width" in data: return [ DocumentAttributeVideo( duration=data.get("duration", 0), w=data.get("width", 512), h=data.get("height", 512), supports_streaming=True, ) ] ext = "." + file.split(".")[-1] return [ DocumentAttributeAudio( duration=data.get("duration", 0), title=data.get("title", file.split("/")[-1].replace(ext, "")), performer=data.get("performer"), ) ] async def ex_aud(e): reply = await e.get_reply_message() if not (reply and reply.media and mediainfo(reply.media).startswith("video")): return await e.eor(get_string("audiotools_8")) name = reply.file.name or "video.mp4" vfile = reply.media.document msg = await e.eor(get_string("com_1")) c_time = time.time() file = await downloader( f"resources/downloads/{name}", vfile, msg, c_time, f"Downloading {name}...", ) out_file = f"{file.name}.aac" cmd = f"ffmpeg -i {file.name} -vn -acodec copy {out_file}" o, err = await bash(cmd) os.remove(file.name) attributes = await set_attributes(out_file) f_time = time.time() try: fo = await uploader(out_file, out_file, f_time, msg, f"Uploading {out_file}...") except FileNotFoundError: return await eor(msg, get_string("audiotools_9")) await e.reply( get_string("audiotools_10"), file=fo, thumb=ULTConfig.thumb, attributes=attributes, ) await msg.delete()
null
5,754
from . import get_help import re from telethon.events import NewMessage as NewMsg from pyUltroid.dB import DEVLIST from pyUltroid.dB.antiflood_db import get_flood, get_flood_limit, rem_flood, set_flood from pyUltroid.fns.admins import admin_check from . import Button, Redis, asst, callback, eod, get_string, ultroid_bot, ultroid_cmd _check_flood = {} if Redis("ANTIFLOOD"): NewMsg( chats=list(get_flood().keys()), ), ) re.compile( "anti_(.*)", ), from .. import * DEVLIST = [ 719195224, # @xditya 1322549723, # @danish_00 1903729401, # @its_buddhhu 1303895686, # @Sipak_OP 611816596, # @Arnab431 1318486004, # @sppidy 803243487, # @hellboi_atul ] def get_flood_limit(chat_id): async def admin_check(event, require=None, silent: bool = False): async def flood_checm(event): count = 1 chat = (await event.get_chat()).title if event.chat_id in _check_flood.keys(): if event.sender_id == list(_check_flood[event.chat_id].keys())[0]: count = _check_flood[event.chat_id][event.sender_id] _check_flood[event.chat_id] = {event.sender_id: count + 1} else: _check_flood[event.chat_id] = {event.sender_id: count} else: _check_flood[event.chat_id] = {event.sender_id: count} if await admin_check(event, silent=True) or getattr(event.sender, "bot", None): return if event.sender_id in DEVLIST: return if _check_flood[event.chat_id][event.sender_id] >= int( get_flood_limit(event.chat_id) ): try: name = event.sender.first_name await event.client.edit_permissions( event.chat_id, event.sender_id, send_messages=False ) del _check_flood[event.chat_id] await event.reply(f"#AntiFlood\n\n{get_string('antiflood_3')}") await asst.send_message( int(Redis("LOG_CHANNEL")), f"#Antiflood\n\n`Muted `[{name}](tg://user?id={event.sender_id})` in {chat}`", buttons=Button.inline( "Unmute", data=f"anti_{event.sender_id}_{event.chat_id}" ), ) except BaseException: pass
null
5,755
from . import get_help import re from telethon.events import NewMessage as NewMsg from pyUltroid.dB import DEVLIST from pyUltroid.dB.antiflood_db import get_flood, get_flood_limit, rem_flood, set_flood from pyUltroid.fns.admins import admin_check from . import Button, Redis, asst, callback, eod, get_string, ultroid_bot, ultroid_cmd async def unmuting(e): ino = (e.data_match.group(1)).decode("UTF-8").split("_") user = int(ino[0]) chat = int(ino[1]) user_name = (await ultroid_bot.get_entity(user)).first_name chat_title = (await ultroid_bot.get_entity(chat)).title await ultroid_bot.edit_permissions(chat, user, send_messages=True) await e.edit( f"#Antiflood\n\n`Unmuted `[{user_name}](tg://user?id={user})` in {chat_title}`" )
null
5,756
from . import get_help import re from telethon.events import NewMessage as NewMsg from pyUltroid.dB import DEVLIST from pyUltroid.dB.antiflood_db import get_flood, get_flood_limit, rem_flood, set_flood from pyUltroid.fns.admins import admin_check from . import Button, Redis, asst, callback, eod, get_string, ultroid_bot, ultroid_cmd def set_flood(chat_id, limit): async def setflood(e): input_ = e.pattern_match.group(1).strip() if not input_: return await e.eor("`What?`", time=5) if not input_.isdigit(): return await e.eor(get_string("com_3"), time=5) if m := set_flood(e.chat_id, input_): return await eod(e, get_string("antiflood_4").format(input_))
null
5,757
from . import get_help import re from telethon.events import NewMessage as NewMsg from pyUltroid.dB import DEVLIST from pyUltroid.dB.antiflood_db import get_flood, get_flood_limit, rem_flood, set_flood from pyUltroid.fns.admins import admin_check from . import Button, Redis, asst, callback, eod, get_string, ultroid_bot, ultroid_cmd _check_flood = {} def rem_flood(chat_id): omk = get_flood() if chat_id in omk.keys(): del omk[chat_id] return udB.set_key("ANTIFLOOD", omk) async def remove_flood(e): hmm = rem_flood(e.chat_id) try: del _check_flood[e.chat_id] except BaseException: pass if hmm: return await e.eor(get_string("antiflood_1"), time=5) await e.eor(get_string("antiflood_2"), time=5)
null
5,758
from . import get_help import re from telethon.events import NewMessage as NewMsg from pyUltroid.dB import DEVLIST from pyUltroid.dB.antiflood_db import get_flood, get_flood_limit, rem_flood, set_flood from pyUltroid.fns.admins import admin_check from . import Button, Redis, asst, callback, eod, get_string, ultroid_bot, ultroid_cmd def get_flood_limit(chat_id): async def getflood(e): if ok := get_flood_limit(e.chat_id): return await e.eor(get_string("antiflood_5").format(ok), time=5) await e.eor(get_string("antiflood_2"), time=5)
null
5,759
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.notes_db import add_note, get_notes, list_note, rem_note 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 notes(e): def add_note(chat, word, msg, media, button): from .. import * def get_msg_button(texts: str): def format_btn(buttons: list): async def an(e): wrd = (e.pattern_match.group(1).strip()).lower() wt = await e.get_reply_message() chat = e.chat_id if not (wt and wrd): return await e.eor(get_string("notes_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 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_note(chat, wrd, txt, m, btn) else: add_note(chat, wrd, None, m, btn) else: txt = wt.text if not btn: txt, btn = get_msg_button(wt.text) add_note(chat, wrd, txt, None, btn) await e.eor(get_string("notes_2").format(wrd)) ultroid_bot.add_handler(notes, events.NewMessage())
null
5,760
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.notes_db import add_note, get_notes, list_note, rem_note 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_note(chat, word): async def rn(e): wrd = (e.pattern_match.group(1).strip()).lower() chat = e.chat_id if not wrd: return await e.eor(get_string("notes_3"), time=5) if wrd.startswith("#"): wrd = wrd.replace("#", "") rem_note(int(chat), wrd) await e.eor(f"Done Note: `#{wrd}` Removed.")
null
5,761
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.notes_db import add_note, get_notes, list_note, rem_note 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_note(chat): ok = get_stuff() if ok.get(int(chat)): return "".join(f"👉 #{z}\n" for z in ok[chat]) async def lsnote(e): if x := list_note(e.chat_id): sd = "Notes Found In This Chats Are\n\n" return await e.eor(sd + x) await e.eor(get_string("notes_5"))
null
5,762
from pyUltroid.dB.warn_db import add_warn, reset_warn, warns from . import eor, get_string, inline_mention, udB, ultroid_cmd def add_warn(chat, user, count, reason): x = get_stuff() try: x[chat].update({user: [count, reason]}) except BaseException: x.update({chat: {user: [count, reason]}}) return udB.set_key("WARNS", x) def warns(chat, user): x = get_stuff() try: count, reason = x[chat][user][0], x[chat][user][1] return count, reason except BaseException: return 0, None def reset_warn(chat, user): x = get_stuff() try: x[chat].pop(user) return udB.set_key("WARNS", x) except BaseException: return async def warn(e): ultroid_bot = e.client reply = await e.get_reply_message() if len(e.text) > 5 and " " not in e.text[5]: return if reply: user = reply.sender_id reason = e.text[5:] if e.pattern_match.group(1).strip() else "unknown" else: try: user = e.text.split()[1] if user.startswith("@"): ok = await ultroid_bot.get_entity(user) user = ok.id else: user = int(user) except BaseException: return await e.eor("Reply To A User", time=5) try: reason = e.text.split(maxsplit=2)[-1] except BaseException: reason = "unknown" count, r = warns(e.chat_id, user) r = f"{r}|$|{reason}" if r else reason try: x = udB.get_key("SETWARN") number, action = int(x.split()[0]), x.split()[1] except BaseException: number, action = 3, "kick" if ("ban" or "kick" or "mute") not in action: action = "kick" if count + 1 >= number: if "ban" in action: try: await ultroid_bot.edit_permissions(e.chat_id, user, view_messages=False) except BaseException: return await e.eor("`Something Went Wrong.`", time=5) elif "kick" in action: try: await ultroid_bot.kick_participant(e.chat_id, user) except BaseException: return await e.eor("`Something Went Wrong.`", time=5) elif "mute" in action: try: await ultroid_bot.edit_permissions( e.chat_id, user, until_date=None, send_messages=False ) except BaseException: return await e.eor("`Something Went Wrong.`", time=5) add_warn(e.chat_id, user, count + 1, r) c, r = warns(e.chat_id, user) ok = await ultroid_bot.get_entity(user) user = inline_mention(ok) r = r.split("|$|") text = f"User {user} Got {action} Due to {count+1} Warns.\n\n" for x in range(c): text += f"•**{x+1}.** {r[x]}\n" await e.eor(text) return reset_warn(e.chat_id, ok.id) add_warn(e.chat_id, user, count + 1, r) ok = await ultroid_bot.get_entity(user) user = inline_mention(ok) await eor( e, f"**WARNING :** {count+1}/{number}\n**To :**{user}\n**Be Careful !!!**\n\n**Reason** : {reason}", )
null
5,763
from pyUltroid.dB.warn_db import add_warn, reset_warn, warns from . import eor, get_string, inline_mention, udB, ultroid_cmd def reset_warn(chat, user): async def rwarn(e): reply = await e.get_reply_message() if reply: user = reply.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 user") reset_warn(e.chat_id, user) ok = await e.client.get_entity(user) user = inline_mention(ok) await e.eor(f"Cleared All Warns of {user}.")
null
5,764
from pyUltroid.dB.warn_db import add_warn, reset_warn, warns from . import eor, get_string, inline_mention, udB, ultroid_cmd def warns(chat, user): x = get_stuff() try: count, reason = x[chat][user][0], x[chat][user][1] return count, reason except BaseException: return 0, None async def twarns(e): reply = await e.get_reply_message() if reply: user = reply.from_id.user_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) c, r = warns(e.chat_id, user) if c and r: ok = await e.client.get_entity(user) user = inline_mention(ok) r = r.split("|$|") text = f"User {user} Got {c} Warns.\n\n" for x in range(c): text += f"•**{x+1}.** {r[x]}\n" await e.eor(text) else: await e.eor("`No Warnings`")
null
5,765
from pyUltroid.dB.warn_db import add_warn, reset_warn, warns from . import eor, get_string, inline_mention, udB, ultroid_cmd async def warnset(e): ok = e.pattern_match.group(1).strip() if not ok: return await e.eor("stuff") if "|" in ok: try: number, action = int(ok.split()[0]), ok.split()[1] except BaseException: return await e.eor(get_string("schdl_2"), time=5) if ("ban" or "kick" or "mute") not in action: return await e.eor("`Only mute / ban / kick option suported`", time=5) udB.set_key("SETWARN", f"{number} {action}") await e.eor(f"Done Your Warn Count is now {number} and Action is {action}") else: await e.eor(get_string("schdl_2"), time=5)
null
5,766
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something _gpromote_rights = ChatAdminRights( add_admins=False, invite_users=True, change_info=False, ban_users=True, delete_messages=True, pin_messages=True, ) async def _(e): x = e.pattern_match.group(1).strip() ultroid_bot = e.client if not x: return await e.eor(get_string("schdl_2"), time=5) user = await e.get_reply_message() if user: ev = await e.eor("`Promoting Replied User Globally`") ok = e.text.split() key = "all" if len(ok) > 1 and (("group" in ok[1]) or ("channel" in ok[1])): key = ok[1] rank = ok[2] if len(ok) > 2 else "AdMin" c = 0 user.id = user.peer_id.user_id if e.is_private else user.from_id.user_id async for x in e.client.iter_dialogs(): if ( "group" in key.lower() and x.is_group or "group" not in key.lower() and "channel" in key.lower() and x.is_channel ): try: await e.client( EditAdminRequest( x.id, user.id, _gpromote_rights, rank, ), ) c += 1 except BaseException: pass elif ( ("group" not in key.lower() or x.is_group) and ( "group" in key.lower() or "channel" not in key.lower() or x.is_channel ) and ( "group" in key.lower() or "channel" in key.lower() or x.is_group or x.is_channel ) ): try: await e.client( EditAdminRequest( x.id, user.id, _gpromote_rights, rank, ), ) c += 1 except Exception as er: LOGS.info(er) await eor(ev, f"Promoted The Replied Users in Total : {c} {key} chats") else: k = e.text.split() if not k[1]: return await eor( e, "`Give someone's username/id or replied to user.", time=5 ) user = k[1] if user.isdigit(): user = int(user) try: name = await e.client.get_entity(user) except BaseException: return await e.eor(f"`No User Found Regarding {user}`", time=5) ev = await e.eor(f"`Promoting {name.first_name} globally.`") key = "all" if len(k) > 2 and (("group" in k[2]) or ("channel" in k[2])): key = k[2] rank = k[3] if len(k) > 3 else "AdMin" c = 0 async for x in e.client.iter_dialogs(): if ( "group" in key.lower() and x.is_group or "group" not in key.lower() and "channel" in key.lower() and x.is_channel or "group" not in key.lower() and "channel" not in key.lower() and (x.is_group or x.is_channel) ): try: await ultroid_bot( EditAdminRequest( x.id, user, _gpromote_rights, rank, ), ) c += 1 except BaseException: pass await eor(ev, f"Promoted {name.first_name} in Total : {c} {key} chats.")
null
5,767
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something _gdemote_rights = ChatAdminRights( add_admins=False, invite_users=False, change_info=False, ban_users=False, delete_messages=False, pin_messages=False, ) async def _(e): x = e.pattern_match.group(1).strip() ultroid_bot = e.client if not x: return await e.eor(get_string("schdl_2"), time=5) user = await e.get_reply_message() if user: user.id = user.peer_id.user_id if e.is_private else user.from_id.user_id ev = await e.eor("`Demoting Replied User Globally`") ok = e.text.split() key = "all" if len(ok) > 1 and (("group" in ok[1]) or ("channel" in ok[1])): key = ok[1] rank = "Not AdMin" c = 0 async for x in e.client.iter_dialogs(): if ( "group" in key.lower() and x.is_group or "group" not in key.lower() and "channel" in key.lower() and x.is_channel or "group" not in key.lower() and "channel" not in key.lower() and (x.is_group or x.is_channel) ): try: await ultroid_bot( EditAdminRequest( x.id, user.id, _gdemote_rights, rank, ), ) c += 1 except BaseException: pass await eor(ev, f"Demoted The Replied Users in Total : {c} {key} chats") else: k = e.text.split() if not k[1]: return await eor( e, "`Give someone's username/id or replied to user.", time=5 ) user = k[1] if user.isdigit(): user = int(user) try: name = await ultroid_bot.get_entity(user) except BaseException: return await e.eor(f"`No User Found Regarding {user}`", time=5) ev = await e.eor(f"`Demoting {name.first_name} globally.`") key = "all" if len(k) > 2 and (("group" in k[2]) or ("channel" in k[2])): key = k[2] rank = "Not AdMin" c = 0 async for x in ultroid_bot.iter_dialogs(): if ( "group" in key.lower() and x.is_group or "group" not in key.lower() and "channel" in key.lower() and x.is_channel or "group" not in key.lower() and "channel" not in key.lower() and (x.is_group or x.is_channel) ): try: await ultroid_bot( EditAdminRequest( x.id, user, _gdemote_rights, rank, ), ) c += 1 except BaseException: pass await eor(ev, f"Demoted {name.first_name} in Total : {c} {key} chats.")
null
5,768
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something def ungban(user): ok = list_gbanned() if ok.get(int(user)): del ok[int(user)] return udB.set_key("GBAN", ok) def is_gbanned(user): ok = list_gbanned() if ok.get(int(user)): return ok[int(user)] async def _(e): xx = await e.eor("`UnGbanning...`") match = e.pattern_match.group(1).strip() peer = None if e.reply_to_msg_id: userid = (await e.get_reply_message()).sender_id elif match: try: userid = int(match) except ValueError: userid = match try: userid = (await e.client.get_entity(userid)).id except Exception as er: return await xx.edit(f"Failed to get User...\nError: {er}") elif e.is_private: userid = e.chat_id else: return await xx.eor("`Reply to some msg or add their id.`", time=5) if not is_gbanned(userid): return await xx.edit("`User/Channel is not Gbanned...`") try: if not peer: peer = await e.client.get_entity(userid) name = inline_mention(peer) except BaseException: userid = int(userid) name = str(userid) chats = 0 if e.client._dialogs: dialog = e.client._dialogs else: dialog = await e.client.get_dialogs() e.client._dialogs.extend(dialog) for ggban in dialog: if ggban.is_group or ggban.is_channel: try: await e.client.edit_permissions(ggban.id, userid, view_messages=True) chats += 1 except FloodWaitError as fw: LOGS.info( f"[FLOOD_WAIT_ERROR] : on Ungban\nSleeping for {fw.seconds+10}" ) await asyncio.sleep(fw.seconds + 10) try: await e.client.edit_permissions( ggban.id, userid, view_messages=True ) chats += 1 except BaseException as er: LOGS.exception(er) except (ChatAdminRequiredError, ValueError): pass except BaseException as er: LOGS.exception(er) ungban(userid) if isinstance(peer, User): await e.client(UnblockRequest(userid)) await xx.edit( f"`Ungbaned` {name} in {chats} `chats.\nRemoved from gbanwatch.`", )
null
5,769
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something from .. import * DEVLIST = [ 719195224, # @xditya 1322549723, # @danish_00 1903729401, # @its_buddhhu 1303895686, # @Sipak_OP 611816596, # @Arnab431 1318486004, # @sppidy 803243487, # @hellboi_atul ] def gban(user, reason): ok = list_gbanned() ok.update({int(user): reason or "No Reason. "}) return udB.set_key("GBAN", ok) def is_gbanned(user): ok = list_gbanned() if ok.get(int(user)): return ok[int(user)] async def _(e): xx = await e.eor("`Gbanning...`") reason = "" if e.reply_to_msg_id: userid = (await e.get_reply_message()).sender_id try: reason = e.text.split(" ", maxsplit=1)[1] except IndexError: pass elif e.pattern_match.group(1).strip(): usr = e.text.split(maxsplit=2)[1] try: userid = await e.client.parse_id(usr) except ValueError: userid = usr try: reason = e.text.split(maxsplit=2)[2] except IndexError: pass elif e.is_private: userid = e.chat_id try: reason = e.text.split(" ", maxsplit=1)[1] except IndexError: pass else: return await xx.eor("`Reply to some msg or add their id.`", time=5) user = None try: user = await e.client.get_entity(userid) name = inline_mention(user) except BaseException: userid = int(userid) name = str(userid) chats = 0 if userid == ultroid_bot.uid: return await xx.eor("`I can't gban myself.`", time=3) elif userid in DEVLIST: return await xx.eor("`I can't gban my Developers.`", time=3) elif is_gbanned(userid): return await eod( xx, "`User is already gbanned and added to gbanwatch.`", time=4, ) if e.client._dialogs: dialog = e.client._dialogs else: dialog = await e.client.get_dialogs() e.client._dialogs.extend(dialog) for ggban in dialog: if ggban.is_group or ggban.is_channel: try: await e.client.edit_permissions(ggban.id, userid, view_messages=False) chats += 1 except FloodWaitError as fw: LOGS.info( f"[FLOOD_WAIT_ERROR] : on GBAN Command\nSleeping for {fw.seconds+10}" ) await asyncio.sleep(fw.seconds + 10) try: await e.client.edit_permissions( ggban.id, userid, view_messages=False ) chats += 1 except BaseException as er: LOGS.exception(er) except (ChatAdminRequiredError, ValueError): pass except BaseException as er: LOGS.exception(er) gban(userid, reason) if isinstance(user, User): await e.client(BlockRequest(userid)) gb_msg = f"**#Gbanned** {name} `in {chats} chats and added to gbanwatch!`" if reason: gb_msg += f"\n**Reason** : {reason}" await xx.edit(gb_msg)
null
5,770
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something keym = KeyManager("GBLACKLISTS", cast=list) 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 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 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 gcast(event): text, btn, reply = "", None, None if xx := event.pattern_match.group(2): msg, btn = get_msg_button(event.text.split(maxsplit=1)[1]) elif event.is_reply: reply = await event.get_reply_message() msg = reply.text if reply.buttons: btn = format_btn(reply.buttons) else: msg, btn = get_msg_button(msg) else: return await eor( event, "`Give some text to Globally Broadcast or reply a message..`" ) kk = await event.eor("`Globally Broadcasting Msg...`") er = 0 done = 0 err = "" if event.client._dialogs: dialog = event.client._dialogs else: dialog = await event.client.get_dialogs() event.client._dialogs.extend(dialog) for x in dialog: if x.is_group: chat = x.entity.id if ( not keym.contains(chat) and int(f"-100{str(chat)}") not in NOSPAM_CHAT and ( ( event.text[2:7] != "admin" or (x.entity.admin_rights or x.entity.creator) ) ) ): try: if btn: bt = create_tl_btn(btn) await something( event, msg, reply.media if reply else None, bt, chat=chat, reply=False, ) else: await event.client.send_message( chat, msg, file=reply.media if reply else None ) done += 1 except FloodWaitError as fw: await asyncio.sleep(fw.seconds + 10) try: if btn: bt = create_tl_btn(btn) await something( event, msg, reply.media if reply else None, bt, chat=chat, reply=False, ) else: await event.client.send_message( chat, msg, file=reply.media if reply else None ) done += 1 except Exception as rr: err += f"• {rr}\n" er += 1 except BaseException as h: err += f"• {str(h)}" + "\n" er += 1 text += f"Done in {done} chats, error in {er} chat(s)" if err != "": open("gcast-error.log", "w+").write(err) text += f"\nYou can do `{HNDLR}ul gcast-error.log` to know error report." await kk.edit(text)
null
5,771
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something keym = KeyManager("GBLACKLISTS", cast=list) 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 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 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 gucast(event): msg, btn, reply = "", None, None if xx := event.pattern_match.group(1).strip(): msg, btn = get_msg_button(event.text.split(maxsplit=1)[1]) elif event.is_reply: reply = await event.get_reply_message() msg = reply.text if reply.buttons: btn = format_btn(reply.buttons) else: msg, btn = get_msg_button(msg) else: return await eor( event, "`Give some text to Globally Broadcast or reply a message..`" ) kk = await event.eor("`Globally Broadcasting Msg...`") er = 0 done = 0 if event.client._dialogs: dialog = event.client._dialogs else: dialog = await event.client.get_dialogs() event.client._dialogs.extend(dialog) for x in dialog: if x.is_user and not x.entity.bot: chat = x.id if not keym.contains(chat): try: if btn: bt = create_tl_btn(btn) await something( event, msg, reply.media if reply else None, bt, chat=chat, reply=False, ) else: await event.client.send_message( chat, msg, file=reply.media if reply else None ) done += 1 except BaseException: er += 1 await kk.edit(f"Done in {done} chats, error in {er} chat(s)")
null
5,772
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something from .. import * DEVLIST = [ 719195224, # @xditya 1322549723, # @danish_00 1903729401, # @its_buddhhu 1303895686, # @Sipak_OP 611816596, # @Arnab431 1318486004, # @sppidy 803243487, # @hellboi_atul ] async def gkick(e): xx = await e.eor("`Gkicking...`") if e.reply_to_msg_id: userid = (await e.get_reply_message()).sender_id elif e.pattern_match.group(1).strip(): userid = await e.client.parse_id(e.pattern_match.group(1).strip()) elif e.is_private: userid = e.chat_id else: return await xx.edit("`Reply to some msg or add their id.`", time=5) name = (await e.client.get_entity(userid)).first_name chats = 0 if userid == ultroid_bot.uid: return await xx.eor("`I can't gkick myself.`", time=3) if userid in DEVLIST: return await xx.eor("`I can't gkick my Developers.`", time=3) if e.client._dialogs: dialog = e.client._dialogs else: dialog = await e.client.get_dialogs() e.client._dialogs.extend(dialog) for gkick in dialog: if gkick.is_group or gkick.is_channel: try: await e.client.kick_participant(gkick.id, userid) chats += 1 except BaseException: pass await xx.edit(f"`Gkicked` [{name}](tg://user?id={userid}) `in {chats} chats.`")
null
5,773
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something from .. import * DEVLIST = [ 719195224, # @xditya 1322549723, # @danish_00 1903729401, # @its_buddhhu 1303895686, # @Sipak_OP 611816596, # @Arnab431 1318486004, # @sppidy 803243487, # @hellboi_atul ] def gmute(user): def is_gmuted(user): async def _(e): xx = await e.eor("`Gmuting...`") if e.reply_to_msg_id: userid = (await e.get_reply_message()).sender_id elif e.pattern_match.group(1).strip(): userid = await e.client.parse_id(e.pattern_match.group(1).strip()) elif e.is_private: userid = e.chat_id else: return await xx.eor("`Reply to some msg or add their id.`", tome=5, time=5) name = await e.client.get_entity(userid) chats = 0 if userid == ultroid_bot.uid: return await xx.eor("`I can't gmute myself.`", time=3) if userid in DEVLIST: return await xx.eor("`I can't gmute my Developers.`", time=3) if is_gmuted(userid): return await xx.eor("`User is already gmuted.`", time=4) if e.client._dialogs: dialog = e.client._dialogs else: dialog = await e.client.get_dialogs() e.client._dialogs.extend(dialog) for onmute in dialog: if onmute.is_group: try: await e.client.edit_permissions(onmute.id, userid, send_messages=False) chats += 1 except BaseException: pass gmute(userid) await xx.edit(f"`Gmuted` {inline_mention(name)} `in {chats} chats.`")
null
5,774
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something def ungmute(user): ok = list_gmuted() if user in ok: ok.remove(int(user)) return udB.set_key("GMUTE", ok) def is_gmuted(user): return int(user) in list_gmuted() async def _(e): xx = await e.eor("`UnGmuting...`") if e.reply_to_msg_id: userid = (await e.get_reply_message()).sender_id elif e.pattern_match.group(1).strip(): userid = await e.client.parse_id(e.pattern_match.group(1).strip()) elif e.is_private: userid = e.chat_id else: return await xx.eor("`Reply to some msg or add their id.`", time=5) name = (await e.client.get_entity(userid)).first_name chats = 0 if not is_gmuted(userid): return await xx.eor("`User is not gmuted.`", time=3) if e.client._dialogs: dialog = e.client._dialogs else: dialog = await e.client.get_dialogs() e.client._dialogs.extend(dialog) for hurr in dialog: if hurr.is_group: try: await e.client.edit_permissions(hurr.id, userid, send_messages=True) chats += 1 except BaseException: pass ungmute(userid) await xx.edit(f"`Ungmuted` {inline_mention(name)} `in {chats} chats.`")
null
5,775
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something def list_gbanned(): return udB.get_key("GBAN") or {} async def list_gengbanned(event): users = list_gbanned() x = await event.eor(get_string("com_1")) msg = "" if not users: return await x.edit("`You haven't GBanned anyone!`") for i in users: try: name = await event.client.get_entity(int(i)) except BaseException: name = i msg += f"<strong>User</strong>: {inline_mention(name, html=True)}\n" reason = users[i] msg += f"<strong>Reason</strong>: {reason}\n\n" if reason is not None else "\n" gbanned_users = f"<strong>List of users GBanned by {OWNER_NAME}</strong>:\n\n{msg}" if len(gbanned_users) > 4096: with open("gbanned.txt", "w") as f: f.write( gbanned_users.replace("<strong>", "") .replace("</strong>", "") .replace("<a href=tg://user?id=", "") .replace("</a>", "") ) await x.reply( file="gbanned.txt", message=f"List of users GBanned by {inline_mention(ultroid_bot.me)}", ) os.remove("gbanned.txt") await x.delete() else: await x.edit(gbanned_users, parse_mode="html")
null
5,776
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something def list_gbanned(): return udB.get_key("GBAN") or {} def is_gbanned(user): ok = list_gbanned() if ok.get(int(user)): return ok[int(user)] async def gstat_(e): xx = await e.eor(get_string("com_1")) if e.is_private: userid = (await e.get_chat()).id elif e.reply_to_msg_id: userid = (await e.get_reply_message()).sender_id elif e.pattern_match.group(1).strip(): try: userid = await e.client.parse_id(e.pattern_match.group(1).strip()) except Exception as err: return await xx.eor(f"{err}", time=10) else: return await xx.eor("`Reply to some msg or add their id.`", time=5) name = (await e.client.get_entity(userid)).first_name msg = f"**{name} is " is_banned = is_gbanned(userid) reason = list_gbanned().get(userid) if is_banned: msg += "Globally Banned" msg += f" with reason** `{reason}`" if reason else ".**" else: msg += "not Globally Banned.**" await xx.edit(msg)
null
5,777
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something async def gblacker(event, type_): try: chat_id = int(event.text.split(maxsplit=1)[1]) try: chat_id = (await event.client.get_entity(chat_id)).id except Exception as e: return await event.eor(f"**ERROR**\n`{str(e)}`") except IndexError: chat_id = event.chat_id if type_ == "add": keym.add(chat_id) elif type_ == "remove": keym.remove(chat_id) await event.eor(f"Global Broadcasts: \n{type_}ed {chat_id}") async def blacklist_(event): await gblacker(event, "add")
null
5,778
import asyncio import os from telethon.errors.rpcerrorlist import ChatAdminRequiredError, FloodWaitError from telethon.tl.functions.channels import EditAdminRequest from telethon.tl.functions.contacts import BlockRequest, UnblockRequest from telethon.tl.types import ChatAdminRights, User from pyUltroid.dB import DEVLIST from pyUltroid.dB.base import KeyManager from pyUltroid.dB.gban_mute_db import ( gban, gmute, is_gbanned, is_gmuted, list_gbanned, ungban, ungmute, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import ( HNDLR, LOGS, NOSPAM_CHAT, OWNER_NAME, eod, eor, get_string, inline_mention, ultroid_bot, ultroid_cmd, ) from ._inline import something async def gblacker(event, type_): try: chat_id = int(event.text.split(maxsplit=1)[1]) try: chat_id = (await event.client.get_entity(chat_id)).id except Exception as e: return await event.eor(f"**ERROR**\n`{str(e)}`") except IndexError: chat_id = event.chat_id if type_ == "add": keym.add(chat_id) elif type_ == "remove": keym.remove(chat_id) await event.eor(f"Global Broadcasts: \n{type_}ed {chat_id}") async def ungblacker(event): await gblacker(event, "remove")
null
5,779
from . import get_help from telethon.utils import get_display_name from . import get_string, udB, ultroid_cmd async def _(e): key = udB.get_key("CLEANCHAT") or [] if e.chat_id in key: return await eod(e, get_string("clan_5")) key.append(e.chat_id) udB.set_key("CLEANCHAT", key) await e.eor(get_string("clan_1"), time=5)
null
5,780
from . import get_help from telethon.utils import get_display_name from . import get_string, udB, ultroid_cmd async def _(e): key = udB.get_key("CLEANCHAT") or [] if e.chat_id in key: key.remove(e.chat_id) udB.set_key("CLEANCHAT", key) await e.eor(get_string("clan_2"), time=5)
null
5,781
from . import get_help from telethon.utils import get_display_name from . import get_string, udB, ultroid_cmd async def _(e): if k := udB.get_key("CLEANCHAT"): o = "" for x in k: try: title = get_display_name(await e.client.get_entity(x)) except BaseException: title = get_string("clan_3") o += f"{x} {title}\n" return await e.eor(o) await e.eor(get_string("clan_4"), time=5)
null
5,782
from pyUltroid.fns.misc import unsplashsearch from . import asyncio, download_file, get_string, os, ultroid_cmd from .. import * async def unsplashsearch(query, limit=None, shuf=True): async def searchunsl(ult): match = ult.pattern_match.group(1).strip() if not match: return await ult.eor("Give me Something to Search") num = 5 if ";" in match: num = int(match.split(";")[1]) match = match.split(";")[0] tep = await ult.eor(get_string("com_1")) res = await unsplashsearch(match, limit=num) if not res: return await ult.eor(get_string("unspl_1"), time=5) CL = [download_file(rp, f"{match}-{e}.png") for e, rp in enumerate(res)] imgs = [z[0] for z in (await asyncio.gather(*CL)) if z] await ult.respond(f"Uploaded {len(imgs)} Images!", file=imgs) await tep.delete() [os.remove(img) for img in imgs]
null
5,783
from telethon.errors import ( BotMethodInvalidError, ChatSendInlineForbiddenError, ChatSendMediaForbiddenError, ) from . import LOG_CHANNEL, LOGS, Button, asst, eor, get_string, ultroid_cmd REPOMSG = """ • **ULTROID USERBOT** •\n • Repo - [Click Here](https://github.com/TeamUltroid/Ultroid) • Addons - [Click Here](https://github.com/TeamUltroid/UltroidAddons) • Support - @UltroidSupportChat """ async def repify(e): try: q = await e.client.inline_query(asst.me.username, "") await q[0].click(e.chat_id) return await e.delete() except ( ChatSendInlineForbiddenError, ChatSendMediaForbiddenError, BotMethodInvalidError, ): pass except Exception as er: LOGS.info(f"Error while repo command : {str(er)}") await e.eor(REPOMSG)
null
5,784
from telethon.errors import ( BotMethodInvalidError, ChatSendInlineForbiddenError, ChatSendMediaForbiddenError, ) from . import LOG_CHANNEL, LOGS, Button, asst, eor, get_string, ultroid_cmd ULTSTRING = """🎇 **Thanks for Deploying Ultroid Userbot!** • Here, are the Some Basic stuff from, where you can Know, about its Usage.""" async def useUltroid(rs): button = Button.inline("Start >>", "initft_2") msg = await asst.send_message( LOG_CHANNEL, ULTSTRING, file="https://graph.org/file/54a917cc9dbb94733ea5f.jpg", buttons=button, ) if not (rs.chat_id == LOG_CHANNEL and rs.client._bot): await eor(rs, f"**[Click Here]({msg.message_link})**")
null
5,785
import os import time from . import ( HNDLR, ULTConfig, asyncio, bash, downloader, get_all_files, get_string, ultroid_cmd, uploader, ) async def zipp(event): reply = await event.get_reply_message() t = time.time() if not reply: await event.eor(get_string("zip_1")) return 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, reply.media.document, xx, t, get_string("com_5") ) file = image.name else: file = await event.download_media(reply) inp = file.replace(file.split(".")[-1], "zip") if event.pattern_match.group(1).strip(): await bash( f"zip -r --password {event.pattern_match.group(1).strip()} {inp} {file}" ) else: await bash(f"zip -r {inp} {file}") k = time.time() xxx = await uploader(inp, inp, k, xx, get_string("com_6")) await event.client.send_file( event.chat_id, xxx, force_document=True, thumb=ULTConfig.thumb, caption=f"`{xxx.name}`", reply_to=reply, ) os.remove(inp) os.remove(file) await xx.delete()
null
5,786
import os import time from . import ( HNDLR, ULTConfig, asyncio, bash, downloader, get_all_files, get_string, ultroid_cmd, uploader, ) async def unzipp(event): reply = await event.get_reply_message() file = event.pattern_match.group(1).strip() t = time.time() if not ((reply and reply.media) or file): await event.eor(get_string("zip_1")) return xx = await event.eor(get_string("com_1")) if reply.media: if not hasattr(reply.media, "document"): return await xx.edit(get_string("zip_3")) file = reply.media.document if not reply.file.name.endswith(("zip", "rar", "exe")): return await xx.edit(get_string("zip_3")) image = await downloader( reply.file.name, reply.media.document, xx, t, get_string("com_5") ) file = image.name if os.path.isdir("unzip"): await bash("rm -rf unzip") os.mkdir("unzip") await bash(f"7z x {file} -aoa -ounzip") await asyncio.sleep(4) ok = get_all_files("unzip") for x in ok: k = time.time() xxx = await uploader(x, x, k, xx, get_string("com_6")) await event.client.send_file( event.chat_id, xxx, force_document=True, thumb=ULTConfig.thumb, caption=f"`{xxx.name}`", ) await xx.delete()
null
5,787
import os import time from . import ( HNDLR, ULTConfig, asyncio, bash, downloader, get_all_files, get_string, ultroid_cmd, uploader, ) async def azipp(event): reply = await event.get_reply_message() t = time.time() if not (reply and reply.media): await event.eor(get_string("zip_1")) return xx = await event.eor(get_string("com_1")) if not os.path.isdir("zip"): os.mkdir("zip") if reply.media: if hasattr(reply.media, "document"): file = reply.media.document image = await downloader( f"zip/{reply.file.name}", reply.media.document, xx, t, get_string("com_5"), ) file = image.name else: file = await event.download_media(reply.media, "zip/") await xx.edit( f"Downloaded `{file}` succesfully\nNow Reply To Other Files To Add And Zip all at once" )
null
5,788
import os import time from . import ( HNDLR, ULTConfig, asyncio, bash, downloader, get_all_files, get_string, ultroid_cmd, uploader, ) async def do_zip(event): if not os.path.isdir("zip"): return await event.eor(get_string("zip_2").format(HNDLR)) xx = await event.eor(get_string("com_1")) if event.pattern_match.group(1).strip(): await bash( f"zip -r --password {event.pattern_match.group(1).strip()} ultroid.zip zip/*" ) else: await bash("zip -r ultroid.zip zip/*") k = time.time() xxx = await uploader("ultroid.zip", "ultroid.zip", k, xx, get_string("com_6")) await event.client.send_file( event.chat_id, xxx, force_document=True, thumb=ULTConfig.thumb, ) await bash("rm -rf zip") os.remove("ultroid.zip") await xx.delete()
null
5,789
from . import get_help import os import re from telegraph import upload_file as uf from telethon.tl.types import User from telethon.utils import pack_bot_file_id from pyUltroid.dB.filter_db import add_filter, get_filter, list_filter, rem_filter 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 filter_func(e): if isinstance(e.sender, User) and e.sender.bot: return xx = (e.text).lower() chat = e.chat_id if x := get_filter(chat): for c in x: pat = r"( |^|[^\w])" + re.escape(c) + r"( |$|[^\w])" if re.search(pat, xx): if k := x.get(c): msg = k["msg"] media = k["media"] if k.get("button"): btn = create_tl_btn(k["button"]) return await something(e, msg, media, btn) await e.reply(msg, file=media) def add_filter(chat, word, msg, media, button): ok = get_stuff() if ok.get(chat): ok[chat].update({word: {"msg": msg, "media": media, "button": button}}) else: ok.update({chat: {word: {"msg": msg, "media": media, "button": button}}}) udB.set_key("FILTERS", 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 af(e): wrd = (e.pattern_match.group(1).strip()).lower() wt = await e.get_reply_message() chat = e.chat_id if not (wt and wrd): return await e.eor(get_string("flr_1")) 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) 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_filter(chat, wrd, txt, m, btn) else: add_filter(chat, wrd, None, m, btn) else: txt = wt.text if not btn: txt, btn = get_msg_button(wt.text) add_filter(chat, wrd, txt, None, btn) await e.eor(get_string("flr_4").format(wrd)) ultroid_bot.add_handler(filter_func, events.NewMessage())
null
5,790
from . import get_help import os import re from telegraph import upload_file as uf from telethon.tl.types import User from telethon.utils import pack_bot_file_id from pyUltroid.dB.filter_db import add_filter, get_filter, list_filter, rem_filter 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_filter(chat, word): ok = get_stuff() if ok.get(chat) and ok[chat].get(word): ok[chat].pop(word) udB.set_key("FILTERS", ok) async def rf(e): wrd = (e.pattern_match.group(1).strip()).lower() chat = e.chat_id if not wrd: return await e.eor(get_string("flr_3")) rem_filter(int(chat), wrd) await e.eor(get_string("flr_5").format(wrd))
null
5,791
from . import get_help import os import re from telegraph import upload_file as uf from telethon.tl.types import User from telethon.utils import pack_bot_file_id from pyUltroid.dB.filter_db import add_filter, get_filter, list_filter, rem_filter 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_filter(chat): async def lsnote(e): if x := list_filter(e.chat_id): sd = "Filters Found In This Chats Are\n\n" return await e.eor(sd + x) await e.eor(get_string("flr_6"))
null
5,792
from telethon import events from telethon.utils import get_display_name from pyUltroid.dB.mute_db import is_muted, mute, unmute from pyUltroid.fns.admins import ban_time from . import asst, eod, get_string, inline_mention, ultroid_bot, ultroid_cmd def is_muted(chat, id): ok = get_muted() return bool(ok.get(chat) and id in ok[chat]) async def watcher(event): if is_muted(event.chat_id, event.sender_id): await event.delete() if event.via_bot and is_muted(event.chat_id, event.via_bot_id): await event.delete()
null
5,793
from telethon import events from telethon.utils import get_display_name from pyUltroid.dB.mute_db import is_muted, mute, unmute from pyUltroid.fns.admins import ban_time from . import asst, eod, get_string, inline_mention, ultroid_bot, ultroid_cmd def mute(chat, id): ok = get_muted() if ok.get(chat): if id not in ok[chat]: ok[chat].append(id) else: ok.update({chat: [id]}) return udB.set_key("MUTE", ok) def is_muted(chat, id): ok = get_muted() return bool(ok.get(chat) and id in ok[chat]) async def startmute(event): xx = await event.eor("`Muting...`") if input_ := event.pattern_match.group(1).strip(): try: userid = await event.client.parse_id(input_) except Exception as x: return await xx.edit(str(x)) elif event.reply_to_msg_id: reply = await event.get_reply_message() userid = reply.sender_id if reply.out or userid in [ultroid_bot.me.id, asst.me.id]: return await xx.eor("`You cannot mute yourself or your assistant bot.`") elif event.is_private: userid = event.chat_id else: return await xx.eor("`Reply to a user or add their userid.`", time=5) chat = await event.get_chat() if "admin_rights" in vars(chat) and vars(chat)["admin_rights"] is not None: if not chat.admin_rights.delete_messages: return await xx.eor("`No proper admin rights...`", time=5) elif "creator" not in vars(chat) and not event.is_private: return await xx.eor("`No proper admin rights...`", time=5) if is_muted(event.chat_id, userid): return await xx.eor("`This user is already muted in this chat.`", time=5) mute(event.chat_id, userid) await xx.eor("`Successfully muted...`", time=3)
null
5,794
from telethon import events from telethon.utils import get_display_name from pyUltroid.dB.mute_db import is_muted, mute, unmute from pyUltroid.fns.admins import ban_time from . import asst, eod, get_string, inline_mention, ultroid_bot, ultroid_cmd def unmute(chat, id): ok = get_muted() if ok.get(chat) and id in ok[chat]: ok[chat].remove(id) return udB.set_key("MUTE", ok) def is_muted(chat, id): ok = get_muted() return bool(ok.get(chat) and id in ok[chat]) async def endmute(event): xx = await event.eor("`Unmuting...`") if input_ := event.pattern_match.group(1).strip(): try: userid = await event.client.parse_id(input_) except Exception as x: return await xx.edit(str(x)) elif event.reply_to_msg_id: userid = (await event.get_reply_message()).sender_id elif event.is_private: userid = event.chat_id else: return await xx.eor("`Reply to a user or add their userid.`", time=5) if not is_muted(event.chat_id, userid): return await xx.eor("`This user is not muted in this chat.`", time=3) unmute(event.chat_id, userid) await xx.eor("`Successfully unmuted...`", time=3)
null
5,795
from telethon import events from telethon.utils import get_display_name from pyUltroid.dB.mute_db import is_muted, mute, unmute from pyUltroid.fns.admins import ban_time from . import asst, eod, get_string, inline_mention, ultroid_bot, 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): xx = await e.eor("`Muting...`") huh = e.text.split() try: tme = huh[1] except IndexError: return await xx.eor("`Time till mute?`", time=5) try: input_ = huh[2] except IndexError: input_ = "" chat = await e.get_chat() if e.reply_to_msg_id: reply = await e.get_reply_message() userid = reply.sender_id name = (await reply.get_sender()).first_name elif input_: userid = await e.client.parse_id(input_) name = (await e.client.get_entity(userid)).first_name else: return await xx.eor(get_string("tban_1"), time=3) if userid == ultroid_bot.uid: return await xx.eor("`I can't mute myself.`", time=3) try: bun = ban_time(tme) await e.client.edit_permissions( chat.id, userid, until_date=bun, send_messages=False, ) await eod( xx, f"`Successfully Muted` [{name}](tg://user?id={userid}) `in {chat.title} for {tme}`", time=5, ) except BaseException as m: await xx.eor(f"`{m}`", time=5)
null
5,796
from telethon import events from telethon.utils import get_display_name from pyUltroid.dB.mute_db import is_muted, mute, unmute from pyUltroid.fns.admins import ban_time from . import asst, eod, get_string, inline_mention, ultroid_bot, ultroid_cmd async def _(e): xx = await e.eor("`Unmuting...`") input = e.pattern_match.group(1).strip() chat = await e.get_chat() if e.reply_to_msg_id: reply = await e.get_reply_message() userid = reply.sender_id name = (await reply.get_sender()).first_name elif input: userid = await e.client.parse_id(input) name = (await e.client.get_entity(userid)).first_name else: return await xx.eor(get_string("tban_1"), time=3) try: await e.client.edit_permissions( chat.id, userid, until_date=None, send_messages=True, ) await eod( xx, f"`Successfully Unmuted` [{name}](tg://user?id={userid}) `in {chat.title}`", time=5, ) except BaseException as m: await xx.eor(f"`{m}`", time=5)
null
5,797
from telethon import events from telethon.utils import get_display_name from pyUltroid.dB.mute_db import is_muted, mute, unmute from pyUltroid.fns.admins import ban_time from . import asst, eod, get_string, inline_mention, ultroid_bot, ultroid_cmd async def _(e): xx = await e.eor("`Muting...`") input = e.pattern_match.group(1).strip() chat = await e.get_chat() if e.reply_to_msg_id: userid = (await e.get_reply_message()).sender_id name = get_display_name(await e.client.get_entity(userid)) elif input: try: userid = await e.client.parse_id(input) name = inline_mention(await e.client.get_entity(userid)) except Exception as x: return await xx.edit(str(x)) else: return await xx.eor(get_string("tban_1"), time=3) if userid == ultroid_bot.uid: return await xx.eor("`I can't mute myself.`", time=3) try: await e.client.edit_permissions( chat.id, userid, until_date=None, send_messages=False, ) await eod( xx, f"`Successfully Muted` {name} `in {chat.title}`", ) except BaseException as m: await xx.eor(f"`{m}`", time=5)
null
5,798
import glob import os import shutil import time import cv2 import numpy as np from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from telethon.errors.rpcerrorlist import PhotoSaveFileInvalidError from pyUltroid.fns.tools import four_point_transform from . import ( HNDLR, LOGS, bash, check_filename, downloader, eor, get_string, ultroid_cmd, ) if not os.path.isdir("pdf"): os.mkdir("pdf") pattern="pdf( (.*)|$)", async def pdfseimg(event): ok = await event.get_reply_message() msg = event.pattern_match.group(1).strip() if not (ok and (ok.document and (ok.document.mime_type == "application/pdf"))): await event.eor("`Reply The pdf u Want to Download..`") return xx = await event.eor(get_string("com_1")) file = ok.media.document k = time.time() filename = "hehe.pdf" result = await downloader( f"pdf/{filename}", file, xx, k, f"Downloading {filename}..." ) await xx.delete() pdfp = "pdf/hehe.pdf" pdfp.replace(".pdf", "") pdf = PdfFileReader(pdfp) if not msg: ok = [] for num in range(pdf.numPages): pw = PdfFileWriter() pw.addPage(pdf.getPage(num)) fil = os.path.join(f"pdf/ult{num + 1}.png") ok.append(fil) with open(fil, "wb") as f: pw.write(f) os.remove(pdfp) for z in ok: await event.client.send_file(event.chat_id, z) shutil.rmtree("pdf") os.mkdir("pdf") await xx.delete() elif "-" in msg: ok = int(msg.split("-")[-1]) - 1 for o in range(ok): pw = PdfFileWriter() pw.addPage(pdf.getPage(o)) with open(os.path.join("ult.png"), "wb") as f: pw.write(f) await event.reply( file="ult.png", ) os.remove("ult.png") os.remove(pdfp) else: o = int(msg) - 1 pw = PdfFileWriter() pw.addPage(pdf.getPage(o)) with open(os.path.join("ult.png"), "wb") as f: pw.write(f) os.remove(pdfp) try: await event.reply(file="ult.png") except PhotoSaveFileInvalidError: await event.reply(file="ult.png", force_document=True) os.remove("ult.png")
null
5,799
import glob import os import shutil import time import cv2 import numpy as np from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from telethon.errors.rpcerrorlist import PhotoSaveFileInvalidError from pyUltroid.fns.tools import four_point_transform from . import ( HNDLR, LOGS, bash, check_filename, downloader, eor, get_string, ultroid_cmd, ) if not os.path.isdir("pdf"): os.mkdir("pdf") pattern="pdf( (.*)|$)", async def pdfsetxt(event): ok = await event.get_reply_message() msg = event.pattern_match.group(1).strip() if not ok and ok.document and ok.document.mime_type == "application/pdf": await event.eor("`Reply The pdf u Want to Download..`") return xx = await event.eor(get_string("com_1")) file = ok.media.document k = time.time() filename = ok.file.name result = await downloader(filename, file, xx, k, f"Downloading {filename}...") await xx.delete() dl = result.name if not msg: pdf = PdfFileReader(dl) text = f"{dl.split('.')[0]}.txt" with open(text, "w") as f: for page_num in range(pdf.numPages): pageObj = pdf.getPage(page_num) txt = pageObj.extractText() f.write(f"Page {page_num + 1}\n") f.write("".center(100, "-")) f.write(txt) await event.client.send_file( event.chat_id, text, reply_to=event.reply_to_msg_id, ) os.remove(text) os.remove(dl) return if "-" in msg: u, d = msg.split("-") a = PdfFileReader(dl) str = "".join(a.getPage(i).extractText() for i in range(int(u) - 1, int(d))) text = f"{dl.split('.')[0]} {msg}.txt" else: u = int(msg) - 1 a = PdfFileReader(dl) str = a.getPage(u).extractText() text = f"{dl.split('.')[0]} Pg-{msg}.txt" with open(text, "w") as f: f.write(str) await event.client.send_file( event.chat_id, text, reply_to=event.reply_to_msg_id, ) os.remove(text) os.remove(dl)
null
5,800
import glob import os import shutil import time import cv2 import numpy as np from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from telethon.errors.rpcerrorlist import PhotoSaveFileInvalidError from pyUltroid.fns.tools import four_point_transform from . import ( HNDLR, LOGS, bash, check_filename, downloader, eor, get_string, ultroid_cmd, ) if not os.path.isdir("pdf"): os.mkdir("pdf") pattern="pdf( (.*)|$)", from .. import * def four_point_transform(image, pts): try: import cv2 except ImportError: raise DependencyMissingError("This function needs 'cv2' to be installed.") rect = order_points(pts) (tl, tr, br, bl) = rect widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) maxWidth = max(int(widthA), int(widthB)) heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) maxHeight = max(int(heightA), int(heightB)) dst = np.array( [[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype="float32", ) M = cv2.getPerspectiveTransform(rect, dst) return cv2.warpPerspective(image, M, (maxWidth, maxHeight)) async def imgscan(event): ok = await event.get_reply_message() if not (ok and (ok.media)): await event.eor("`Reply The pdf u Want to Download..`") return if not ( ok.photo or (ok.file.name and ok.file.name.endswith(("png", "jpg", "jpeg", "webp"))) ): await event.eor("`Reply to a Image only...`") return ultt = await ok.download_media() xx = await event.eor(get_string("com_1")) image = cv2.imread(ultt) original_image = image.copy() ratio = image.shape[0] / 500.0 hi, wid = image.shape[:2] ra = 500 / float(hi) dmes = (int(wid * ra), 500) image = cv2.resize(image, dmes, interpolation=cv2.INTER_AREA) image_yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV) image_y = np.zeros(image_yuv.shape[:2], np.uint8) image_y[:, :] = image_yuv[:, :, 0] image_blurred = cv2.GaussianBlur(image_y, (3, 3), 0) edges = cv2.Canny(image_blurred, 50, 200, apertureSize=3) contours, hierarchy = cv2.findContours( edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE, ) polygons = [] for cnt in contours: hull = cv2.convexHull(cnt) polygons.append(cv2.approxPolyDP(hull, 0.01 * cv2.arcLength(hull, True), False)) sortedPoly = sorted(polygons, key=cv2.contourArea, reverse=True) cv2.drawContours(image, sortedPoly[0], -1, (0, 0, 255), 5) simplified_cnt = sortedPoly[0] if len(simplified_cnt) == 4: try: from skimage.filters import threshold_local except ImportError: LOGS.info(f"Scikit-Image is not Installed.") await xx.edit("`Installing Scikit-Image...\nThis may take some long...`") _, __ = await bash("pip install scikit-image") LOGS.info(_) from skimage.filters import threshold_local cropped_image = four_point_transform( original_image, simplified_cnt.reshape(4, 2) * ratio, ) gray_image = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2GRAY) T = threshold_local(gray_image, 11, offset=10, method="gaussian") ok = (gray_image > T).astype("uint8") * 255 if len(simplified_cnt) != 4: ok = cv2.detailEnhance(original_image, sigma_s=10, sigma_r=0.15) cv2.imwrite("o.png", ok) image1 = Image.open("o.png") im1 = image1.convert("RGB") scann = f"Scanned {ultt.split('.')[0]}.pdf" im1.save(scann) await event.client.send_file(event.chat_id, scann, reply_to=event.reply_to_msg_id) await xx.delete() os.remove(ultt) os.remove("o.png") os.remove(scann)
null
5,801
import glob import os import shutil import time import cv2 import numpy as np from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from telethon.errors.rpcerrorlist import PhotoSaveFileInvalidError from pyUltroid.fns.tools import four_point_transform from . import ( HNDLR, LOGS, bash, check_filename, downloader, eor, get_string, ultroid_cmd, ) if not os.path.isdir("pdf"): os.mkdir("pdf") pattern="pdf( (.*)|$)", from .. import * def four_point_transform(image, pts): async def savepdf(event): ok = await event.get_reply_message() if not (ok and (ok.media)): await eor( event, "`Reply to Images/pdf which u want to merge as a single pdf..`", ) return ultt = await ok.download_media() if ultt.endswith(("png", "jpg", "jpeg", "webp")): xx = await event.eor(get_string("com_1")) image = cv2.imread(ultt) original_image = image.copy() ratio = image.shape[0] / 500.0 h_, _v = image.shape[:2] m_ = 500 / float(h_) image = cv2.resize(image, (int(_v * m_), 500), interpolation=cv2.INTER_AREA) image_yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV) image_y = np.zeros(image_yuv.shape[:2], np.uint8) image_y[:, :] = image_yuv[:, :, 0] image_blurred = cv2.GaussianBlur(image_y, (3, 3), 0) edges = cv2.Canny(image_blurred, 50, 200, apertureSize=3) contours, hierarchy = cv2.findContours( edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE, ) polygons = [] for cnt in contours: hull = cv2.convexHull(cnt) polygons.append( cv2.approxPolyDP(hull, 0.01 * cv2.arcLength(hull, True), False), ) sortedPoly = sorted(polygons, key=cv2.contourArea, reverse=True) cv2.drawContours(image, sortedPoly[0], -1, (0, 0, 255), 5) simplified_cnt = sortedPoly[0] if len(simplified_cnt) == 4: try: from skimage.filters import threshold_local except ImportError: LOGS.info(f"Scikit-Image is not Installed.") await xx.edit( "`Installing Scikit-Image...\nThis may take some long...`" ) _, __ = await bash("pip install scikit-image") LOGS.info(_) from skimage.filters import threshold_local cropped_image = four_point_transform( original_image, simplified_cnt.reshape(4, 2) * ratio, ) gray_image = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2GRAY) T = threshold_local(gray_image, 11, offset=10, method="gaussian") ok = (gray_image > T).astype("uint8") * 255 if len(simplified_cnt) != 4: ok = cv2.detailEnhance(original_image, sigma_s=10, sigma_r=0.15) cv2.imwrite("o.png", ok) image1 = Image.open("o.png") im1 = image1.convert("RGB") a = check_filename("pdf/scan.pdf") im1.save(a) await xx.edit( f"Done, Now Reply Another Image/pdf if completed then use {HNDLR}pdsend to merge nd send all as pdf", ) os.remove("o.png") elif ultt.endswith(".pdf"): a = check_filename("pdf/scan.pdf") await event.client.download_media(ok, a) await eor( event, f"Done, Now Reply Another Image/pdf if completed then use {HNDLR}pdsend to merge nd send all as pdf", ) else: await event.eor("`Reply to a Image/pdf only...`") os.remove(ultt)
null
5,802
import glob import os import shutil import time import cv2 import numpy as np from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from telethon.errors.rpcerrorlist import PhotoSaveFileInvalidError from pyUltroid.fns.tools import four_point_transform from . import ( HNDLR, LOGS, bash, check_filename, downloader, eor, get_string, ultroid_cmd, ) if not os.path.isdir("pdf"): os.mkdir("pdf") pattern="pdf( (.*)|$)", async def sendpdf(event): if not os.path.exists("pdf/scan.pdf"): await eor( event, "first select pages by replying .pdsave of which u want to make multi page pdf file", ) return msg = event.pattern_match.group(1).strip() ok = f"{msg}.pdf" if msg else "My PDF File.pdf" merger = PdfFileMerger() afl = glob.glob("pdf/*") ok_ = [*sorted(afl)] for item in ok_: if item.endswith("pdf"): merger.append(item) merger.write(ok) await event.client.send_file(event.chat_id, ok_, reply_to=event.reply_to_msg_id) os.remove(ok_) shutil.rmtree("pdf/") os.makedirs("pdf/")
null
5,803
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.greetings_db import ( add_goodbye, add_thanks, add_welcome, delete_goodbye, delete_welcome, get_goodbye, get_welcome, must_thank, remove_thanks, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import HNDLR, eor, get_string, mediainfo, ultroid_cmd from ._inline import something def add_welcome(chat, msg, media, button): from .. import * def get_msg_button(texts: str): def format_btn(buttons: list): async def setwel(event): x = await event.eor(get_string("com_1")) r = await event.get_reply_message() btn = format_btn(r.buttons) if (r and r.buttons) else None try: text = event.text.split(maxsplit=1)[1] except IndexError: text = r.text if r else None if r and r.media: wut = mediainfo(r.media) if wut.startswith(("pic", "gif")): dl = await r.download_media() variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" elif wut == "video": if r.media.document.size > 8 * 1000 * 1000: return await eor(x, get_string("com_4"), time=5) dl = await r.download_media() variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" elif wut == "web": m = None else: m = pack_bot_file_id(r.media) if r.text: txt = r.text if not btn: txt, btn = get_msg_button(r.text) add_welcome(event.chat_id, txt, m, btn) else: add_welcome(event.chat_id, None, m, btn) await eor(x, get_string("grt_1")) elif text: if not btn: txt, btn = get_msg_button(text) add_welcome(event.chat_id, txt, None, btn) await eor(x, get_string("grt_1")) else: await eor(x, get_string("grt_3"), time=5)
null
5,804
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.greetings_db import ( add_goodbye, add_thanks, add_welcome, delete_goodbye, delete_welcome, get_goodbye, get_welcome, must_thank, remove_thanks, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import HNDLR, eor, get_string, mediainfo, ultroid_cmd from ._inline import something def get_welcome(chat): ok = get_stuff("WELCOME") return ok.get(chat) def delete_welcome(chat): ok = get_stuff("WELCOME") if ok.get(chat): ok.pop(chat) return udB.set_key("WELCOME", ok) async def clearwel(event): if not get_welcome(event.chat_id): return await event.eor(get_string("grt_4"), time=5) delete_welcome(event.chat_id) await event.eor(get_string("grt_5"), time=5)
null
5,805
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.greetings_db import ( add_goodbye, add_thanks, add_welcome, delete_goodbye, delete_welcome, get_goodbye, get_welcome, must_thank, remove_thanks, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import HNDLR, eor, get_string, mediainfo, ultroid_cmd from ._inline import something def get_welcome(chat): ok = get_stuff("WELCOME") return ok.get(chat) from .. import * 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 listwel(event): wel = get_welcome(event.chat_id) if not wel: return await event.eor(get_string("grt_4"), time=5) msgg, med = wel["welcome"], wel["media"] if wel.get("button"): btn = create_tl_btn(wel["button"]) return await something(event, msgg, med, btn) await event.reply(f"**Welcome Note in this chat**\n\n`{msgg}`", file=med) await event.delete()
null
5,806
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.greetings_db import ( add_goodbye, add_thanks, add_welcome, delete_goodbye, delete_welcome, get_goodbye, get_welcome, must_thank, remove_thanks, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import HNDLR, eor, get_string, mediainfo, ultroid_cmd from ._inline import something def add_goodbye(chat, msg, media, button): ok = get_stuff("GOODBYE") ok.update({chat: {"goodbye": msg, "media": media, "button": button}}) return udB.set_key("GOODBYE", 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 setgb(event): x = await event.eor(get_string("com_1")) r = await event.get_reply_message() btn = format_btn(r.buttons) if (r and r.buttons) else None try: text = event.text.split(maxsplit=1)[1] except IndexError: text = r.text if r else None if r and r.media: wut = mediainfo(r.media) if wut.startswith(("pic", "gif")): dl = await r.download_media() variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" elif wut == "video": if r.media.document.size > 8 * 1000 * 1000: return await eor(x, get_string("com_4"), time=5) dl = await r.download_media() variable = uf(dl) os.remove(dl) m = f"https://graph.org{variable[0]}" elif wut == "web": m = None else: m = pack_bot_file_id(r.media) if r.text: txt = r.text if not btn: txt, btn = get_msg_button(r.text) add_goodbye(event.chat_id, txt, m, btn) else: add_goodbye(event.chat_id, None, m, btn) await eor(x, "`Goodbye note saved`") elif text: if not btn: txt, btn = get_msg_button(text) add_goodbye(event.chat_id, txt, None, btn) await eor(x, "`Goodbye note saved`") else: await eor(x, get_string("grt_7"), time=5)
null
5,807
import os from telegraph import upload_file as uf from telethon.utils import pack_bot_file_id from pyUltroid.dB.greetings_db import ( add_goodbye, add_thanks, add_welcome, delete_goodbye, delete_welcome, get_goodbye, get_welcome, must_thank, remove_thanks, ) from pyUltroid.fns.tools import create_tl_btn, format_btn, get_msg_button from . import HNDLR, eor, get_string, mediainfo, ultroid_cmd from ._inline import something def get_goodbye(chat): ok = get_stuff("GOODBYE") return ok.get(chat) def delete_goodbye(chat): ok = get_stuff("GOODBYE") if ok.get(chat): ok.pop(chat) return udB.set_key("GOODBYE", ok) async def clearwgb(event): if not get_goodbye(event.chat_id): return await event.eor(get_string("grt_6"), time=5) delete_goodbye(event.chat_id) await event.eor("`Goodbye Note Deleted`", time=5)
null