def help_button(bot: Bot, update: Update): query = update.callback_query mod_match = re.match(r"help_module\((.+?)\)", query.data) prev_match = re.match(r"help_prev\((.+?)\)", query.data) next_match = re.match(r"help_next\((.+?)\)", query.data) back_match = re.match(r"help_back", query.data) try: if mod_match: module = mod_match.group(1) text = "Here is the help for the *{}* module:\n".format(HELPABLE[module].__mod_name__) \ + HELPABLE[module].__help__ query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="🚶🏻♂️Back🚶🏻♂️", callback_data="help_back") ]])) elif prev_match: curr_page = int(prev_match.group(1)) query.message.reply_text(HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( curr_page - 1, HELPABLE, "help"))) elif next_match: next_page = int(next_match.group(1)) query.message.reply_text(HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( next_page + 1, HELPABLE, "help"))) elif back_match: query.message.reply_text(text=HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, HELPABLE, "help"))) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: LOGGER.exception("Exception in help buttons. %s", str(query.data))
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 = "<b>{}:</b>" \ "\n#SILENT BAN" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".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 += "\n<b>• Reason:</b> {}".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 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 del_blackliststicker(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] user = update.effective_user to_match = message.sticker if not to_match: return getmode, value = sql.get_blacklist_setting(chat.id) chat_filters = sql.get_chat_stickers(chat.id) for trigger in chat_filters: if to_match.set_name.lower() == trigger.lower(): try: if getmode == 0: return elif getmode == 1: message.delete() elif getmode == 2: message.delete() warn(update.effective_user, chat, "Using sticker '{}' which in blacklist stickers". format(trigger), message, update.effective_user, conn=False) return elif getmode == 3: message.delete() bot.restrict_chat_member(chat.id, update.effective_user.id, can_send_messages=False) bot.sendMessage( chat.id, "{} muted because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 4: message.delete() res = chat.unban_member(update.effective_user.id) if res: bot.sendMessage( chat.id, "{} kicked because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 5: message.delete() chat.kick_member(user.id) bot.sendMessage( chat.id, "{} banned because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 6: message.delete() bantime = extract_time(message, value) chat.kick_member(user.id, until_date=bantime) bot.sendMessage( chat.id, "{} banned for {} because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return elif getmode == 7: message.delete() mutetime = extract_time(message, value) bot.restrict_chat_member(chat.id, user.id, until_date=mutetime, can_send_messages=False) bot.sendMessage( chat.id, "{} muted for {} because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def reply_filter(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] to_match = extract_text(message) if not to_match: return if message.reply_to_message: message = message.reply_to_message 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): filt = sql.get_filter(chat.id, keyword) buttons = sql.get_buttons(chat.id, filt.keyword) if len(buttons) > 0: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) 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, reply_markup=keyboard) 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: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) should_preview_disabled = True if "telegra.ph" in filt.reply or "youtu.be" in filt.reply: should_preview_disabled = False try: message.reply_text(filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=should_preview_disabled, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Unsupported url protocol": message.reply_text("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, or ask in @Sur_vivor for help.") elif excp.message == "Reply message not found": bot.send_message(chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard) else: message.reply_text("This note could not be sent, as it is incorrectly formatted. Ask in " "@Sur_vivor if you can't figure out why!") 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. message.reply_text(filt.reply) break
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data) prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data) next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data) back_match = re.match(r"stngs_back\((.+?)\)", query.data) try: if mod_match: chat_id = mod_match.group(1) module = mod_match.group(2) chat = bot.get_chat(chat_id) text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title), CHAT_SETTINGS[ module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="🏃🏻♂️Back🏃🏻♂️", callback_data="stngs_back({})".format(chat_id)) ]])) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.reply_text( text= "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id))) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def temp_ban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] chat_name = chat.title or chat.first or chat.username 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("You don't seem to be referring to a user.") 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 "" else: 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 "" if not reason: message.reply_text( "You haven't specified a time to ban this user for!") return "" 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 = "<b>{}:</b>" \ "\n#TEMP BANNED" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</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), member.user.id, 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 message.reply_text(f"<b>{html.escape(member.user.first_name)}</b>" + f" will be banned for {time_val} in " + f"{chat_name}", parse_mode=ParseMode.HTML) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( "Banned! User will be banned for {}.".format(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 ""
def ban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] chat_name = chat.title or chat.first or chat.username message = update.effective_message # type: Optional[Message] user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("You don't seem to be referring to a user.") 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 "" else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text("I really wish I could ban admins...") return "" if user_id == 1491765026: message.reply_text( "There is no way I can Ban this user.He is my Creator/Developer") return "" if user_id == bot.id: message.reply_text("I'm not gonna ban myself..f**k off!") return "" log = "<b>{}:</b>" \ "\n#BANNED" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {} (<code>{}</code>)".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), member.user.id) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id) bot.send_sticker(chat.id, BAN_STICKER) bot.sendMessage(chat.id, "🔨 {} was banned by {}!".format( mention_html(member.user.id, member.user.first_name), mention_html(user.id, user.first_name)), parse_mode=ParseMode.HTML) 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("I can't ban that user.") return ""
def import_data(bot: Bot, update): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": update.effective_message.reply_text( "This command can only be runned on group, not PM.") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if msg.reply_to_message and msg.reply_to_message.document: try: file_info = bot.get_file(msg.reply_to_message.document.file_id) except BadRequest: msg.reply_text( "Try downloading and uploading the file yourself again, This one seem broken!" ) return with BytesIO() as file: file_info.download(out=file) file.seek(0) data = json.load(file) # only import one group if len(data) > 1 and str(chat.id) not in data: msg.reply_text( "There are more than one group in this file and the chat.id is not same! How am i supposed to import it?" ) return # Check if backup is this chat try: if data.get(str(chat.id)) == None: if conn: text = "Backup comes from another chat, I can't return another chat to chat *{}*".format( chat_name) else: text = "Backup comes from another chat, I can't return another chat to this chat" return msg.reply_text(text, parse_mode="markdown") except: return msg.reply_text( "There is problem while importing the data! try again") # Check if backup is from self try: if str(bot.id) != str(data[str(chat.id)]['bot']): return msg.reply_text( "Backup from another bot that is not suggested might cause the problem, documents, photos, videos, audios, records might not work as it should be. However, You can still request a feature regarding this in @Telegram 😂 !" ) except: pass # Select data source if str(chat.id) in data: data = data[str(chat.id)]['hashes'] else: data = data[list(data.keys())[0]]['hashes'] try: for mod in DATA_IMPORT: mod.__import_data__(str(chat.id), data) except Exception: msg.reply_text( "An error occurred while recovering your data. The process failed.Try Again!" ) LOGGER.exception("Imprt for the chat %s with the name %s failed.", str(chat.id), str(chat.title)) return # TODO: some of that link logic # NOTE: consider default permissions stuff? if conn: text = "Backup fully restored on *{}*.".format(chat_name) else: text = "Backup fully restored" msg.reply_text(text, parse_mode="markdown")