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 get_user_id(username): # ensure valid userid if len(username) <= 5: return None if username.startswith("@"): username = username[1:] users = sql.get_userid_by_name(username) if not users: return None elif len(users) == 1: return users[0].user_id else: for user_obj in users: try: userdat = dispatcher.bot.get_chat(user_obj.user_id) if userdat.username == username: return userdat.id except BadRequest as excp: if excp.message == "Chat not found": pass else: LOGGER.exception("Error extracting user ID") return None
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 load order names. Quitting.") quit(1) 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 del_lockables(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message for lockable, filter in LOCK_TYPES.items(): if (filter(message) and sql.is_locked(chat.id, lockable) and can_delete(chat, bot.id)): if lockable == "bots": new_members = update.effective_message.new_chat_members for new_mem in new_members: if new_mem.is_bot: if not is_bot_admin(chat, bot.id): message.reply_text( tld(chat.id, "locks_lock_bots_no_admin")) return chat.kick_member(new_mem.id) message.reply_text(tld(chat.id, "locks_lock_bots_kick")) else: try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in lockables") break
def get_help(bot: Bot, update: Update): chat = update.effective_chat args = update.effective_message.text.split(None, 1) # ONLY send help in PM if chat.type != chat.PRIVATE: update.effective_message.reply_text( tld(chat.id, "help_pm_only"), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text=tld(chat.id, "btn_help"), url="t.me/{}?start=help".format(bot.username), ) ]]), ) return if len(args) >= 2: mod_name = None for x in HELPABLE: if args[1].lower() == HELPABLE[x].lower(): mod_name = tld(chat.id, "modname_" + x).strip() module = x break if mod_name: help_txt = tld(chat.id, module + "_help") if not help_txt: LOGGER.exception(f"Help string for {module} not found!") text = tld(chat.id, "here_is_help").format(mod_name, help_txt) send_help( chat.id, text, InlineKeyboardMarkup([[ InlineKeyboardButton( text=tld(chat.id, "btn_go_back"), callback_data="help_back", ) ]]), ) return update.effective_message.reply_text(tld( chat.id, "help_not_found").format(args[1]), parse_mode=ParseMode.HTML) return send_help( chat.id, tld(chat.id, "send-help").format(dispatcher.bot.first_name, tld(chat.id, "cmd_multitrigger")), )
def sban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] update.effective_message.delete() user_id, reason = extract_user_and_text(message, args) if not user_id: return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": return "" else: raise if is_user_ban_protected(chat, user_id, member): return "" if user_id == bot.id: return "" log = tld(chat.id, "bans_sban_logger").format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id, ) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) try: chat.kick_member(user_id) return log except BadRequest as excp: if excp.message == "Reply message not found": return log else: LOGGER.warning(update) LOGGER.exception( "ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) return ""
def help_button(bot: Bot, update: Update): query = update.callback_query chat = update.effective_chat back_match = re.match(r"help_back", query.data) mod_match = re.match(r"help_module\((.+?)\)", query.data) try: if mod_match: module = mod_match.group(1) mod_name = tld(chat.id, "modname_" + module).strip() help_txt = tld( chat.id, module + "_help") # tld_help(chat.id, HELPABLE[module].__mod_name__) if not help_txt: LOGGER.exception(f"Help string for {module} not found!") text = tld(chat.id, "here_is_help").format(mod_name, help_txt) bot.edit_message_text( chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text=tld(chat.id, "btn_go_back"), callback_data="help_back", ) ]]), disable_web_page_preview=True, ) elif back_match: bot.edit_message_text( chat_id=query.message.chat_id, message_id=query.message.message_id, text=tld(chat.id, "send-help").format(dispatcher.bot.first_name, tld(chat.id, "cmd_multitrigger")), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(chat.id, 0, HELPABLE, "help")), disable_web_page_preview=True, ) # ensure no spinny white circle bot.answer_callback_query(query.id) # query.message.delete() except BadRequest: pass
def rest_handler(bot: Bot, update: Update): msg = update.effective_message chat = update.effective_chat for restriction, filter in RESTRICTION_TYPES.items(): if (filter(msg) and sql.is_restr_locked(chat.id, restriction) and can_delete(chat, bot.id)): try: msg.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in restrictions") break
def snipe(bot: Bot, update: Update, args: List[str]): try: chat_id = str(args[0]) del args[0] except TypeError as excp: update.effective_message.reply_text( "Please give me a chat to echo to!") to_send = " ".join(args) if len(to_send) >= 2: try: bot.sendMessage(int(chat_id), str(to_send)) except TelegramError: LOGGER.warning("Couldn't send to group %s", str(chat_id)) update.effective_message.reply_text( "Couldn't send the message. Perhaps I'm not part of that group?" )
def user_join_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat user = update.effective_user msg = update.effective_message fed_id = sql.get_fed_id(chat.id) if is_user_fed_owner(fed_id, user.id): user_id = extract_user(msg, args) if user_id: user = bot.get_chat(user_id) elif not msg.reply_to_message and not args: user = msg.from_user elif not msg.reply_to_message and ( not args or (len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not msg.parse_entities([MessageEntity.TEXT_MENTION]))): msg.reply_text(tld(chat.id, "common_err_no_user")) return else: LOGGER.warning("error") getuser = sql.search_user_in_fed(fed_id, user_id) fed_id = sql.get_fed_id(chat.id) info = sql.get_fed_info(fed_id) get_owner = eval(info["fusers"])["owner"] get_owner = bot.get_chat(get_owner).id if user_id == get_owner: update.effective_message.reply_text( tld(chat.id, "feds_promote_owner")) return if getuser: update.effective_message.reply_text( tld(chat.id, "feds_promote_owner")) return if user_id == bot.id: update.effective_message.reply_text( tld(chat.id, "feds_promote_bot")) return res = sql.user_join_fed(fed_id, user_id) if res: update.effective_message.reply_text( tld(chat.id, "feds_promote_success")) else: update.effective_message.reply_text("") else: update.effective_message.reply_text(tld(chat.id, "feds_owner_only"))
def tld(chat_id, t, show_none=True): LANGUAGE = prev_locale(chat_id) if LANGUAGE: LOCALE = LANGUAGE.locale_name if LOCALE in ("en-US") and t in strings["en-US"]: result = decode( encode(strings["en-US"][t], "latin-1", "backslashreplace"), "unicode-escape", ) return result elif LOCALE in ("en-GB") and t in strings["en-GB"]: result = decode( encode(strings["en-GB"][t], "latin-1", "backslashreplace"), "unicode-escape", ) return result elif LOCALE in ("id") and t in strings["id"]: result = decode( encode(strings["id"][t], "latin-1", "backslashreplace"), "unicode-escape", ) return result elif LOCALE in ("ru") and t in strings["ru"]: result = decode( encode(strings["ru"][t], "latin-1", "backslashreplace"), "unicode-escape", ) return result elif LOCALE in ("es") and t in strings["es"]: result = decode( encode(strings["es"][t], "latin-1", "backslashreplace"), "unicode-escape", ) return result if t in strings["en-US"]: result = decode( encode(strings["en-US"][t], "latin-1", "backslashreplace"), "unicode-escape") return result err = f"No string found for {t}.\nReport it in @exusiaisupport." LOGGER.warning(err) return err
def del_blacklist_url(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message parsed_entities = message.parse_entities(types=["url"]) extracted_domains = [] for obj, url in parsed_entities.items(): extract_url = tldextract.extract(url) extracted_domains.append(extract_url.domain + "." + extract_url.suffix) for url in sql.get_blacklisted_urls(chat.id): if url in extracted_domains: try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def user_demote_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat user = update.effective_user fed_id = sql.get_fed_id(chat.id) if is_user_fed_owner(fed_id, user.id): msg = update.effective_message user_id = extract_user(msg, args) if user_id: user = bot.get_chat(user_id) elif not msg.reply_to_message and not args: user = msg.from_user elif not msg.reply_to_message and ( not args or (len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not msg.parse_entities([MessageEntity.TEXT_MENTION]))): msg.reply_text(tld(chat.id, "common_err_no_user")) return else: LOGGER.warning("error") if user_id == bot.id: update.effective_message.reply_text(tld(chat.id, "feds_demote_bot")) return if sql.search_user_in_fed(fed_id, user_id) == False: update.effective_message.reply_text( tld(chat.id, "feds_demote_target_not_admin")) return res = sql.user_demote_fed(fed_id, user_id) if res == True: update.effective_message.reply_text( tld(chat.id, "feds_demote_success")) else: update.effective_message.reply_text( tld(chat.id, "feds_demote_failed")) else: update.effective_message.reply_text(tld(chat.id, "feds_owner_only")) return
def del_blacklist(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message to_match = extract_text(message) if not to_match: return chat_filters = sql.get_chat_blacklist(chat.id) for trigger in chat_filters: pattern = r"( |^|[^\w])" + re.escape(trigger) + r"( |$|[^\w])" if re.search(pattern, to_match, flags=re.IGNORECASE): try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def broadcast(bot: Bot, update: Update): to_send = update.effective_message.text.split(None, 1) if len(to_send) >= 2: chats = sql.get_all_chats() or [] failed = 0 for chat in chats: try: bot.sendMessage(int(chat.chat_id), to_send[1]) sleep(0.1) except TelegramError: failed += 1 LOGGER.warning( "Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name), ) update.effective_message.reply_text( "Broadcast complete. {} groups failed to receive the message, probably " "due to being kicked.".format(failed))
def main(): # test_handler = CommandHandler("test", test) #Unused variable start_handler = CommandHandler("start", start, pass_args=True) help_handler = CommandHandler("help", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_") start_callback_handler = CallbackQueryHandler(send_start, pattern=r"bot_start") migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats) # dispatcher.add_handler(test_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(start_callback_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(migrate_handler) # dispatcher.add_error_handler(error_callback) # add antiflood processor Dispatcher.process_update = process_update LOGGER.info("Using long polling.") # updater.start_polling(timeout=15, read_latency=4, clean=True) updater.start_polling( poll_interval=0.0, timeout=10, clean=True, bootstrap_retries=-1, read_latency=3.0, ) LOGGER.info("Successfully loaded") if len(argv) not in (1, 3, 4): tbot.disconnect() else: tbot.run_until_disconnected() updater.idle()
def log_action(bot: Bot, update: Update, *args, **kwargs): try: result = func(bot, update, *args, **kwargs) except Exception: return chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] if result: if chat.type == chat.SUPERGROUP and chat.username: result += tld(chat.id, "log_channel_link").format( chat.username, message.message_id) log_chat = sql.get_chat_log_channel(chat.id) if log_chat: send_log(bot, log_chat, chat.id, result) elif result == "": pass else: LOGGER.warning( "%s was set as loggable, but had no return statement.", func) return result
def tld_list(chat_id, t): LANGUAGE = prev_locale(chat_id) if LANGUAGE: LOCALE = LANGUAGE.locale_name if LOCALE in ("en-US") and t in strings["en-US"]: return strings["en-US"][t] elif LOCALE in ("en-GB") and t in strings["en-GB"]: return strings["en-GB"][t] elif LOCALE in ("id") and t in strings["id"]: return strings["id"][t] elif LOCALE in ("ru") and t in strings["ru"]: return strings["ru"][t] elif LOCALE in ("es") and t in strings["es"]: return strings["es"][t] if t in strings["en-US"]: return strings["en-US"][t] LOGGER.warning(f"#NOSTR No string found for {t}.") return f"No string found for {t}.\nReport it in @exusiaisupport."
def setlog(bot: Bot, update: Update): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: message.reply_text(tld(chat.id, "log_channel_fwd_cmd")) elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception( "Error deleting message in log channel. Should work anyway though." ) try: bot.send_message( message.forward_from_chat.id, tld(chat.id, "log_channel_chn_curr_conf").format(chat.title or chat.first_name), ) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message(chat.id, tld(chat.id, "log_channel_link_success")) else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, tld(chat.id, "log_channel_link_success")) else: message.reply_text(tld(chat.id, "log_channel_invalid_message"), ParseMode.MARKDOWN)
def new_fed(bot: Bot, update: Update): chat = update.effective_chat user = update.effective_user message = update.effective_message if chat.type != "private": update.effective_message.reply_text(tld(chat.id, "common_cmd_pm_only")) return fednam = message.text.split(None, 1)[1] if not fednam == "": fed_id = str(uuid.uuid4()) fed_name = fednam LOGGER.info(fed_id) if user.id == int(OWNER_ID): fed_id = fed_name x = sql.new_fed(user.id, fed_name, fed_id) if not x: update.effective_message.reply_text( tld(chat.id, "feds_create_fail")) return update.effective_message.reply_text( tld(chat.id, "feds_create_success").format(fed_name, fed_id, fed_id), parse_mode=ParseMode.MARKDOWN, ) try: bot.send_message( MESSAGE_DUMP, tld(chat.id, "feds_create_success_logger").format(fed_name, fed_id), parse_mode=ParseMode.HTML, ) except Exception: LOGGER.warning("Cannot send a message to MESSAGE_DUMP") else: update.effective_message.reply_text(tld(chat.id, "feds_err_no_args"))
def send_log(bot: Bot, log_chat_id: str, orig_chat_id: str, result: str): try: bot.send_message(log_chat_id, result, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Chat not found": bot.send_message(orig_chat_id, "This log channel has been deleted - unsetting.") sql.stop_chat_logging(orig_chat_id) else: LOGGER.warning(excp.message) LOGGER.warning(result) LOGGER.exception("Could not parse") bot.send_message( log_chat_id, result + "\n\nFormatting has been disabled due to an unexpected error.", )
from ExusiaiBot.events import register from ExusiaiBot import LOGGER from ExusiaiBot.modules.tr_engine.strings import tld from requests import get import rapidjson as json # Greeting all bot owners that is using this module, # - RealAkito (used to be peaktogoo) [Module Maker] # have spent so much time of their life into making this module better, stable, and well more supports. # Please don't remove these comment, if you're still respecting me, the module maker. # # This module was inspired by Android Helper Bot by Vachounet. # None of the code is taken from the bot itself, to avoid confusion. LOGGER.info("android: Original Android Modules by @RealAkito on Telegram") @register(pattern=r"^/los(?: |$)(\S*)") async def los(event): if event.from_id == None: return chat_id = event.chat_id try: device_ = event.pattern_match.group(1) device = urllib.parse.quote_plus(device_) except Exception: device = "" if device == "":
def report(bot: Bot, update: Update) -> str: message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] if chat and message.reply_to_message and sql.chat_should_report(chat.id): reported_user = message.reply_to_message.from_user # type: Optional[User] chat_name = chat.title or chat.first or chat.username admin_list = chat.get_administrators() if int(reported_user.id) == int(user.id): return if chat.username and chat.type == Chat.SUPERGROUP: msg = ("<b>{}:</b>" "\n<b>Reported user:</b> {} (<code>{}</code>)" "\n<b>Reported by:</b> {} (<code>{}</code>)".format( html.escape(chat.title), mention_html(reported_user.id, reported_user.first_name), reported_user.id, mention_html(user.id, user.first_name), user.id, )) link = ("\n<b>Link:</b> " '<a href="http://telegram.me/{}/{}">click here</a>'.format( chat.username, message.message_id)) should_forward = True keyboard = [ [ InlineKeyboardButton( "➡ Message", url="https://t.me/{}/{}".format( chat.username, str(message.reply_to_message.message_id)), ) ], [ InlineKeyboardButton( "⚠ Kick", callback_data="report_{}=kick={}={}".format( chat.id, reported_user.id, reported_user.first_name), ), InlineKeyboardButton( "⛔️ Ban", callback_data="report_{}=banned={}={}".format( chat.id, reported_user.id, reported_user.first_name), ), ], [ InlineKeyboardButton( "❎ Delete Message", callback_data="report_{}=delete={}={}".format( chat.id, reported_user.id, message.reply_to_message.message_id, ), ) ], ] reply_markup = InlineKeyboardMarkup(keyboard) else: msg = '{} is calling for admins in "{}"!'.format( mention_html(user.id, user.first_name), html.escape(chat_name)) link = "" should_forward = True for admin in admin_list: if admin.user.is_bot: # can't message bots continue if sql.user_should_report(admin.user.id): try: if not chat.type == Chat.SUPERGROUP: bot.send_message( admin.user.id, msg + link, parse_mode=ParseMode.HTML, disable_web_page_preview=True, ) if should_forward: message.reply_to_message.forward(admin.user.id) if ( len(message.text.split()) > 1 ): # If user is giving a reason, send his message too message.forward(admin.user.id) if not chat.username: bot.send_message( admin.user.id, msg + link, parse_mode=ParseMode.HTML, disable_web_page_preview=True, ) if should_forward: message.reply_to_message.forward(admin.user.id) if ( len(message.text.split()) > 1 ): # If user is giving a reason, send his message too message.forward(admin.user.id) if chat.username and chat.type == Chat.SUPERGROUP: bot.send_message( admin.user.id, msg + link, parse_mode=ParseMode.HTML, reply_markup=reply_markup, disable_web_page_preview=True, ) if should_forward: message.reply_to_message.forward(admin.user.id) if ( len(message.text.split()) > 1 ): # If user is giving a reason, send his message too message.forward(admin.user.id) except Unauthorized: pass except BadRequest as excp: # TODO: cleanup exceptions LOGGER.exception( f"Exception while reporting user : {excp}") message.reply_to_message.reply_text( tld(chat.id, "reports_success").format( mention_html(user.id, user.first_name)), parse_mode=ParseMode.HTML, disable_web_page_preview=True, ) return msg return ""
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 load order names. Quitting.") quit(1) 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 ALL_MODULES = sorted(__list_all_modules()) LOGGER.info("Modules to load: %s", str(ALL_MODULES)) __all__ = ALL_MODULES + ["ALL_MODULES"]
def ban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text(tld(chat.id, "common_err_no_user")) return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found.": message.reply_text(tld(chat.id, "bans_err_usr_not_found")) return "" else: raise if user_id == bot.id: message.reply_text(tld(chat.id, "bans_err_usr_is_bot")) return "" if is_user_ban_protected(chat, user_id, member): message.reply_text(tld(chat.id, "bans_err_usr_is_admin")) return "" log = tld(chat.id, "bans_logger").format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id, ) reply = tld(chat.id, "bans_banned_success").format( mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), html.escape(chat.title), ) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) reply += tld(chat.id, "bans_logger_reason").format(reason) try: chat.kick_member(user_id) message.reply_text(reply, parse_mode=ParseMode.HTML) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, quote=False, parse_mode=ParseMode.HTML) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text( tld(chat.id, "bans_err_unknown").format("banning")) return ""
# Stop processing with any other handler. except DispatcherHandlerStop: self.logger.debug( "Stopping further handlers due to DispatcherHandlerStop") break # Dispatch any error. except TelegramError as te: self.logger.warning( "A TelegramError was raised while processing the Update") try: self.dispatch_error(update, te) except DispatcherHandlerStop: self.logger.debug("Error handler stopped further handlers") break except Exception: self.logger.exception( "An uncaught error was raised while handling the error") # Errors should not stop the thread. except Exception: self.logger.exception( "An uncaught error was raised while processing the update") if __name__ == "__main__": LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES)) tbot.start(bot_token=TOKEN) main()
def error_callback(bot, update, error): try: raise error except Unauthorized: LOGGER.warning(error) # remove update.message.chat_id from conversation list except BadRequest: LOGGER.warning(error) # handle malformed requests - read more below! except TimedOut: LOGGER.warning("NO NONO3") # handle slow connection problems except NetworkError: LOGGER.warning("NO NONO4") # handle other connection problems except ChatMigrated as err: LOGGER.warning(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: LOGGER.warning(error)
def extract_user_and_text(message: Message, args: List[str]) -> (Optional[int], Optional[str]): chat = message.chat prev_message = message.reply_to_message split_text = message.text.split(None, 1) if len(split_text) < 2: return id_from_reply(message) # only option possible text_to_parse = split_text[1] text = "" entities = list(message.parse_entities([MessageEntity.TEXT_MENTION])) if len(entities) > 0: ent = entities[0] else: ent = None # if entity offset matches (command end/text start) then all good if entities and ent and ent.offset == len( message.text) - len(text_to_parse): ent = entities[0] user_id = ent.user.id text = message.text[ent.offset + ent.length:] elif len(args) >= 1 and args[0][0] == "@": user = args[0] user_id = get_user_id(user) if not user_id: message.reply_text(tld(chat.id, "helpers_user_not_in_db")) return None, None else: user_id = user_id res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif len(args) >= 1 and args[0].isdigit(): user_id = int(args[0]) res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif prev_message: user_id, text = id_from_reply(message) else: return None, None try: message.bot.get_chat(user_id) except BadRequest as excp: if excp.message in ("User_id_invalid", "Chat not found"): message.reply_text(tld(chat.id, "helpers_user_not_in_db")) else: LOGGER.exception("Exception %s on user %s", excp.message, user_id) return None, None return user_id, text
def send(update, message, keyboard, backup_message): chat = update.effective_chat cleanserv = sql.clean_service(chat.id) reply = update.message.message_id # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False try: msg = update.effective_message.reply_text( message, parse_mode=ParseMode.HTML, reply_markup=keyboard, reply_to_message_id=reply, disable_web_page_preview=True, ) except IndexError: msg = update.effective_message.reply_text( markdown_parser(backup_message + "\nNote: the current message was " "invalid due to markdown issues. Could be " "due to the user's name."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) except KeyError: msg = update.effective_message.reply_text( markdown_parser(backup_message + "\nNote: the current message is " "invalid due to an issue with some misplaced " "curly brackets. Please update"), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) except BadRequest as excp: if excp.message == "Button_url_invalid": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has an invalid url " "in one of its buttons. Please update."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) elif excp.message == "Unsupported url protocol": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has buttons which " "use url protocols that are unsupported by " "telegram. Please update."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) elif excp.message == "Wrong url host": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has some bad urls. " "Please update."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) LOGGER.warning(message) LOGGER.warning(keyboard) LOGGER.exception("Could not parse! got invalid url host errors") else: try: msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: An error occured when sending the " "custom message. Please update."), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN, ) except BadRequest: return "" return msg
def temp_nomedia(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message conn = connected(bot, update, chat, user.id) if conn: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": return else: chatD = chat user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text(tld(chat.id, "mute_not_refer")) return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text(tld(chat.id, "mute_not_existed")) return "" else: raise if is_user_admin(chat, user_id, member): message.reply_text(tld(chat.id, "restrict_is_admin")) return "" if user_id == bot.id: message.reply_text(tld(chat.id, "restrict_is_bot")) return "" if not reason: message.reply_text(tld(chat.id, "nomedia_need_time")) return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = ("<b>{}:</b>" "\n#TEMP RESTRICTED" "\n<b>• Admin:</b> {}" "\n<b>• User:</b> {}" "\n<b>• ID:</b> <code>{}</code>" "\n<b>• Time:</b> {}".format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id, time_val, )) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) try: if member.can_send_messages is None or member.can_send_messages: bot.restrict_chat_member( chat.id, user_id, until_date=mutetime, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, ) message.reply_text( tld(chat.id, "nomedia_success").format(time_val, chatD.title)) return log else: message.reply_text( tld(chat.id, "restrict_already_restricted").format(chatD.title)) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( tld(chat.id, "nomedia_success").format(time_val, chatD.title), quote=False, ) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text(tld(chat.id, "restrict_cant_restricted")) return ""