def load_module(shortname): if shortname.startswith("__"): pass elif shortname.endswith("_"): import LEGENDX.utils path = Path(f"LEGENDX/plugins/{shortname}.py") name = "LEGENDX.plugins.{}".format(shortname) spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) LOGS.info("Successfully imported " + shortname) else: import LEGENDX.utils path = Path(f"LEGENDX/plugins/{shortname}.py") name = "LEGENDX.plugins.{}".format(shortname) spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) mod.bot = bot mod.tgbot = bot.tgbot mod.Var = Var mod.command = command mod.logger = logging.getLogger(shortname) # support for uniborg sys.modules["uniborg.util"] = LEGENDX.utils mod.Config = Config mod.borg = bot mod.edit_or_reply = edit_or_reply # support for paperplaneextended sys.modules["LEGENDX.events"] = LEGENDX.utils spec.loader.exec_module(mod) # for imports sys.modules["LEGENDX.plugins." + shortname] = mod LOGS.info("Successfully imported " + shortname)
async def pressf(f): """Pays respects""" args = f.text.split() arg = (f.text.split(' ', 1))[1] if len(args) > 1 else None if len(args) == 1: r = random.randint(0, 3) LOGS.info(r) if r == 0: await f.edit("┏━━━┓\n┃┏━━┛\n┃┗━━┓\n┃┏━━┛\n┃┃\n┗┛") elif r == 1: await f.edit("╭━━━╮\n┃╭━━╯\n┃╰━━╮\n┃╭━━╯\n┃┃\n╰╯") else: arg = "F" if arg is not None: out = "" F_LENGTHS = [5, 1, 1, 4, 1, 1, 1] for line in F_LENGTHS: c = max(round(line / len(arg)), 1) out += (arg * c) + "\n" await f.edit("`" + out + "`")
def extract_w_h(file): """ Get width and height of media """ command_to_run = [ "ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", file, ] # https://stackoverflow.com/a/11236144/4723940 try: t_response = subprocess.check_output(command_to_run, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: LOGS.warning(exc) else: x_reponse = t_response.decode("UTF-8") response_json = json.loads(x_reponse) width = int(response_json["streams"][0]["width"]) height = int(response_json["streams"][0]["height"]) return width, height
async def download(target_file): """ For .dl command, download files to the LEGENDX's server. """ await target_file.edit("Processing using LEGENDX server ( ◜‿◝ )♡") input_str = target_file.pattern_match.group(1) if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() # https://stackoverflow.com/a/761825/4723940 file_name = file_name.strip() head, tail = os.path.split(file_name) if head: if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)): os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)) file_name = os.path.join(head, tail) downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) c_time = time.time() display_message = None while not downloader.isFinished(): status = downloader.get_status().capitalize() total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() elapsed_time = round(diff) * 1000 progress_str = "[{0}{1}] {2}%".format( ''.join(["▰" for i in range(math.floor(percentage / 10))]), ''.join(["▱" for i in range(10 - math.floor(percentage / 10))]), round(percentage, 2)) estimated_total_time = downloader.get_eta(human=True) try: current_message = f"{status}..\ \nFOR : F.R.I.D.A.Y™ AND INDIANBOT™\ \nURL: {url}\ \nFile Name: {file_name}\ \n{progress_str}\ \n{humanbytes(downloaded)} of {humanbytes(total_length)}\ \nETA: {estimated_total_time}" if round(diff % 10.00) == 0 and current_message != display_message: await target_file.edit(current_message) display_message = current_message except Exception as e: LOGS.info(str(e)) if downloader.isSuccessful(): await target_file.edit("Downloaded to `{}` successfully !!".format( downloaded_file_name)) else: await target_file.edit("Incorrect URL\n{}".format(url)) elif target_file.reply_to_msg_id: try: c_time = time.time() downloaded_file_name = await target_file.client.download_media( await target_file.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, target_file, c_time, "Downloading..."))) except Exception as e: # pylint:disable=C0103,W0703 await target_file.edit(str(e)) else: await target_file.edit("Downloaded to `{}` successfully !!".format( downloaded_file_name)) else: await target_file.edit( "Reply to a message to download to my local server.")
async def uploadir(udir_event): """ For .uploadir command, allows you to upload everything from a folder in the server""" input_str = udir_event.pattern_match.group(1) if os.path.exists(input_str): await udir_event.edit("Downloading Using Userbot Server....") lst_of_files = [] for r, d, f in os.walk(input_str): for file in f: lst_of_files.append(os.path.join(r, file)) for file in d: lst_of_files.append(os.path.join(r, file)) LOGS.info(lst_of_files) uploaded = 0 await udir_event.edit( "Found {} files. Uploading will start soon. Please wait!".format( len(lst_of_files))) for single_file in lst_of_files: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) c_time = time.time() if not caption_rts.lower().endswith(".mp4"): await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, force_document=False, allow_cache=False, reply_to=udir_event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, udir_event, c_time, "Uploading in Progress.......", single_file))) else: thumb_image = os.path.join(input_str, "thumb.jpg") c_time = time.time() metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, thumb=thumb_image, force_document=False, allow_cache=False, reply_to=udir_event.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, udir_event, c_time, "Uploading...", single_file))) os.remove(single_file) uploaded = uploaded + 1 await udir_event.edit( "Uploaded {} files successfully !!".format(uploaded)) else: await udir_event.edit("404: Directory Not Found")
async def mega_downloader(megadl): catevent = await edit_or_reply(megadl, "`Collecting information...`") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) msg_link = await megadl.get_reply_message() link = megadl.pattern_match.group(1) if link: pass elif msg_link: link = msg_link.text else: return await catevent.edit("Usage: `.mega` **<MEGA.nz link>**") try: link = re.findall(r"\bhttps?://.*mega.*\.nz\S+", link)[0] # - Mega changed their URL again - if "file" in link: link = link.replace("#", "!").replace("file/", "#!") elif "folder" in link or "#F" in link or "#N" in link: await catevent.edit("`folder download support are removed...`") return except IndexError: await catevent.edit("`MEGA.nz link not found...`") return None cmd = f"bin/megadown -q -m {link}" result = await subprocess_run(catevent, cmd) try: data = json.loads(result[0]) except json.JSONDecodeError: await catevent.edit("**JSONDecodeError**: `failed to extract link...`") return None except (IndexError, TypeError): return file_name = data["file_name"] file_url = data["url"] hex_key = data["hex_key"] hex_raw_key = data["hex_raw_key"] temp_file_name = file_name + ".temp" temp_file_path = os.path.join(TEMP_DOWNLOAD_DIRECTORY, temp_file_name) file_path = os.path.join(TEMP_DOWNLOAD_DIRECTORY, file_name) if os.path.isfile(file_path): try: raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), file_path) except FileExistsError as e: await catevent.edit(f"`{str(e)}`") return None downloader = SmartDL(file_url, temp_file_path, progress_bar=False) display_message = None try: downloader.start(blocking=False) except HTTPError as e: await catevent.edit(f"**HTTPError**: `{str(e)}`") return None start = time.time() while not downloader.isFinished(): status = downloader.get_status().capitalize() total_length = downloader.filesize or None downloaded = downloader.get_dl_size() percentage = int(downloader.get_progress() * 100) speed = downloader.get_speed(human=True) estimated_total_time = round(downloader.get_eta()) progress_str = "`{0}` | [{1}{2}] `{3}%`".format( status, "".join(["▰" for i in range(math.floor(percentage / 10))]), "".join(["▱" for i in range(10 - math.floor(percentage / 10))]), round(percentage, 2), ) diff = time.time() - start try: current_message = ( f"**➥file name : **`{file_name}`\n\n" "**➥Status**\n" f"{progress_str}\n" f"`{humanbytes(downloaded)}` of `{humanbytes(total_length)}`" f" @ `{speed}`\n" f"**➥ETA -> **`{time_formatter(estimated_total_time)}`\n" f"**➥ Duration -> **`{time_formatter(round(diff))}`" ) if round(diff % 15.00) == 0 and ( display_message != current_message or total_length == downloaded ): await catevent.edit(current_message) await asyncio.sleep(1) display_message = current_message except Exception: pass finally: if status == "Combining": wait = round(downloader.get_eta()) await asyncio.sleep(wait) if downloader.isSuccessful(): download_time = round(downloader.get_dl_time() + wait) try: P = multiprocessing.Process( target=await decrypt_file( catevent, file_path, temp_file_path, hex_key, hex_raw_key ), name="Decrypt_File", ) P.start() P.join() except FileNotFoundError as e: await catevent.edit(f"`{str(e)}`") return None else: await catevent.edit( f"**➥ file name : **`{file_name}`\n\n" f"**➥ Successfully downloaded in : ** `{file_path}`.\n" f"**➥ Download took :** {time_formatter(download_time)}." ) return None else: await megadl.edit( "`Failed to download, " "check heroku Logs for more details.`" ) for e in downloader.get_errors(): LOGS.info(str(e)) return
async def glitch(event): await event.edit("```Glitching Wait...```") cmd = event.pattern_match.group(1) input = event.pattern_match.group(2) reply = await event.get_reply_message() if not (reply and (reply.media)): await event.edit("`Media not found...`") return if not os.path.isdir("./temp/"): os.mkdir("./temp/") reply_to_id = event.reply_to_msg_id remixsticker = await reply.download_media(file="./temp/") if not remixsticker.endswith(('.mp4', '.webp', '.tgs', '.png', '.jpg')): os.remove(remixsticker) await event.edit("`Media not found...`") return file = os.path.join("./temp/", "glitch.png") if input: if not input.isdigit(): await event.edit("`You input is invalid, check help`") return input = int(input) if not 0 < input < 9: await event.edit("`Invalid Range...`") return else: input = 2 if remixsticker.endswith(".tgs"): file = os.path.join("./temp/", "glitch.png") cmd = f"lottie_convert.py --frame 0 -if lottie -of png {remixsticker} {file}" stdout, stderr = (await runcmd(cmd))[:2] if not os.path.lexists(file): await event.edit("`remixsticker not found...`") LOGS.info(stdout + stderr) glitch_file = file elif remixsticker.endswith(".webp"): file = os.path.join("./temp/", "glitch.png") os.rename(remixsticker, file) if not os.path.lexists(file): await event.edit("`remixsticker not found... `") return glitch_file = file elif remixsticker.endswith(".mp4"): file = os.path.join("./temp/", "glitch.png") await take_screen_shot(remixsticker, 0, file) if not os.path.lexists(file): await event.edit("```remixsticker not found...```") return glitch_file = file else: glitch_file = remixsticker glitcher = ImageGlitcher() img = Image.open(glitch_file) if cmd == "glitchs": glitched = "./temp/" + "glitched.webp" glitch_img = glitcher.glitch_image(img, input, color_offset=True) glitch_img.save(glitched) await bot.send_file( event.chat_id, glitched, reply_to_message_id=reply_to_id) os.remove(glitched) await event.delete() elif cmd == "glitch": Glitched = "./temp/" + "glitch.gif" glitch_img = glitcher.glitch_image( img, input, color_offset=True, gif=True) DURATION = 200 LOOP = 0 glitch_img[0].save( Glitched, format='GIF', append_images=glitch_img[1:], save_all=True, duration=DURATION, loop=LOOP) await bot.send_file( event.chat_id, Glitched, reply_to_message_id=reply_to_id) os.remove(Glitched) await event.delete() for files in (remixsticker, glitch_file): if files and os.path.exists(files): os.remove(files)