async def quotecmd(message: Message): """quotecmd""" asyncio.get_event_loop().create_task(message.delete()) args = message.input_str replied = message.reply_to_message async with userge.conversation('QuotLyBot') as conv: try: if replied and not args: await conv.forward_message(replied) else: if not args: await message.err('input not found!') return await conv.send_message(args) except YouBlockedUser: await message.edit('first **unblock** @QuotLyBot') return quote = await conv.get_response(mark_read=True) if not quote.sticker: await message.err('something went wrong!') else: message_id = replied.message_id if replied else None await userge.send_sticker(chat_id=message.chat.id, sticker=quote.sticker.file_id, file_ref=quote.sticker.file_ref, reply_to_message_id=message_id)
async def jio_music(message: Message): bot_ = "JioDLBot" query_ = message.input_str result = await userge.get_inline_bot_results(bot_, query_) if not result.results: await message.edit(f"Song <code>{query_}</code> not found...", del_in=5) return try: log_ = await userge.send_inline_bot_result( Config.LOG_CHANNEL_ID, query_id=result.query_id, result_id=result.results[0].id, ) await gather( userge.copy_message( chat_id=message.chat.id, from_chat_id=Config.LOG_CHANNEL_ID, message_id=log_.updates[0].id, ), message.delete(), ) except BaseException as e: await message.err( f"`Something unexpected happend.`\n<b>ERROR:</b> `{e}`", del_in=5)
async def webss(message: Message): if Config.GOOGLE_CHROME_BIN is None: await message.err("need to install Google Chrome. Module Stopping") return link_match = match(r"\bhttps?://.*\.\S+", message.input_str) if not link_match: await message.err("`I need a valid link to take screenshots from.`") return link = link_match.group() await message.edit("`Processing ...`") chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = Config.GOOGLE_CHROME_BIN chrome_options.add_argument("--ignore-certificate-errors") chrome_options.add_argument("--test-type") chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-gpu") driver = webdriver.Chrome(chrome_options=chrome_options) driver.get(link) height = driver.execute_script( "return Math.max(document.body.scrollHeight, document.body.offsetHeight, " "document.documentElement.clientHeight, document.documentElement.scrollHeight, " "document.documentElement.offsetHeight);" ) width = driver.execute_script( "return Math.max(document.body.scrollWidth, document.body.offsetWidth, " "document.documentElement.clientWidth, document.documentElement.scrollWidth, " "document.documentElement.offsetWidth);" ) driver.set_window_size(width + 125, height + 125) wait_for = height / 1000 await message.edit( f"`Generating screenshot of the page...`" f"\n`Height of page = {height}px`" f"\n`Width of page = {width}px`" f"\n`Waiting ({int(wait_for)}s) for the page to load.`" ) await asyncio.sleep(int(wait_for)) im_png = driver.get_screenshot_as_png() driver.close() message_id = message.message_id if message.reply_to_message: message_id = message.reply_to_message.message_id file_path = os.path.join(Config.DOWN_PATH, "webss.png") async with aiofiles.open(file_path, "wb") as out_file: await out_file.write(im_png) await asyncio.gather( message.delete(), message.client.send_document( chat_id=message.chat.id, document=file_path, caption=link, reply_to_message_id=message_id, ), ) os.remove(file_path) driver.quit()
async def check_and_send(message: Message, *args, **kwargs): replied = message.reply_to_message if replied: await asyncio.gather( message.delete(), replied.reply(*args, **kwargs) ) else: await message.edit(*args, **kwargs)
async def video_compress(message: Message): """ compress video """ replied = message.reply_to_message if message.filtered_input_str and ' ' not in message.filtered_input_str: return await message.err("path not specified!") percentage, input_str = message.filtered_input_str.split(' ', 1) data = await get_media_path_and_name(message, input_str=input_str) if not data: return dl_loc, file_name = data FF_MPEG_DOWN_LOAD_MEDIA_PATH.mkdir(parents=True, exist_ok=True) await message.edit("`Compressing media...`") # https://github.com/kkroening/ffmpeg-python/issues/545 info = await probe(dl_loc) total_time = floor(float(info['streams'][0]['duration'])) target_percentage = int(percentage) filesize = Path(dl_loc).stat().st_size # https://github.com/AbirHasan2005/VideoCompress/blob/main/bot/helper_funcs/ffmpeg.py#L60 calculated_percentage = 100 - target_percentage target_size = (calculated_percentage / 100) * filesize target_bitrate = int(floor(target_size * 8 / total_time)) if target_bitrate // 1000000 >= 1: bitrate = str(target_bitrate // 1000000) + "M" else: bitrate = str(target_bitrate // 1000) + "k" video_file = f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/compressed_{file_name}" start = datetime.now() try: await run( ffmpeg.input(dl_loc).output(video_file, video_bitrate=bitrate, bufsize=bitrate, vcodec="h264", preset="ultrafast")) except ffmpeg.Error as e: await message.err(f"{e.stderr}") else: message_id = replied.id if replied else None caption = ( f"[{humanbytes(Path(video_file).stat().st_size)}]\n" f"{replied.caption if hasattr(replied, 'media') else file_name}") await message.edit( f"`Done in in {(datetime.now() - start).seconds} seconds!`") await asyncio.gather( message.delete(), message.client.send_video(chat_id=message.chat.id, reply_to_message_id=message_id, video=video_file, caption=caption)) finally: if '-d' in message.flags: Path(video_file).unlink(missing_ok=True) Path(f"downloads/{file_name}").unlink(missing_ok=True)
async def quotecmd(message: Message): """quotecmd""" quote_list = [] replied = message.reply_to_message if replied and "l" in message.flags and not message.filtered_input_str: args = "" limit = message.flags.get("l", 1) if limit.isdigit(): limit = int(limit) else: return await message.err("give valid no. of message to quote", del_in=3) num = min(limit, 24) async for msg in userge.iter_history( message.chat.id, limit=num, offset_id=replied.message_id, reverse=True ): if msg.message_id != message.message_id: quote_list.append(msg.message_id) else: args = message.input_str quote_list.append(replied.message_id) asyncio.get_event_loop().create_task(message.delete()) async with userge.conversation("QuotLyBot") as conv: try: if quote_list and not args: await userge.forward_messages("QuotLyBot", message.chat.id, quote_list) else: if not args: await message.err("input not found!") return await conv.send_message(args) except YouBlockedUser: await message.edit("first **unblock** @QuotLyBot") return quote = await conv.get_response(mark_read=True) if not (quote.sticker or quote.document): await message.err("something went wrong!") else: message_id = replied.message_id if replied else None if quote.sticker: await userge.send_sticker( chat_id=message.chat.id, sticker=quote.sticker.file_id, file_ref=quote.sticker.file_ref, reply_to_message_id=message_id, ) else: await userge.send_document( chat_id=message.chat.id, document=quote.document.file_id, file_ref=quote.document.file_ref, reply_to_message_id=message_id, )
async def translateme(message: Message): text = message.filtered_input_str flags = message.flags replied = message.reply_to_message is_poll = False if replied: if replied.poll: is_poll = True text = f'{replied.poll.question}' for option in replied.poll.options: text += f'\n\n\n{option.text}' else: text = replied.text or replied.caption if not text: return await message.err( "Give a text or reply to a message to translate!") if len(flags) == 2: src, dest = list(flags) elif len(flags) == 1: src, dest = 'auto', list(flags)[0] else: src, dest = 'auto', translate.LANG text = get_emoji_regexp().sub(u'', text) await message.edit("`Translating ...`") try: reply_text = await _translate_this(text, dest, src) except ValueError: return await message.err("Invalid destination language.") if is_poll: options = reply_text.text.split('\n\n\n') if len(options) > 1: question = options.pop(0) await asyncio.gather( message.delete(), message.client.send_poll( chat_id=message.chat.id, question=question, options=options, is_anonymous=replied.poll.is_anonymous)) return source_lan = LANGUAGES[f'{reply_text.src.lower()}'] transl_lan = LANGUAGES[f'{reply_text.dest.lower()}'] output = f"**Source ({source_lan.title()}):**`\n{text}`\n\n\ **Translation ({transl_lan.title()}):**\n`{reply_text.text}`" await message.edit_or_send_as_file(text=output, caption="translated")
async def video_trim(message: Message): """ trim """ replied = message.reply_to_message if '|' not in message.filtered_input_str: return await message.err("path not specified!") match = re.search(r'(\d{2}:\d{2}:\d{2})? ?(\d{2}:\d{2}:\d{2})?', message.filtered_input_str.split('|', 1)[0]) if not (match and match.group(1) and match.group(2)): return await message.err("You muse specify end time at least!") data = await get_media_path_and_name( message, input_str=message.filtered_input_str.split('|', 1)[1]) if not data: return dl_loc, file_name = data FF_MPEG_DOWN_LOAD_MEDIA_PATH.mkdir(parents=True, exist_ok=True) await message.edit("`Trimming media...`") end_time = match.group(1) if not match.group(2) else match.group(2) start_time = match.group( 1) if match.group(1) and match.group(1) != end_time else "00:00:00" video_file = f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/trimmed_{file_name}" start = datetime.now() try: await run( ffmpeg.input(dl_loc, ss=start_time, to=end_time).output(video_file)) except ffmpeg.Error as e: await message.err(f"{e.stderr}") else: await message.edit( f"`Done in in {(datetime.now() - start).seconds} seconds!`") message_id = replied.id if replied else None caption = ( f"[{humanbytes(Path(video_file).stat().st_size)}]\n" f"{replied.caption if hasattr(replied, 'media') else file_name}") await asyncio.gather( message.delete(), message.client.send_video(chat_id=message.chat.id, reply_to_message_id=message_id, video=video_file, caption=caption)) finally: if '-d' in message.flags: Path(f"downloads/{file_name}").unlink(missing_ok=True) Path(video_file).unlink(missing_ok=True)
async def noformat_message(message: Message): reply = message.reply_to_message msg_text = None buttons = "" media = get_file_id(reply) if reply.text: msg_text = reply.text.html elif media: msg_text = reply.caption.html if reply.caption else None else: return await message.err( "Not Supported!, reply to a supported media type or text", del_in=5) if "-alt" in message.flags: lbr_ = "(" rbr_ = ")" else: lbr_ = "[" rbr_ = "]" if reply.reply_markup and not isinstance(reply.reply_markup, ReplyKeyboardRemove): for row in reply.reply_markup.inline_keyboard: firstbtn = True for btn in row: if btn.url: if firstbtn: buttons += f"[{btn.text}]{lbr_}buttonurl:{btn.url}{rbr_}" firstbtn = False else: buttons += f"[{btn.text}]{lbr_}buttonurl:{btn.url}:same{rbr_}" if media: await gather( message.delete(), message.client.send_cached_media( chat_id=message.chat.id, file_id=media, caption=f"{msg_text}{buttons}", reply_to_message_id=reply.message_id, parse_mode=None, ), ) else: await message.edit(f"{msg_text}{buttons}", parse_mode=None)
async def scale_video(message: Message): """ scale video quality """ replied = message.reply_to_message flags = message.flags if '-q' not in flags: return await message.err("You must specify a quality!") quality = int(flags.get('-q').rstrip('p')) custom_bitrate = flags.get('-b', "28") encoder = "libx265" if "-c" in flags else "h264" data = await get_media_path_and_name(message) if not data: return dl_loc, file_name = data FF_MPEG_DOWN_LOAD_MEDIA_PATH.mkdir(parents=True, exist_ok=True) await message.edit("`Scaling the video...`") video_file = f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/{quality}_{file_name}" start = datetime.now() try: await run( ffmpeg.input(dl_loc).filter("scale", -1, quality).output(video_file, vcodec=encoder, crf=custom_bitrate, preset="ultrafast")) except ffmpeg.Error as e: await message.err(f"{e.stderr}") else: message_id = replied.id if replied else None await message.edit( f"`Done in in {(datetime.now() - start).seconds} seconds!`") caption = ( f"[{humanbytes(Path(video_file).stat().st_size)}]\n" f"{replied.caption if hasattr(replied, 'media') else file_name}") await asyncio.gather( message.delete(), message.client.send_video(chat_id=message.chat.id, reply_to_message_id=message_id, video=video_file, caption=caption)) finally: if '-d' in message.flags: Path(video_file).unlink(missing_ok=True) Path(f"downloads/{file_name}").unlink(missing_ok=True)
async def manage_voice_chat(m: Message, gc: XPlayer): """Manage your voice chats.""" if not (m.client.is_bot or gc.chat_has_bot): return await m.err( "Bot Needed !, if bot is present in the group then try again with SUDO_TRIGGER." ) out = voice_chat_helpers_buttons() if m.client.is_bot: await m.edit(out[0], reply_markup=InlineKeyboardMarkup(out[1])) else: await asyncio.gather( m.delete(), userge.bot.send_message( m.chat.id, out[0], reply_markup=InlineKeyboardMarkup(out[1]), ), )
async def video_to_audio(message: Message): """ extract audio from video """ replied = message.reply_to_message custom_bitrate = "48000" if message.flags and '-b' in message.flags: custom_bitrate = message.flags.get('-b', "48000") data = await get_media_path_and_name(message) if not data: return dl_loc, file_name = data FF_MPEG_DOWN_LOAD_MEDIA_PATH.mkdir(parents=True, exist_ok=True) await message.edit("`Extracting audio...`") audio_file = f"{file_name.split('.')[0]}.mp3" start = datetime.now() try: await run( ffmpeg.input(dl_loc).output( f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/{audio_file}", format="mp3", audio_bitrate=custom_bitrate).overwrite_output()) except ffmpeg.Error as e: await message.err(f"{e.stderr}") else: await message.edit( f"`Done in in {(datetime.now() - start).seconds} seconds!`") message_id = replied.id if replied else None caption = ( f"[{humanbytes(Path(FF_MPEG_DOWN_LOAD_MEDIA_PATH / audio_file).stat().st_size)}]\n" f"{replied.caption if hasattr(replied, 'media') else file_name}") await asyncio.gather( message.delete(), message.client.send_audio( chat_id=message.chat.id, reply_to_message_id=message_id, audio=f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/{audio_file}", caption=caption)) finally: if '-d' in message.flags: Path(f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/{audio_file}").unlink( missing_ok=True) Path(f"downloads/{file_name}").unlink(missing_ok=True)
async def encode_x256(message: Message): """ encode using x256 """ replied = message.reply_to_message custom_bitrate = 28 if message.flags and '-b' in message.flags: custom_bitrate = int(message.flags.get('-b')) data = await get_media_path_and_name(message) if not data: return dl_loc, file_name = data FF_MPEG_DOWN_LOAD_MEDIA_PATH.mkdir(parents=True, exist_ok=True) video_file = f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/x256_{file_name}" await message.edit("`Encoding to x256...`") start = datetime.now() try: await run( ffmpeg.input(dl_loc).output(video_file, vcodec="libx265", crf=custom_bitrate, preset="ultrafast")) except ffmpeg.Error as e: await message.err(f"`{e.stderr}`") else: await message.edit( f"`Done in in {(datetime.now() - start).seconds} seconds!`") caption = ( f"[{humanbytes(Path(video_file).stat().st_size)}]\n" f"{replied.caption if hasattr(replied, 'media') else file_name}") message_id = replied.id if replied else None await asyncio.gather( message.delete(), message.client.send_video(chat_id=message.chat.id, reply_to_message_id=message_id, video=video_file, caption=caption)) finally: if '-d' in message.flags: Path(video_file).unlink(missing_ok=True) Path(f"downloads/{file_name}").unlink(missing_ok=True)
async def quotecmd(message: Message): """quotecmd""" asyncio.create_task(message.delete()) args = message.input_str replied = message.reply_to_message async with userge.conversation('QuotLyBot') as conv: try: if replied: await conv.forward_message(replied) else: if not args: await message.err('input not found!') return await conv.send_message(args) except YouBlockedUser: await message.edit('first **unblock** @QuotLyBot') return quote = await conv.get_response(mark_read=True) await userge.forward_messages(chat_id=message.chat.id, from_chat_id=conv.chat_id, message_ids=quote.message_id, as_copy=True)
async def deezing_(message: Message): """download music from deezer""" query_ = message.input_str if ";" in query_: split_ = query_.split(";", 1) song_, num = split_[0], split_[1] else: song_ = query_ num = "0" try: num = int(num) except BaseException: await message.edit("`Please enter a proper number after ';'...`", del_in=5) return bot_ = "deezermusicbot" song_ = capitaled(song_) await message.edit(f"Searching <b>{song_}</b> on deezer...") results = await userge.get_inline_bot_results(bot_, song_) if not results.results: await message.edit(f"Song <code>{song_}</code> not found...", del_in=5) return try: log_send = await userge.send_inline_bot_result( chat_id=Config.LOG_CHANNEL_ID, query_id=results.query_id, result_id=results.results[int(num)].id, ) await gather( userge.copy_message( chat_id=message.chat.id, from_chat_id=Config.LOG_CHANNEL_ID, message_id=log_send.updates[0].id, ), message.delete(), ) except BaseException as e: await message.err( f"`Something unexpected happend.`\n<b>ERROR:</b> `{e}`", del_in=5 )
async def inline_buttons(message: Message): await message.edit("<code>Creating an Inline Button...</code>") reply = message.reply_to_message msg_content = None media_valid = False media_id = 0 if reply: media_valid = bool(get_file_id(reply)) if message.input_str: msg_content = message.input_str if media_valid: media_id = (await reply.forward(Config.LOG_CHANNEL_ID)).message_id elif reply: if media_valid: media_id = (await reply.forward(Config.LOG_CHANNEL_ID)).message_id msg_content = reply.caption.html if reply.caption else None elif reply.text: msg_content = reply.text.html if not msg_content: return await message.err("Content not found", del_in=5) rnd_id = userge.rnd_id() msg_content = check_brackets(msg_content) InlineDB.save_msg(rnd_id, msg_content, media_valid, media_id) x = await userge.get_inline_bot_results( (await get_bot_info())["bot"].uname, f"btn_{rnd_id}" ) await gather( userge.send_inline_bot_result( chat_id=message.chat.id, query_id=x.query_id, result_id=x.results[0].id, ), message.delete(), )
async def video_thumbnail(message: Message): """ extract thumbnail """ replied = message.reply_to_message data = await get_media_path_and_name(message) if not data: return dl_loc, file_name = data FF_MPEG_DOWN_LOAD_MEDIA_PATH.mkdir(parents=True, exist_ok=True) await message.edit("`Extracting video thumbnail...`") thumbnail_file = f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/{file_name.split('.')[0]}.png" start = datetime.now() try: await run( ffmpeg.input(dl_loc, ss="00:01:00").filter('scale', 720, -1).output(thumbnail_file, vframes=1)) except ffmpeg.Error as e: await message.err(f"{e.stderr}") else: if not Path(thumbnail_file).exists(): return await message.err("not able to get thumbnail") await message.edit( f"`Done in in {(datetime.now() - start).seconds} seconds!`") message_id = replied.id if replied else None await asyncio.gather( message.delete(), message.client.send_photo(chat_id=message.chat.id, reply_to_message_id=message_id, photo=thumbnail_file, caption=replied.caption if hasattr( replied, 'media') else file_name)) finally: if '-d' in message.flags: Path(thumbnail_file).unlink(missing_ok=True) Path(f"downloads/{file_name}").unlink(missing_ok=True)
async def get_user(msg: Message): """ get last.fm user """ await msg.edit("`checking user...`") if msg.input_str: user = LastFm(msg).get_user(msg.input_str) else: user = LastFm(msg).get_user() out = f''' __Name:__ [{user.get_name()}]({unquote(user.get_url())}) __Country:__ `{user.get_country()}` ''' if user.get_loved_tracks(): out += '__GetLovedTracks:__\n' out += "\n".join([ f" `{i}. {a[0]} 😘`" for i, a in enumerate(user.get_loved_tracks(15), start=1) ]) else: out += '__GetLovedTracks:__ `No tracks found.`\n' if bool(user.get_now_playing()): out += '__NowPlaying:__ `True`\n' out += f' __● SongName:__ `{user.get_now_playing()}`' else: out += '__NowPlaying:__ `False`' if user.get_image(): path = os.path.join(Config.DOWN_PATH, f"{user.get_name()}.png") if not os.path.exists(path): await pool.run_in_thread(wget.download)(user.get_image(), path) else: path = "resources/no_image.png" await asyncio.gather( msg.delete(), msg.client.send_photo(chat_id=msg.chat.id, photo=path, caption=out))
async def carbon_(message: Message): if Config.GOOGLE_CHROME_BIN is None: replied = message.reply_to_message if replied: text = replied.text else: text = message.text if not text: await message.err("need input text!") return await message.edit("`Creating a Carbon...`") async with userge.conversation("CarbonNowShBot", timeout=30) as conv: try: await conv.send_message(text) except YouBlockedUser: await message.edit("first **unblock** @CarbonNowShBot") return response = await conv.get_response(mark_read=True) while not response.reply_markup: response = await conv.get_response(mark_read=True) await response.click(x=random.randint(0, 2), y=random.randint(0, 8)) response = await conv.get_response(mark_read=True) while not response.media: response = await conv.get_response(mark_read=True) caption = "\n".join(response.caption.split("\n")[0:2]) file_id = response.document.file_id await asyncio.gather( message.delete(), userge.send_document( chat_id=message.chat.id, document=file_id, caption="`" + caption + "`", reply_to_message_id=replied.message_id if replied else None, ), ) else: input_str = message.filtered_input_str replied = message.reply_to_message theme = "seti" lang = "auto" red = message.flags.get("r", random.randint(0, 255)) green = message.flags.get("g", random.randint(0, 255)) blue = message.flags.get("b", random.randint(0, 255)) alpha = message.flags.get("a", random.randint(0, 100)) bg_ = f"rgba({red}, {green}, {blue}, {alpha})" if replied and ( replied.text or (replied.document and "text" in replied.document.mime_type) ): message_id = replied.message_id if replied.document: await message.edit("`Downloading File...`") path_ = await message.client.download_media( replied, file_name=Config.DOWN_PATH ) async with aiofiles.open(path_) as file_: code = await file_.read() os.remove(path_) else: code = replied.text if input_str: if "|" in input_str: args = input_str.split("|") if len(args) == 2: theme = args[0].strip() lang = args[1].strip() else: theme = input_str elif input_str: message_id = message.message_id if "|" in input_str: args = input_str.split("|") if len(args) == 3: theme = args[0].strip() lang = args[1].strip() code = args[2].strip() elif len(args) == 2: theme = args[0].strip() code = args[1].strip() else: code = input_str else: await message.err("need input text!") return await message.edit("`Creating a Carbon...`") code = quote_plus(code) await message.edit("`Processing... 20%`") carbon_path = os.path.join(Config.DOWN_PATH, "carbon.png") if os.path.isfile(carbon_path): os.remove(carbon_path) url = CARBON.format(theme=theme, lang=lang, code=code, bg=bg_) if len(url) > 6590: await message.err("input too large!") return chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = Config.GOOGLE_CHROME_BIN chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": Config.DOWN_PATH} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(chrome_options=chrome_options) driver.get(url) await message.edit("`Processing... 40%`") driver.command_executor._commands[ "send_command" ] = ( # pylint: disable=protected-access "POST", "/session/$sessionId/chromium/send_command", ) params = { "cmd": "Page.setDownloadBehavior", "params": {"behavior": "allow", "downloadPath": Config.DOWN_PATH}, } driver.execute("send_command", params) # driver.find_element_by_xpath("//button[contains(text(),'Export')]").click() driver.find_element_by_id("export-menu").click() await asyncio.sleep(1) await message.edit("`Processing... 60%`") driver.find_element_by_xpath("//button[contains(text(),'4x')]").click() await asyncio.sleep(1) driver.find_element_by_id("export-png").click() await message.edit("`Processing... 80%`") while not os.path.isfile(carbon_path): await asyncio.sleep(0.5) await message.edit("`Processing... 100%`") await message.edit("`Uploading Carbon...`") await asyncio.gather( message.delete(), message.client.send_document( chat_id=message.chat.id, document=carbon_path, reply_to_message_id=message_id, ), ) os.remove(carbon_path) driver.quit()
async def lydia_session(message: Message): """ lydia command handler """ if CH_LYDIA_API is None: await message.edit( "Please Configure `CH_LYDIA_API` & `CUSTOM_REPLY_CHANNEL`" "\n\nAll Instructions are available" " in @UnofficialPluginsHelp") return await message.edit("`processing lydia...`") replied = message.reply_to_message if '-on' in message.flags and replied: user_id = replied.from_user.id if user_id in ACTIVE_CHATS: await message.edit("AI is already Enabled on Replied User", del_in=3) return data = await LYDIA_CHATS.find_one({'_id': user_id}) if not data: await message.edit("`creating new session...`") ses = await _create_lydia() await LYDIA_CHATS.insert_one({ '_id': user_id, 'session_id': ses.id, 'session_exp': ses.expires, 'active': True }) ACTIVE_CHATS[user_id] = (ses.id, ses.expires) else: await message.edit("`activating session...`") await LYDIA_CHATS.update_one({'_id': user_id}, {"$set": { 'active': True }}) ACTIVE_CHATS[user_id] = (data['session_id'], data['session_exp']) await message.edit("`AI Enabled for Replied User`", del_in=3) elif '-off' in message.flags and replied: user_id = replied.from_user.id if user_id not in ACTIVE_CHATS: await message.edit("How to delete a thing that doesn't Exist?", del_in=3) return await message.edit("`disactivating session...`") await LYDIA_CHATS.update_one({'_id': user_id}, {"$set": { 'active': False }}) del ACTIVE_CHATS[user_id] await message.edit("`AI Disable for Replied User`", del_in=3) # Group Features Won't be displayed in Help Info For Now 😉 elif '-enagrp' in message.flags: chat_id = message.chat.id if chat_id in ACTIVE_CHATS: await message.edit("AI is already Enabled on this chat", del_in=3) return data = await LYDIA_CHATS.find_one({'_id': chat_id}) if not data: await message.edit("`creating new session...`") ses = await _create_lydia() await LYDIA_CHATS.insert_one({ '_id': chat_id, 'session_id': ses.id, 'session_exp': ses.expires, 'active': True }) ACTIVE_CHATS[chat_id] = (ses.id, ses.expires) else: await message.edit("`activating session...`") await LYDIA_CHATS.update_one({'_id': chat_id}, {"$set": { 'active': True }}) ACTIVE_CHATS[chat_id] = (data['session_id'], data['session_exp']) await message.edit("`AI Enabled in Current Chat :D`", del_in=3) elif '-disgrp' in message.flags: chat_id = message.chat.id if chat_id not in ACTIVE_CHATS: await message.edit("AI wasn't enabled in current chat. >:(", del_in=3) return await message.edit("`disactivating session...`") await LYDIA_CHATS.update_one({'_id': chat_id}, {"$set": { 'active': False }}) del ACTIVE_CHATS[chat_id] await message.edit("`AI Disabled in Current Chat`", del_in=3) elif '-grps' in message.flags: msg = "**AI Enabled Chats**\n\n" for chat_id in ACTIVE_CHATS: if not str(chat_id).startswith("-100"): continue chat_ = await userge.get_chat(chat_id) title = chat_.title msg += f"{title} {chat_id}\n" await message.edit_or_send_as_file(msg) elif '-list' in message.flags: msg = "**AI Enabled User List**\n\n" for user_id in ACTIVE_CHATS: if str(user_id).startswith("-100"): continue try: u_info = await userge.get_user_dict(user_id) u_men = u_info['mention'] msg += f"{u_men}\n" except PeerIdInvalid: msg += f"[user](tg://user?id={user_id}) - `{user_id}`\n" await message.edit_or_send_as_file(msg) elif '-info' in message.flags: await asyncio.gather( message.reply_photo(photo="resources/lydia.jpg", caption=LYDIA_API_INFO), message.delete()) else: await asyncio.gather( message.reply_sticker("CAADAQAEAQAC0rXRRju3sbCT07jIFgQ"), message.delete())
async def carbon_(message: Message): if Config.GOOGLE_CHROME_BIN is None: replied = message.reply_to_message if replied: text = replied.text else: text = message.text if not text: await message.err("need input text!") return await message.edit("`Sedang Mengcarbon Sayang...`") async with userge.conversation("CarbonNowShBot", timeout=30) as conv: try: await conv.send_message(text) except YouBlockedUser: await message.edit('first **unblock** @CarbonNowShBot') return response = await conv.get_response(mark_read=True) while not response.reply_markup: response = await conv.get_response(mark_read=True) await response.click(x=random.randint(0, 2), y=random.randint(0, 8)) response = await conv.get_response(mark_read=True) while not response.media: response = await conv.get_response(mark_read=True) caption = "\n".join(response.caption.split("\n")[0:2]) file_id = response.document.file_id await asyncio.gather( message.delete(), userge.send_document(chat_id=message.chat.id, document=file_id, caption='`' + caption + '`', reply_to_message_id=replied.message_id if replied else None)) else: input_str = message.filtered_input_str replied = message.reply_to_message theme = 'seti' lang = 'auto' red = message.flags.get('r', random.randint(0, 255)) green = message.flags.get('g', random.randint(0, 255)) blue = message.flags.get('b', random.randint(0, 255)) alpha = message.flags.get('a', random.randint(0, 100)) bg_ = f"rgba({red}, {green}, {blue}, {alpha})" if replied and (replied.text or (replied.document and 'text' in replied.document.mime_type)): message_id = replied.message_id if replied.document: await message.edit("`Downloading File...`") path_ = await message.client.download_media( replied, file_name=Config.DOWN_PATH) async with aiofiles.open(path_) as file_: code = await file_.read() os.remove(path_) else: code = replied.text if input_str: if '|' in input_str: args = input_str.split('|') if len(args) == 2: theme = args[0].strip() lang = args[1].strip() else: theme = input_str elif input_str: message_id = message.message_id if '|' in input_str: args = input_str.split('|') if len(args) == 3: theme = args[0].strip() lang = args[1].strip() code = args[2].strip() elif len(args) == 2: theme = args[0].strip() code = args[1].strip() else: code = input_str else: await message.err("Masukan Text Dulu Dong Sayang !") return await message.edit( "`Oke Perintah Di Terima Sayang , Aku akan Ngeproses Carbon Mu Sayang...`" ) code = quote_plus(code) await message.edit("`Proses Sudah 20% Sayang`") carbon_path = os.path.join(Config.DOWN_PATH, "carbon.png") if os.path.isfile(carbon_path): os.remove(carbon_path) url = CARBON.format(theme=theme, lang=lang, code=code, bg=bg_) if len(url) > 2590: await message.err("input too large!") return chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = Config.GOOGLE_CHROME_BIN chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-gpu") prefs = {'download.default_directory': Config.DOWN_PATH} chrome_options.add_experimental_option('prefs', prefs) driver = webdriver.Chrome(chrome_options=chrome_options) driver.get(url) await message.edit("`Proses Sudah 40% Sayang`") driver.command_executor._commands["send_command"] = ( # pylint: disable=protected-access "POST", '/session/$sessionId/chromium/send_command') params = { 'cmd': 'Page.setDownloadBehavior', 'params': { 'behavior': 'allow', 'downloadPath': Config.DOWN_PATH } } driver.execute("send_command", params) # driver.find_element_by_xpath("//button[contains(text(),'Export')]").click() driver.find_element_by_id("export-menu").click() await asyncio.sleep(1) await message.edit("`Proses Sudah 60% Sayang`") driver.find_element_by_xpath("//button[contains(text(),'4x')]").click() await asyncio.sleep(1) driver.find_element_by_xpath( "//button[contains(text(),'PNG')]").click() await message.edit("`Proses Sudah 80% Sayang`") while not os.path.isfile(carbon_path): await asyncio.sleep(0.5) await message.edit("`Proses Sudah 100% Sayang`") await message.edit("`Mengupload Hasil Carbon Mu Sayang!...`") await asyncio.gather( message.delete(), message.client.send_photo(chat_id=message.chat.id, photo=carbon_path, reply_to_message_id=message_id)) os.remove(carbon_path) driver.quit()