def error_handler(update, context): """Log the error and send a telegram message to notify the developer.""" # Log the error before we do anything else, so we can see it even if something breaks. LOGGER.error(msg="Exception while handling an update:", exc_info=context.error) # traceback.format_exception returns the usual python message about an exception, but as a # list of strings rather than a single string, so we have to join them together. tb_list = traceback.format_exception( None, context.error, context.error.__traceback__ ) tb = "".join(tb_list) # Build the message with some markup and additional information about what happened. message = ( "An exception was raised while handling an update\n" "<pre>update = {}</pre>\n\n" "<pre>{}</pre>" ).format( html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False)), html.escape(tb), ) if len(message) >= 4096: message = message[:4096] # Finally, send the message context.bot.send_message(chat_id=OWNER_ID, text=message, parse_mode=ParseMode.HTML)
def shellExecute(bot: Bot, update: Update): cmd = update.message.text.split(' ', maxsplit=1) if len(cmd) == 1: sendMessage("No command provided!", bot, update) return LOGGER.info(cmd) output = shell(cmd[1]) if output[1].decode(): LOGGER.error(f"Shell: {output[1].decode()}") if len(output[0].decode()) > 4000: with open("shell.txt", 'w') as f: f.write(f"Output\n-----------\n{output[0].decode()}\n") if output[1]: f.write(f"STDError\n-----------\n{output[1].decode()}\n") with open("shell.txt", 'rb') as f: bot.send_document(document=f, filename=f.name, reply_to_message_id=update.message.message_id, chat_id=update.message.chat_id) else: if output[1].decode(): sendMessage(f"<code>{output[1].decode()}</code>", bot, update) return else: sendMessage(f"<code>{output[0].decode()}</code>", bot, update)
def __list_all_modules(): from os.path import dirname, basename, isfile import glob # This generates a list of modules in this folder for the * in __main__ to work. mod_paths = glob.glob(dirname(__file__) + "/*.py") all_modules = [ basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") and not f.endswith('__init__.py') ] if LOAD or NO_LOAD: to_load = LOAD if to_load: if not all( any(mod == module_name for module_name in all_modules) for mod in to_load): LOGGER.error("අවලංගු පැටවුම් නාම. ඉවත්වීම.") quit(1) else: to_load = all_modules if NO_LOAD: LOGGER.info("පැටවීම නොවේ: {}".format(NO_LOAD)) return [item for item in to_load if item not in NO_LOAD] return to_load return all_modules
def __list_all_modules(): from os.path import dirname, basename, isfile import glob # This generates a list of modules in this folder for the * in __main__ to work. mod_paths = glob.glob(dirname(__file__) + "/*.py") all_modules = [basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") and not f.endswith('__init__.py')] if LOAD or NO_LOAD: to_load = LOAD if to_load: if not all(any(mod == module_name for module_name in all_modules) for mod in to_load): LOGGER.error("Invalid loadorder names. Quitting.") quit(1) all_modules = sorted(set(all_modules) - set(to_load)) to_load = list(all_modules) + to_load else: to_load = all_modules if NO_LOAD: LOGGER.info("Not loading: {}".format(NO_LOAD)) return [item for item in to_load if item not in NO_LOAD] return to_load return all_modules
def shell(update: Update, context: CallbackContext): message = update.effective_message cmd = message.text.split(' ', 1) if len(cmd) == 1: message.reply_text('No command to execute was given.') return cmd = cmd[1] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() reply = '' stderr = stderr.decode() stdout = stdout.decode() if stdout: reply += f"*Stdout*\n`{stdout}`\n" LOGGER.info(f"Shell - {cmd} - {stdout}") if stderr: reply += f"*Stderr*\n`{stderr}`\n" LOGGER.error(f"Shell - {cmd} - {stderr}") if len(reply) > 3000: with open('shell_output.txt', 'w') as file: file.write(reply) with open('shell_output.txt', 'rb') as doc: context.bot.send_document(document=doc, filename=doc.name, reply_to_message_id=message.message_id, chat_id=message.chat_id) else: message.reply_text(reply, parse_mode=ParseMode.MARKDOWN)
def __list_all_modules(): from os.path import dirname, basename, isfile import glob # This generates a list of modules in this folder for the * in __main__ to work. mod_paths = glob.glob(dirname(__file__) + "/*.py") all_modules = [ basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") and not f.endswith('__init__.py') ] if sys.platform.startswith('win'): os.system('color') os.system('cls') else: os.system('clear') if LOAD or NO_LOAD: to_load = LOAD if to_load: if not all( any(mod == module_name for module_name in all_modules) for mod in to_load): LOGGER.error("Invalid loadorder names. Quitting.") quit(1) else: to_load = all_modules if NO_LOAD: LOGGER.info(f"Not loading: {NO_LOAD}") return [item for item in to_load if item not in NO_LOAD] return to_load return all_modules
async def song(client, message): chat_id = message.chat.id user_id = message.from_user["id"] args = get_arg(message) + " " + "song" if args.startswith(" "): await message.reply("Enter a song name. Check /help") return "" status = await message.reply("Processing...") video_link = yt_search(args) if not video_link: await status.edit("Song not found.") return "" yt = YouTube(video_link) audio = yt.streams.filter(only_audio=True).first() try: download = audio.download(filename=f"{str(user_id)}") except Exception as ex: await status.edit("Failed to download song") LOGGER.error(ex) return "" rename = os.rename(download, f"{str(user_id)}.mp3") await pbot.send_chat_action(message.chat.id, "upload_audio") await pbot.send_audio( chat_id=message.chat.id, audio=f"{str(user_id)}.mp3", duration=int(yt.length), title=str(yt.title), performer=str(yt.author), reply_to_message_id=message.message_id, ) await status.delete() os.remove(f"{str(user_id)}.mp3")
def blacklist_chats(bot: Bot, update: Update): chat = update.effective_chat if chat.id not in BL_CHATS: return try: chat.send_message( "This chat has been blacklisted! Head over to @PhoenixSupport to find out why!" ) chat.leave() raise DispatcherHandlerStop except TelegramError as e: LOGGER.error( f"Couldn't leave blacklisted chat: {chat.id} due to:\n{e}")
def log_for_entity(bot, chat, entity, log_chat, result, tags): try: response = requests.get(entity) if response.status_code == requests.codes.ok: result += f'{entity}' extracted = tldextract.extract(entity) if f"#{extracted.domain}" not in tags: tags.append(f"#{extracted.domain}") tags.sort() if tags: tags_string = " ".join(tags) result += f"\n\nTags:\n{tags_string}" send_log(bot, log_chat, chat.id, result) except Exception as e: LOGGER.info(f"Resource {entity} is not a valid url") LOGGER.error(e)
def error_handler(update: Update, context: CallbackContext) -> None: """Log the error and send a telegram message to notify the developer.""" # Log the error before we do anything else, so we can see it even if something breaks. LOGGER.error(msg="Exception while handling an update:", exc_info=context.error) if isinstance(context.error, SQLAlchemyError) or isinstance( context.error, DBAPIError): return # traceback.format_exception returns the usual python message about an exception, but as a # list of strings rather than a single string, so we have to join them together. else: tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) tb_string = "".join(tb_list) # Build the message with some markup and additional information about what happened. # You might need to add some logic to deal with messages longer than the 4096 character limit. message = ( f"An exception was raised while handling an update\n" f"update = {(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}" "\n\n" f"context.chat_data = {(str(context.chat_data))}\n\n" f"context.user_data = {(str(context.user_data))}\n\n" f"{(tb_string)}") key = (requests.post("https://nekobin.com/api/documents", json={ "content": message }).json().get("result").get("key")) url = f"https://nekobin.com/{key}.py" markup = InlineKeyboardMarkup( [[InlineKeyboardButton("Nekobin", url=url)]]) # Finally, send the message context.bot.send_message( chat_id=OWNER_ID, text="Your sugar mommy got some errors for you, you cute guy.", reply_markup=markup, )
def error_handler(update, context): """Log the error and send a telegram message to notify the developer.""" message = update.effective_message text = message.text.split(None, 1) LOGGER.error(msg="Error found, check dump below:", exc_info=context.error) # traceback.format_exception returns the usual python message about an exception, but as a # list of strings rather than a single string, so we have to join them together. tb_list = traceback.format_exception( None, context.error, context.error.__traceback__ ) trace = "".join(tb_list) # if only a single command with no args then if len(text) == 1: cmd = f"{text[0]}" args = "None" else: cmd, args = text # lets try to get as much information from the telegram update as possible payload = f"\n<b>- Command</b>:<code> {cmd}</code>" payload += f"\n<b>- Arguments</b>:<code> {args}</code>" payload += f"\n<b>- Error message</b>:\n<code>{context.error}</code>" # normally, we always have a user. If not, its either a channel or a poll update. if update.effective_user: payload += f" \n<b>- User</b>: {mention_html(update.effective_user.id, update.effective_user.first_name)}" # there are more situations when you don't get a chat if update.effective_chat: if update.effective_chat.title == None: payload += f" \n<b>- Chat</b>:<b> Bot PM</b>" else: invite_link = update.effective_chat.link if invite_link is None: payload += f" \n<b>- Chat</b>:<b> {update.effective_chat.title}</b>, chat is <b>private</b>" else: payload += f' \n<b>- Chat</b>:<a href="{invite_link}"><b> {update.effective_chat.title}</b></a>' # but only one where you have an empty payload by now: A poll (buuuh) if update.poll: payload += f" \n<b>- Poll id</b>: {update.poll.id}." # lets put this in a "well" formatted text text = f"<b>Error found while handling an update!</b> {payload}" # now paste the error (trace) in nekobin and make buttons # with url of log, as log in telegram message is hardly readable.. key = ( requests.post( "https://nekobin.com/api/documents", json={ "content": f"{trace}\n\n{json.dumps(update.to_dict(), indent=2, ensure_ascii=False)}" }, ) .json() .get("result") .get("key") ) markup = InlineKeyboardMarkup( [ [ InlineKeyboardButton( text="Full traceback on nekobin", url=f"https://nekobin.com/{key}.py", ), # InlineKeyboardButton( # text="Send traceback as message", # , # ), ] ] ) context.bot.send_message(OWNER_ID, text, reply_markup=markup, parse_mode="html")