def send_log( context: CallbackContext, log_chat_id: str, orig_chat_id: str, result: str, ): bot = context.bot try: bot.send_message( log_chat_id, result, parse_mode=ParseMode.HTML, disable_web_page_preview=True, ) 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.", )
def main(): if SUPPORT_CHAT is not None and isinstance(SUPPORT_CHAT, str): try: dispatcher.bot.sendMessage(f"@{SUPPORT_CHAT}", "Cutie Is Now Available in Bedroom") except Unauthorized: LOGGER.warning( "Bot isnt able to send message to support_chat, go and check!") except BadRequest as e: LOGGER.warning(e.message) test_handler = CommandHandler("test", test) start_handler = CommandHandler("start", start) help_handler = CommandHandler("help", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_.*") settings_handler = CommandHandler("settings", get_settings) settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_") donate_handler = CommandHandler("donate", donate) migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats) # dispatcher.add_handler(test_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(settings_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(settings_callback_handler) dispatcher.add_handler(migrate_handler) dispatcher.add_handler(donate_handler) dispatcher.add_error_handler(error_callback) if WEBHOOK: LOGGER.info("Using webhooks.") updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) if CERT_PATH: updater.bot.set_webhook(url=URL + TOKEN, certificate=open(CERT_PATH, 'rb')) else: updater.bot.set_webhook(url=URL + TOKEN) else: LOGGER.info("Ahh Baby. I am Feeling So Good.") updater.start_polling(timeout=15, read_latency=4, clean=True) if len(argv) not in (1, 3, 4): telethn.disconnect() else: telethn.run_until_disconnected() updater.idle()
def get_exception(excp, filt, chat): if excp.message == "Unsupported url protocol": return "You seem to be trying to use the URL protocol which is not supported. Telegram does not support key for multiple protocols, such as tg: //. Please try again!" if excp.message == "Reply message not found": return "noreply" LOGGER.warning("Message %s could not be parsed", str(filt.reply)) LOGGER.exception("Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id)) return "This data could not be sent because it is incorrectly formatted."
def snipe(update: Update, context: CallbackContext): args = context.args bot = context.bot try: chat_id = str(args[0]) del args[0] except TypeError: 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 temp_ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user.") return log_message else: raise if user_id == bot.id: message.reply_text("I'm not gonna BAN myself, are you crazy?") return log_message if is_user_ban_protected(chat, user_id, member): message.reply_text("I don't feel like it.") return log_message if not reason: message.reply_text( "You haven't specified a time to ban this user for!") return log_message split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" bantime = extract_time(message, time_val) if not bantime: return log_message log = ( f"<b>{html.escape(chat.title)}:</b>\n" "#TEMP BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}\n" f"<b>Time:</b> {time_val}") if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id, until_date=bantime) # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker bot.sendMessage( chat.id, f"Banned! User {mention_html(member.user.id, html.escape(member.user.first_name))} " f"will be banned for {time_val}.", parse_mode=ParseMode.HTML) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(f"Banned! User will be banned for {time_val}.", quote=False) 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("Well damn, I can't ban that user.") return log_message
def ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot = context.bot args = context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("Dude at least refer some user to ban!") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("Can't seem to find this person.") return log_message if user_id == bot.id: message.reply_text("Oh yeah, ban myself, noob!") return log_message if is_user_ban_protected(chat, user_id, member) and user not in DEV_USERS: if user_id == OWNER_ID: message.reply_text("Trying to put me against a Master huh?") elif user_id in DEV_USERS: message.reply_text("I can't act against our own.") elif user_id in DRAGONS: message.reply_text( "Fighting this Bersekser here will put user lives at risk." ) elif user_id in DEMONS: message.reply_text( "Bring an order from Master Servant to fight a Assasin servant." ) elif user_id in TIGERS: message.reply_text( "Bring an order from Master Servant to fight a Lancer servant." ) elif user_id in WOLVES: message.reply_text("Rider abilities make them ban immune!") else: message.reply_text("This user has immunity and cannot be banned.") return log_message if message.text.startswith("/s"): silent = True if not can_delete(chat, context.bot.id): return "" else: silent = False log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#{'S' if silent else ''}BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.ban_member(user_id) if silent: if message.reply_to_message: message.reply_to_message.delete() message.delete() return log # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker reply = ( f"<code>❕</code><b>Ban Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: reply += f"\n<code> </code><b>• Reason:</b> \n{html.escape(reason)}" bot.sendMessage( chat.id, reply, reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton( text="Unban", callback_data=f"unbanb_unban={user_id}" ), InlineKeyboardButton(text="Delete", callback_data="unbanb_del"), ] ] ), parse_mode=ParseMode.HTML, ) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply if silent: return log message.reply_text("Banned!", quote=False) 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("Uhm...that didn't work...") return log_message
def temp_ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("Dude! at least refer some user to ban...") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("I can't seem to find this user.") return log_message if user_id == bot.id: message.reply_text("I'm not gonna BAN myself, are you crazy?") return log_message if is_user_ban_protected(chat, user_id, member): message.reply_text("I don't feel like it.") return log_message if not reason: message.reply_text("You haven't specified a time to ban this user for!") return log_message split_reason = reason.split(None, 1) time_val = split_reason[0].lower() reason = split_reason[1] if len(split_reason) > 1 else "" bantime = extract_time(message, time_val) if not bantime: return log_message log = ( f"<b>{html.escape(chat.title)}:</b>\n" "#TEMP BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}\n" f"<b>Time:</b> {time_val}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.ban_member(user_id, until_date=bantime) # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker reply_msg = ( f"<code>❕</code><b>Temp Banned</b>\n" f"<code> </code><b>• User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}\n" f"<code> </code><b>• Banned for: {time_val}</b>" ) if reason: reply_msg += f"\n<code> </code><b>• Reason:</b> {html.escape(reason)}" bot.sendMessage( chat.id, reply_msg, reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton( text="Unban", callback_data=f"unbanb_unban={user_id}" ), InlineKeyboardButton(text="Delete", callback_data="unbanb_del"), ] ] ), parse_mode=ParseMode.HTML, ) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( f"Banned! User will be banned for {time_val}.", quote=False ) 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("Well damn, I can't ban that user.") return log_message
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.MARKDOWN, reply_markup=keyboard, 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") elif excp.message == "Have no rights to send a message": return else: msg = update.effective_message.reply_text( markdown_parser(backup_message + "\nNote: An error occured when sending the " "custom message. Please update."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) LOGGER.exception() return msg
def send(update, message, keyboard, backup_message): chat = update.effective_chat reply = None try: msg = update.effective_chat.send_message( message, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard, reply_to_message_id=reply, ) except BadRequest as excp: if excp.message == "Button_url_invalid": msg = update.effective_chat.send_message( 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 == "Have no rights to send a message": return elif excp.message == "Replied message not found": msg = update.effective_chat.send_message( message, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard, quote=False, ) elif excp.message == "Unsupported url protocol": msg = update.effective_chat.send_message( 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_chat.send_message( 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: msg = update.effective_chat.send_message( markdown_parser( backup_message + "\nNote: An error occured when sending the " "custom message. Please update.", ), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) LOGGER.exception() return msg
def temp_mute(update: Update, context: CallbackContext) -> str: bot, args = context.bot, context.args chat = update.effective_chat user = update.effective_user message = update.effective_message user_id, reason = extract_user_and_text(message, args) reply = check_user(user_id, bot, chat) if reply: message.reply_text(reply) return "" member = chat.get_member(user_id) if not reason: message.reply_text( "You haven't specified a time to mute this user for!") return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() reason = split_reason[1] if len(split_reason) > 1 else "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#TEMP MUTED\n" f"<b>Admin:</b> {mention_html(user.id, user.first_name)}\n" f"<b>User:</b> {mention_html(member.user.id, member.user.first_name)}\n" f"<b>Time:</b> {time_val}") if reason: log += f"\n<b>Reason:</b> {reason}" try: if member.can_send_messages is None or member.can_send_messages: chat_permissions = ChatPermissions(can_send_messages=False) bot.restrict_chat_member( chat.id, user_id, chat_permissions, until_date=mutetime, ) bot.sendMessage( chat.id, f"Muted <b>{html.escape(member.user.first_name)}</b> for {time_val}!", parse_mode=ParseMode.HTML, ) return log message.reply_text("This user is already muted.") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(f"Muted for {time_val}!", quote=False) return log 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("Well damn, I can't mute that user.") return ""
def rban(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message if not args: message.reply_text("You don't seem to be referring to a chat/user.") return user_id, chat_id = extract_user_and_text(message, args) if not user_id: message.reply_text( "You don't seem to be referring to a user or the ID specified is incorrect..", ) return if not chat_id: message.reply_text("You don't seem to be referring to a chat.") return try: chat = bot.get_chat(chat_id.split()[0]) except BadRequest as excp: if excp.message == "Chat not found": message.reply_text( "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat.", ) return raise if chat.type == "private": message.reply_text("I'm sorry, but that's a private chat!") return if (not is_bot_admin(chat, bot.id) or not chat.get_member(bot.id).can_restrict_members): message.reply_text( "I can't restrict people there! Make sure I'm admin and can ban users.", ) return try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user") return raise if is_user_ban_protected(chat, user_id, member): message.reply_text("I really wish I could ban admins...") return if user_id == bot.id: message.reply_text("I'm not gonna BAN myself, are you crazy?") return try: chat.ban_member(user_id) message.reply_text("Banned from chat!") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text("Banned!", quote=False) elif excp.message in RBAN_ERRORS: message.reply_text(excp.message) 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("Well damn, I can't ban that user.")
def runmute(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message if not args: message.reply_text("You don't seem to be referring to a chat/user.") return user_id, chat_id = extract_user_and_text(message, args) if not user_id: message.reply_text( "You don't seem to be referring to a user or the ID specified is incorrect..", ) return if not chat_id: message.reply_text("You don't seem to be referring to a chat.") return try: chat = bot.get_chat(chat_id.split()[0]) except BadRequest as excp: if excp.message == "Chat not found": message.reply_text( "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat.", ) return raise if chat.type == "private": message.reply_text("I'm sorry, but that's a private chat!") return if (not is_bot_admin(chat, bot.id) or not chat.get_member(bot.id).can_restrict_members): message.reply_text( "I can't unrestrict people there! Make sure I'm admin and can unban users.", ) return try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user there") return raise if (is_user_in_chat(chat, user_id) and (member.can_send_messages and member.can_send_media_messages and member.can_send_other_messages and member.can_add_web_page_previews)): message.reply_text( "This user already has the right to speak in that chat.") return if user_id == bot.id: message.reply_text("I'm not gonna UNMUTE myself, I'm an admin there!") return try: bot.restrict_chat_member( chat.id, int(user_id), permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True, ), ) message.reply_text("Yep, this user can talk in that chat!") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text("Unmuted!", quote=False) elif excp.message in RUNMUTE_ERRORS: message.reply_text(excp.message) else: LOGGER.warning(update) LOGGER.exception( "ERROR unmnuting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Well damn, I can't unmute that user.")
def sed(update: Update, context: CallbackContext): sed_result = separate_sed(update.effective_message.text) if sed_result and update.effective_message.reply_to_message: if update.effective_message.reply_to_message.text: to_fix = update.effective_message.reply_to_message.text elif update.effective_message.reply_to_message.caption: to_fix = update.effective_message.reply_to_message.caption else: return repl, repl_with, flags = sed_result if not repl: update.effective_message.reply_to_message.reply_text( "You're trying to replace... " "nothing with something?") return try: try: check = regex.match(repl, to_fix, flags=regex.IGNORECASE, timeout=5) except TimeoutError: return if check and check.group(0).lower() == to_fix.lower(): update.effective_message.reply_to_message.reply_text( "Hey everyone, {} is trying to make " "me say stuff I don't wanna " "say!".format(update.effective_user.first_name)) return if infinite_loop_check(repl): update.effective_message.reply_text( "I'm afraid I can't run that regex.") return if 'i' in flags and 'g' in flags: text = regex.sub(repl, repl_with, to_fix, flags=regex.I, timeout=3).strip() elif 'i' in flags: text = regex.sub(repl, repl_with, to_fix, count=1, flags=regex.I, timeout=3).strip() elif 'g' in flags: text = regex.sub(repl, repl_with, to_fix, timeout=3).strip() else: text = regex.sub(repl, repl_with, to_fix, count=1, timeout=3).strip() except TimeoutError: update.effective_message.reply_text('Timeout') return except sre_constants.error: LOGGER.warning(update.effective_message.text) LOGGER.exception("SRE constant error") update.effective_message.reply_text( "Do you even sed? Apparently not.") return # empty string errors -_- if len(text) >= telegram.MAX_MESSAGE_LENGTH: update.effective_message.reply_text( "The result of the sed command was too long for \ telegram!") elif text: update.effective_message.reply_to_message.reply_text(text)
def ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot = context.bot args = context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("Can't seem to find this person.") return log_message else: raise if user_id == bot.id: message.reply_text("Oh yeah, ban myself, noob!") return log_message if is_user_ban_protected(chat, user_id, member) and user not in DEV_USERS: if user_id == OWNER_ID: message.reply_text( "Trying to put me against a God level disaster huh?") return log_message elif user_id in DEV_USERS: message.reply_text("I can't act against our own.") return log_message elif user_id in DRAGONS: message.reply_text( "Fighting this Dragon here will put civilian lives at risk.") return log_message elif user_id in DEMONS: message.reply_text( "Bring an order from Heroes association to fight a Demon disaster." ) return log_message elif user_id in TIGERS: message.reply_text( "Bring an order from Heroes association to fight a Tiger disaster." ) return log_message elif user_id in WOLVES: message.reply_text("Wolf abilities make them ban immune!") return log_message else: message.reply_text("This user has immunity and cannot be banned.") return log_message log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id) # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker reply = ( f"<code>❕</code><b>Ban Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: reply += f"\n<code> </code><b>• Reason:</b> \n{html.escape(reason)}" bot.sendMessage(chat.id, reply, parse_mode=ParseMode.HTML, quote=False) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text('Banned!', quote=False) 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("Uhm...that didn't work...") return log_message
def ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot = context.bot args = context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("Can't seem to find this person.") return log_message else: raise if user_id == bot.id: message.reply_text("Sumimasen...You baka?") return log_message if is_user_ban_protected(chat, user_id, member) and user not in DEV_USERS: if user_id == OWNER_ID: message.reply_text( "Rias-sama is my everything. Don't ever think about it.") return log_message elif user_id in DEV_USERS: message.reply_text("I can't act against our own.") return log_message elif user_id in DRAGONS: message.reply_text( "No!, Issei is Red dragon emperor. YOU WILL GET BANNED BY RIAS FOR YOUR BAD INTENSIONS." ) return log_message elif user_id in DEMONS: message.reply_text( "Can't go against the member of Gremory family.") return log_message elif user_id in TIGERS: message.reply_text( "Wait...President Rias is coming...She will deal with you.") return log_message elif user_id in WOLVES: message.reply_text("Cutie Cutie...Can't ban Rias's servants!") return log_message else: message.reply_text("This user has immunity and cannot be banned.") return log_message log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id) # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker reply = ( f"<code>❕</code><b>Ban Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: reply += f"\n<code> </code><b>• Reason:</b> \n{html.escape(reason)}" bot.sendMessage(chat.id, reply, parse_mode=ParseMode.HTML, quote=False) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text('Banned!', quote=False) 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("Uhm...that didn't work...") return log_message
def reply_filter(update, context): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] if not update.effective_user or update.effective_user.id == 777000: return to_match = extract_text(message) if not to_match: return chat_filters = sql.get_chat_triggers(chat.id) for keyword in chat_filters: pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])" if re.search(pattern, to_match, flags=re.IGNORECASE): if MessageHandlerChecker.check_user(update.effective_user.id): return filt = sql.get_filter(chat.id, keyword) if filt.reply == "there is should be a new reply": buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) VALID_WELCOME_FORMATTERS = [ "first", "last", "fullname", "username", "id", "chatname", "mention", ] if filt.reply_text: if '%%%' in filt.reply_text: split = filt.reply_text.split('%%%') if all(split): text = random.choice(split) else: text = filt.reply_text else: text = filt.reply_text if text.startswith('~!') and text.endswith('!~'): sticker_id = text.replace('~!', '').replace('!~', '') try: context.bot.send_sticker( chat.id, sticker_id, reply_to_message_id=message.message_id) return except BadRequest as excp: if excp.message == 'Wrong remote file identifier specified: wrong padding in the string': context.bot.send_message( chat.id, "Message couldn't be sent, Is the sticker id valid?" ) return else: LOGGER.exception("Error in filters: " + excp.message) return valid_format = escape_invalid_curly_brackets( text, VALID_WELCOME_FORMATTERS) if valid_format: filtext = valid_format.format( first=escape(message.from_user.first_name), last=escape(message.from_user.last_name or message.from_user.first_name), fullname=" ".join( [ escape(message.from_user.first_name), escape(message.from_user.last_name), ] if message.from_user.last_name else [escape(message.from_user.first_name)]), username="******" + escape(message.from_user.username) if message.from_user.username else mention_html( message.from_user.id, message.from_user.first_name), mention=mention_html(message.from_user.id, message.from_user.first_name), chatname=escape(message.chat.title) if message.chat.type != "private" else escape( message.from_user.first_name), id=message.from_user.id, ) else: filtext = "" else: filtext = "" if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): try: context.bot.send_message( chat.id, markdown_to_html(filtext), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: error_catch = get_exception(excp, filt, chat) if error_catch == "noreply": try: context.bot.send_message( chat.id, markdown_to_html(filtext), parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) send_message( update.effective_message, get_exception(excp, filt, chat), ) else: try: send_message( update.effective_message, get_exception(excp, filt, chat), ) except BadRequest as excp: LOGGER.exception("Failed to send message: " + excp.message) pass else: if ENUM_FUNC_MAP[ filt.file_type] == dispatcher.bot.send_sticker: ENUM_FUNC_MAP[filt.file_type]( chat.id, filt.file_id, reply_to_message_id=message.message_id, reply_markup=keyboard, ) else: ENUM_FUNC_MAP[filt.file_type]( chat.id, filt.file_id, caption=markdown_to_html(filtext), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML, reply_markup=keyboard, ) break else: if filt.is_sticker: message.reply_sticker(filt.reply) elif filt.is_document: message.reply_document(filt.reply) elif filt.is_image: message.reply_photo(filt.reply) elif filt.is_audio: message.reply_audio(filt.reply) elif filt.is_voice: message.reply_voice(filt.reply) elif filt.is_video: message.reply_video(filt.reply) elif filt.has_markdown: buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) try: send_message( update.effective_message, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: if excp.message == "Unsupported url protocol": try: send_message( update.effective_message, "You seem to be trying to use an unsupported url protocol. " "Telegram doesn't support buttons for some protocols, such as tg://. Please try " "again...", ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass elif excp.message == "Reply message not found": try: context.bot.send_message( chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass else: try: send_message( update.effective_message, "This message couldn't be sent as it's incorrectly formatted.", ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass LOGGER.warning("Message %s could not be parsed", str(filt.reply)) LOGGER.exception( "Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id), ) else: # LEGACY - all new filters will have has_markdown set to True. try: send_message(update.effective_message, filt.reply) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass break
def get(update, context, notename, show_none=True, no_format=False): bot = context.bot chat_id = update.effective_chat.id note = sql.get_note(chat_id, notename) message = update.effective_message # type: Optional[Message] if note: # If we're replying to a message, reply to that message (unless it's an error) if message.reply_to_message: reply_id = message.reply_to_message.message_id else: reply_id = message.message_id if note.is_reply: if JOIN_LOGGER: try: bot.forward_message(chat_id=chat_id, from_chat_id=JOIN_LOGGER, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "This message seems to have been lost - I'll remove it " "from your notes list.") sql.rm_note(chat_id, notename) else: raise else: try: bot.forward_message(chat_id=chat_id, from_chat_id=chat_id, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "Looks like the original sender of this note has deleted " "their message - sorry! Get your bot admin to start using a " "message dump to avoid this. I'll remove this note from " "your saved notes.") sql.rm_note(chat_id, notename) else: raise else: VALID_NOTE_FORMATTERS = [ 'first', 'last', 'fullname', 'username', 'id', 'chatname', 'mention' ] valid_format = escape_invalid_curly_brackets( note.value, VALID_NOTE_FORMATTERS) if valid_format: text = valid_format.format( first=escape_markdown(message.from_user.first_name), last=escape_markdown(message.from_user.last_name or message.from_user.first_name), fullname=escape_markdown( " ".join([ message.from_user.first_name, message.from_user. last_name ] if message.from_user.last_name else [message.from_user.first_name])), username="******" + message.from_user.username if message.from_user.username else mention_markdown( message.from_user.id, message.from_user.first_name), mention=mention_markdown(message.from_user.id, message.from_user.first_name), chatname=escape_markdown( message.chat.title if message.chat.type != "private" else message.from_user.first_name), id=message.from_user.id) else: text = "" keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): bot.send_message(chat_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) else: ENUM_FUNC_MAP[note.msgtype](chat_id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Entity_mention_user_invalid": message.reply_text( "Looks like you tried to mention someone I've never seen before. If you really " "want to mention them, forward one of their messages to me, and I'll be able " "to tag them!") elif FILE_MATCHER.match(note.value): message.reply_text( "This note was an incorrectly imported file from another bot - I can't use " "it. If you really need it, you'll have to save it again. In " "the meantime, I'll remove it from your notes list.") sql.rm_note(chat_id, notename) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted. Ask in " f"@{SUPPORT_CHAT} if you can't figure out why!") LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id)) LOGGER.warning("Message was: %s", str(note.value)) return elif show_none: message.reply_text("This note doesn't exist")