async def execute_python(client: Client, message: Message): """ Execute any Python 3 code. Native async code is unsupported, so import asyncio and run it manually whenever you need it. Note that the client and message are available to use in this command. """ args = get_args(message.text or message.caption, maximum=1) if args: clear_timeout = 15 result_type = "Output" old_stdout = sys.stdout old_stderr = sys.stderr try: sys.stdout = StringIO( ) # Replace stdout and stderr to catch prints and unhandled errors sys.stderr = StringIO() exec(args, globals(), locals()) raw_output = sys.stdout.getvalue().strip().split( "\n") if sys.stdout.getvalue() else None if raw_output: output = "\n".join(raw_output[:7]) # Limit the output length if len(raw_output) > 7: output += "\n..." elif sys.stderr.getvalue( ): # In case we have something in our stderr, we treat it as an error result_type = "Error log" output = sys.stderr.getvalue().strip() else: output = "The script was successful..." text = "<b>Input:</b>\n<pre>{}</pre>\n\n<b>{}:</b>\n<pre>{}</pre>".format( quote_html(args), result_type, quote_html(output)) except Exception: etype, evalue, _ = sys.exc_info() text = "<b>Input:</b>\n<pre>{}</pre>\n\n<b>Error log:</b>\n<pre>{}</pre>".format( quote_html(args), quote_html("".join( traceback.format_exception_only( etype, evalue)).strip()), # A short message ) finally: # Always return to original stdout and stderr sys.stdout = old_stdout sys.stderr = old_stderr else: clear_timeout = 3.5 text = "Write the <b>python code</b> to be executed." await message.edit_text(text) await clean_up(client, message.chat.id, message.message_id, clear_after=clear_timeout)
async def flood_command(client: Client, message: Message): """ Classic flooder. It's quite dangerous so use it carefully. I'm not responsible for any harm or account losses. """ args = get_args(message.text or message.caption) if len(args) != 2 or not args[0].isdigit(): # Not enough arguments await message.edit_text( "Pass the number of messages and the text that will be repeated.\n\n<code>.flood 3 we are victors!</code>" ) await clean_up(client, message.chat.id, message.message_id) else: text_to_flood = quote_html(args[1]) await message.edit_text(text_to_flood ) # Edit the message with .flood command. for _ in range(int(args[0]) - 1): try: await message.reply_text(text_to_flood, quote=False, disable_web_page_preview=True) except FloodWait as ex: logger.error(f"Sleeping for {ex.x} seconds in .flood") await asyncio.sleep(ex.x) except RPCError as ex: logger.error(f"{ex} in .flood, stopping command!") break
async def flood_command(_, message: Message): """ Send a specified number of messages consecutively. Only for development and testing purposes. Using this command in malicious ways may lead to your profile loss, I'm not responsible for any damage caused. """ args = message.get_args() if len(args) != 2 or not args[0].isdigit(): # Not enough arguments await message.edit_text( "Pass the number of messages and the text that will be repeated." "\n\n<code>.flood 3 we are victors!</code>", ) else: await message.delete() for _ in range(int(args[0])): try: await message.reply_text( quote_html(args[1]), quote=False, disable_web_page_preview=True ) except FloodWait as ex: logger.error(f"Sleeping for {ex.x} seconds in .flood") await asyncio.sleep(ex.x) except RPCError as ex: logger.error(f"{ex} in .flood, stopping command!") break
async def execute_python(client: Client, message: Message): """ Execute <s>almost</s> any Python 3 code. Native async code is unsupported, so import asyncio and run it manually whenever you need it. Note that the Client and Message <b>are available</b> for you in here. Also, be wary of security threats when using this command, and <b>DO NOT</b> use any suspicious code given by other people. """ if args := message.get_args(maximum=1): clear_timeout = 20.5 result_type = "Output" old_stdout = sys.stdout old_stderr = sys.stderr try: sys.stdout = ( StringIO() ) # Replace stdout and stderr to catch prints and unhandled errors sys.stderr = StringIO() exec(args[0], globals(), locals()) raw_output = (sys.stdout.getvalue().strip().split("\n") if sys.stdout.getvalue() else None) if raw_output: output = "\n".join(raw_output[:7]) # Limit the output length if len(raw_output) > 7: output += "\n..." elif ( sys.stderr.getvalue() ): # In case we have something in our stderr, we treat it as an error result_type = "Error log" output = sys.stderr.getvalue().strip() else: output = "The script was successful..." text = "<b>Input:</b>\n<pre>{}</pre>\n\n<b>{}:</b>\n<pre>{}</pre>".format( quote_html(args[0]), result_type, quote_html(output)) except Exception: # noqa etype, evalue, _ = sys.exc_info() text = "<b>Input:</b>\n<pre>{}</pre>\n\n<b>Error log:</b>\n<pre>{}</pre>".format( quote_html(args[0]), quote_html("".join( traceback.format_exception_only( etype, evalue)).strip()), # A short message ) finally: # Always return to original stdout and stderr sys.stdout = old_stdout sys.stderr = old_stderr
def get_anime_info(response: dict) -> str: """ Get a ready-to-use info about an anime and return the whole text. :param response: JSON response :return: """ japanese_title = quote_html(response["title_romaji"]) english_title = quote_html( response["title_english"] ) if response["title_english"] else japanese_title episode = response["episode"] is_nsfw = "Yes" if response["is_adult"] else "No" if japanese_title == english_title: title_block = f"<b>Title:</b> <code>{japanese_title}</code>" else: title_block = ( f"<b>English title:</b> <code>{english_title}</code>\n<b>Japanese title:</b> <code>{japanese_title}</code>" ) if episode: minutes, seconds = divmod(int(response["at"]), 60) episode = f"\nEpisode <b>{episode}</b>, at <b>~{minutes:02d}:{seconds:02d}</b>" else: episode = "" anilist = ANILIST_URL.format(anime_id=response["anilist_id"]) if response["mal_id"]: myanimelist = MAL_URL.format(anime_id=response["mal_id"]) link_block = ( f'<b><a href="{myanimelist}">Watch on MyAnimeList</a>\n<a href="{anilist}">Watch on Anilist</a></b>' ) else: link_block = f'<b><a href="{anilist}">Watch on Anilist</a></b>' accuracy = (Decimal(response["similarity"]) * 100).quantize(Decimal(".01")) warn = ", <i>probably wrong</i>" if accuracy < 87 else "" full_text = f"{title_block}\n\nNSFW: <b>{is_nsfw}</b>\nAccuracy: <b>{accuracy}%</b>{warn}{episode}\n\n{link_block}" return full_text
def get_entity_info(entity: Union[User, Chat, ChatPreview]) -> str: """ Build info text according to a specified User or Chat object and return the result. :param entity: User/Chat/ChatPreview object of the target :return: """ if isinstance(entity, User): # It's a User object if entity.is_deleted: full_text = f"<b>{entity.first_name}</b>\n\nThis profile is deleted." else: dc_name = (f"{entity.dc_id}-{DC_LOCATIONS[entity.dc_id]}" if entity.dc_id else "Unavailable") full_text = ( f"<b>{entity.mention}</b>\n\n<b>ID</b>: " f"<code>{entity.id}</code>\nType: <b>user</b>\nIs bot: <b>" f"{STATUS[entity.is_bot]}</b>\nIs scam: " f"<b>{STATUS[entity.is_scam]}</b>\nData center: <b>{dc_name}</b>" ) elif isinstance(entity, ChatPreview): # It's a private chat preview full_text = (f"<b>{entity.title}</b>\n\nType: " f"<b>{entity.type}</b>\nIs private: <b>Yes</b>\n" f"Members count: <b>{entity.members_count}</b>" f"\n\n<i>Join this {entity.type} to get more info.</i>") else: # It's a Chat object dc_name = f"{entity.dc_id}-{DC_LOCATIONS[entity.dc_id]}" if entity.dc_id else "Unavailable" description = f"{quote_html(entity.description)}\n\n" if entity.description else "" linked_chat = (f"<code>{entity.linked_chat.id}</code>" if entity.linked_chat else "<b>None</b>") is_private = not bool(entity.username) if entity.username: title = f'<a href="https://t.me/{entity.username}">{entity.title}</a>' else: title = quote_html(entity.title) full_text = ( f"<b>{title}</b>\n\n{description}<b>ID</b>: " f"<code>{entity.id}</code>\nType: <b>{entity.type}</b>\n" f"Linked chat: {linked_chat}\nIs private: <b>{STATUS[is_private]}</b>\n" f"Is scam: <b>{STATUS[entity.is_scam]}</b>\nData center: <b>{dc_name}</b>" ) return full_text
def secure_text(cls, v): if not v: return None return quote_html(v)