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 = "*{}* memiliki pengaturan berikut untuk *{}* 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="Kembali", 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( "Hai yang disana! Ada beberapa pengaturan untuk {} - silakan dan pilih apa " "Anda tertarik.".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( "Hai yang disana! Ada beberapa pengaturan untuk {} - silakan dan pilih apa " "Anda tertarik.".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= "Hai yang disana! Ada beberapa pengaturan for {} - silakan dan pilih apa " "Anda tertarik.".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 == "Pesan tidak diubah": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Pesan tidak dapat dihapus": pass else: LOGGER.exception("Pengecualian dalam tombol pengaturan. %s", str(query.data))
def temp_mute(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("ആരെയാണ് എന്നു പറഞ്ഞില്ലല്ലോ...") 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_admin(chat, user_id, member): message.reply_text("അഡ്മിൻ ആണ്... മ്യൂട്ട് ചെയ്യാൻ പറ്റില്ല!") return "" if user_id == bot.id: message.reply_text("I'm not gonna MUTE myself, are you crazy?") return "" if not reason: message.reply_text( "ഇയാളെ എത്ര സമയം മ്യൂട്ട് ചെയ്യണം എന്നു പറഞ്ഞില്ലല്ലോ?") 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 MUTED" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\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), time_val) if reason: log += "\n<b>Reason:</b> {}".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=False) message.reply_text( "കുറച്ചുനേരം മിണ്ടാതിരിക്ക്! Muted for {}!".format(time_val)) return log else: message.reply_text("ഇയാളെ already മ്യൂട്ട് ചെയ്തിട്ടുണ്ട്!") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( "കുറച്ചുനേരം മിണ്ടാതിരിക്ക്! Muted for {}!".format(time_val), 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("Well damn, I can't mute that user.") return ""
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 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." ) 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 temp_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("Bir istifadəçini seçməmisiniz.") return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("Bu istifadəçini tapa bilmirəm") return "" else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text( "Kaş adminləri ban edə biləcək super güclərim olsa...") return "" if user_id == bot.id: message.reply_text("Ha ha ha çox gülməlidi. Mən özümü ban etməyəcəm!") return "" if not reason: message.reply_text( "Bu istifadəçini qadağan edəcək bir vaxt təyin etməmisiniz!") 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> {}" \ "\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), 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("Ban olundu! Səbəb {}.".format(time_val)) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text("Ban olundu! Səbəb {}.".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 runban(bot: Bot, update: Update, args: List[str]): message = update.effective_message if not args: message.reply_text( "Görünür söhbət və ya istifadəçi haqqında danışmırsız.") return user_id, chat_id = extract_user_and_text(message, args) if not user_id: message.reply_text("Bir istifadəçini seçməmisiniz.") return elif not chat_id: message.reply_text( "Görünür söhbət və ya istifadəçi haqqında danışmırsız..") return try: chat = bot.get_chat(chat_id.split()[0]) except BadRequest as excp: if excp.message == "Chat not found": message.reply_text("Qeyd qrup tapılmadı") return else: raise if chat.type == 'private': message.reply_text("Qrup gizli olduğu üçün heçnə edə bilmərəm") return if not is_bot_admin(chat, bot.id) or not chat.get_member( bot.id).can_restrict_members: message.reply_text( "İstifadəçiləri bloklaya bilmirəm. Admin olduğumdan və istifadəçiləri qadağa etmə özəlliyimin açıq olduğuna fikir ver)" ) return try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("Bu istifadəçini tapa bilmirəm there") return else: raise if is_user_in_chat(chat, user_id): message.reply_text( "Bu istifadəçinin onsuzda banı yoxdu. Banı olmayan istifadəçini necə unban edim? )" ) return if user_id == bot.id: message.reply_text( "Bir bunu etmədiyin qalmışd)) Bunu etmiyəcəm çünki ADMİNƏM!") return try: chat.unban_member(user_id) message.reply_text("Uraa! Artıq istifadəçi qrupa qatıla bilər") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text('Unban olundu!', quote=False) elif excp.message in RUNBAN_ERRORS: message.reply_text(excp.message) else: LOGGER.warning(update) LOGGER.exception( "ERROR unbanning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text( "Lənət olsun bu istifadəçinin qadağasın qaldıra bilmərəm.")
def temp_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] if user.id not in _TELE_GRAM_ID_S: admin_user = chat.get_member(user.id) if not (admin_user.can_restrict_members or admin_user.status == "creator"): return user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text( "നിങ്ങൾ ഒരു ഉപയോക്താവിനെ സൂചിപ്പിക്കുന്നതായി തോന്നുന്നില്ല.") return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("എനിക്ക് ഈ ഉപയോക്താവിനെ കണ്ടെത്താനാകുന്നില്ല") return "" else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text("അഡ്മിൻ ആണ്... ബാൻ ചെയ്യാൻ പറ്റില്ല!") return "" if user_id == bot.id: message.reply_text("ഞാൻ എന്നെത്തന്നെ ബാൻ ചെയ്യണം എന്നാണോ പറയുന്നത്?") return "" if not reason: message.reply_text("ഇയാളെ എത്ര സമയം ബാൻ ചെയ്യണം എന്നു പറഞ്ഞില്ലല്ലോ?") 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( "ബണ്ണ് കൊടുത്തുവിട്ടു! User will be BANNED for {}.".format( time_val)) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( "ബണ്ണ് കൊടുത്തുവിട്ടു! 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( "കൊള്ളാം, എനിക്ക് ആ ഉപയോക്താവിനെ നിരോധിക്കാൻ കഴിയില്ല.") return ""
def temp_ban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" 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, 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 += "\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, 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 settings_button(update: Update, context: CallbackContext): bot = context.bot 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 = get_string("main", "MODULE_SETTINGS", lang.get_lang(chat_id)).format(escape_markdown(chat.title), CHAT_SETTINGS[ module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) # MODULE_SETTINGS 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(get_string("main", "LOT_OF_SETTINGS", lang.get_lang(chat_id)).format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id))) # LOT_OF_SETTINGS 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(get_string("main", "LOT_OF_SETTINGS", lang.get_lang(chat_id)).format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id))) # LOT_OF_SETTINGS elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.reply_text(text=get_string("main", "LOT_OF_SETTINGS", lang.get_lang(chat_id)).format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id))) # LOT_OF_SETTINGS # 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": # ERR_MSG_NOT_MODIFIED pass elif excp.message == "Query_id_invalid": # ERR_QUERY_ID_INVALID pass elif excp.message == "Message can't be deleted": # ERR_MSG_CANT_DELETE pass else: LOGGER.exception(get_string("main", "ERR_EXCP_SETTINGS_BUTTONS", DEFAULT_LANG), str(query.data)) # ERR_EXCP_SETTINGS_BUTTONS
def temp_nomedia(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("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_admin(chat, user_id, member): message.reply_text("I really wish I could restrict admins...") return "" if user_id == bot.id: message.reply_text("I'm not gonna RESTRICT myself, are you crazy?") return "" if not reason: message.reply_text( "You haven't specified a time to restrict 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 = "" 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 += "\n<b>• Reason:</b> {}".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( "Restricted from sending media for {}!".format(time_val)) return log else: message.reply_text("This user is already restricted.") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text("Restricted for {}!".format(time_val), 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("Well damn, I can't restrict that user.") return ""
def temp_mute(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] args = context.args if user_can_ban(chat, user, context.bot.id) == False: message.reply_text( "You don't have enough rights to restrict someone from talking!") return "" 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_admin(chat, user_id, member): message.reply_text("I really wish I could mute admins...") return "" if user_id == context.bot.id: message.reply_text("I'm not gonna MUTE myself, are you crazy?") return "" 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() 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 MUTED" "\n<b>Admin:</b> {}" "\n<b>User:</b> {}" "\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), time_val, )) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: if member.can_send_messages is None or member.can_send_messages: context.bot.restrict_chat_member( chat.id, user_id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False), ) message.reply_text("shut up! 🤐 Taped for {}!".format(time_val)) return log else: 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("shut up! 🤐 Taped for {}!".format(time_val), 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("Well damn, I can't mute that user.") return ""
def get(bot, update, notename, show_none=True, no_format=False): chat_id = update.effective_chat.id message = update.effective_message # type: Optional[Message] timer = sql.get_clearnotes(chat_id) delmsg = "" count = 0 if notename.isnumeric(): check = sql.get_note(chat_id, notename) # If check == true, it means that notename and noteid conflicts each other if check: message.reply_text(warning.format(notename=notename)) # If check == false, it means that we need to search notename for given noteid else: note_list = sql.get_all_chat_notes(chat_id) for note in note_list: count = count + 1 if str(count) == notename: notename = note.name break # As it can be overwritten later note = sql.get_note(chat_id, notename) # Removed lower() for compatibility 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 MESSAGE_DUMP: try: delmsg = bot.forward_message( chat_id=chat_id, from_chat_id=MESSAGE_DUMP, 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: delmsg = 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: text = note.value 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): delmsg = bot.send_message( chat_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard, ) else: delmsg = ENUM_FUNC_MAP[note.msgtype]( chat_id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, 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 " "@bot_workshop 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)) if timer != 0: sleep(int(timer)) try: delmsg.delete() message.delete() except: pass return if show_none: message.reply_text("This note doesn't exist")
def temp_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("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) keyboard = [] bot.send_sticker(update.effective_chat.id, BAN_STICKER) # banhammer marie sticker reply = "{} has been temporarily banned for {}!".format(mention_html(member.user.id, member.user.first_name),time_val) message.reply_text(reply, reply_markup=keyboard, 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 report(bot: Bot, update: Update) -> str: message = update.effective_message chat = update.effective_chat user = update.effective_user if chat and message.reply_to_message and sql.chat_should_report(chat.id): reported_user = message.reply_to_message.from_user chat_name = chat.title or chat.first or chat.username admin_list = chat.get_administrators() message = update.effective_message if user.id == reported_user.id: message.reply_text("Uh yeah, Sure.") return "" if user.id == bot.id: message.reply_text("Nice try.") return "" if reported_user.id in REPORT_IMMUNE_USERS: message.reply_text("Uh? You reporting whitelisted users?") return "" if chat.username and chat.type == Chat.SUPERGROUP: reported = f"{mention_html(user.id, user.first_name)} reported {mention_html(reported_user.id, reported_user.first_name)} to the admins!" msg = (f"<b>{html.escape(chat.title)}:</b>\n" f"<b>Reported user:</b> {mention_html(reported_user.id, reported_user.first_name)} (<code>{reported_user.id}</code>)\n" f"<b>Reported by:</b> {mention_html(user.id, user.first_name)} (<code>{user.id}</code>)") link = f'\n<b>Link:</b> <a href="https://t.me/{chat.username}/{message.message_id}">click here</a>' should_forward = False else: reported = f"{mention_html(user.id, user.first_name)} reported " \ f"{mention_html(reported_user.id, reported_user.first_name)} to the admins!" msg = f'{mention_html(user.id, user.first_name)} is calling for admins in "{html.escape(chat_name)}"!' link = "" should_forward = True message.reply_text(reported, parse_mode=ParseMode.HTML) for admin in admin_list: if admin.user.is_bot: # can't message bots continue if sql.user_should_report(admin.user.id): try: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML) 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: # TODO: cleanup exceptions LOGGER.exception("Exception while reporting user") return msg return ""
def temp_mute(bot: Bot, update: Update, args: List[str]) -> str: 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() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" 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: bot.restrict_chat_member(chat.id, user_id, until_date=mutetime, can_send_messages=False) bot.sendMessage( chat.id, f"Muted <b>{html.escape(member.user.first_name)}</b> for {time_val}!", parse_mode=ParseMode.HTML) return log else: 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 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("Well damn, I can't mute that user.") return ""
def help_button(update, context): 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.edit_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.edit_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.edit_text( HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, HELPABLE, "help") ), ) elif back_match: query.message.edit_text( text=HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, HELPABLE, "help") ), ) # ensure no spinny white circle context.bot.answer_callback_query(query.id) # query.message.delete() except Exception 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: query.message.edit_text(excp.message) LOGGER.exception("Exception in help buttons. %s", str(query.data))
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("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 "" elif user_id == OWNER_ID: message.reply_text( "Haha, you know what I ain't gonna do, ban my Boss?") return "" log = "<b>{}:</b>" \ "\n#BANNED" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name)) reply = "🔨 {} was banned by {}!".format( mention_html(member.user.id, member.user.first_name), mention_html(user.id, user.first_name)) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id) keyboard = [] bot.send_sticker(chat.id, BAN_STICKER) message.reply_text(reply, reply_markup=keyboard, 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("Well damn, 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] # TODO: allow uploading doc with command, not just as reply # only work with a doc 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: filetype = msg.reply_to_message.document.file_name if filetype.split('.')[-1] not in ("backup", "json", "txt"): msg.reply_text("File is not valid!") return 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) try: # If backup is from Monica if data.get('bot_base') == "Monica": imp_notes = 0 NOT_IMPORTED = "This cannot be imported because from other bot." NOT_IMPORTED_INT = 0 # If backup is from this bot, import all files if data.get('bot_id') == bot.id: is_self = True else: is_self = False # Import notes if data.get('notes'): allnotes = data['notes'] NOT_IMPORTED += "\n\nNotes:\n" for x in allnotes: # If from self, import all if is_self: note_data, buttons = button_markdown_parser(x['note_data'], entities=0) note_name = x['note_tag'] note_file = None note_type = x['note_type'] if x['note_file']: note_file = x['note_file'] if note_type == 0: note_type = Types.TEXT elif note_type == 1: note_type = Types.BUTTON_TEXT elif note_type == 2: note_type = Types.STICKER elif note_type == 3: note_type = Types.DOCUMENT elif note_type == 4: note_type = Types.PHOTO elif note_type == 5: note_type = Types.AUDIO elif note_type == 6: note_type = Types.VOICE elif note_type == 7: note_type = Types.VIDEO elif note_type == 8: note_type = Types.VIDEO_NOTE else: note_type = None if note_type <= 8: notesql.add_note_to_db(chat_id, note_name, note_data, note_type, buttons, note_file) imp_notes += 1 else: # If this text if x['note_type'] == 0: note_data, buttons = button_markdown_parser(x['text'].replace("\\", ""), entities=0) note_name = x['name'] notesql.add_note_to_db(chat_id, note_name, note_data, Types.TEXT, buttons, None) imp_notes += 1 else: NOT_IMPORTED += "- {}\n".format(x['name']) NOT_IMPORTED_INT += 1 if conn: text = (update.effective_message, "Full backup returned on *{}*. Welcome backup! ").format(chat_name) else: text = (update.effective_message, "Backup fully restored.\nDone with welcome backup! ").format(chat_name) try: msg.reply_text(text, parse_mode="markdown") except BadRequest: msg.reply_text(text, parse_mode="markdown", quote=False) if NOT_IMPORTED_INT: f = open("{}-notimported.txt".format(chat_id), "w") f.write(str(NOT_IMPORTED)) f.close() bot.sendDocument(chat_id, document=open('{}-notimported.txt'.format(chat_id), 'rb'), caption=tl(update.effective_message, "*Data that can't be imported*"), timeout=360, parse_mode=ParseMode.MARKDOWN) os.remove("{}-notimported.txt".format(chat_id)) return except Exception as err: msg.reply_text(tl(update.effective_message, "An error has occurred getting Ctrl backup!\nGo, ping [Support Chat](https://t.me/AnieSupport) and ask if any solution of it!\n\nMaybe they can resolve your issue!"), parse_mode="markdown") LOGGER.exception("An error when importing from Julie base!") return # 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! Please ask in @ctrlsupport about why this happened.") # 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.!") 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. If you experience a problem with this, please ask in @AnieSupport!\nThank you!") 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")
def get(bot, update, notename, show_none=True, no_format=False): chat_id = update.effective_chat.id chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chat_id = conn send_id = user.id else: chat_id = update.effective_chat.id send_id = chat_id note = sql.get_note(chat_id, notename) message = update.effective_message # type: Optional[Message] if note: if MessageHandlerChecker.check_user(update.effective_user.id): return # 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 MESSAGE_DUMP: try: bot.forward_message( chat_id=update.effective_chat.id, from_chat_id=MESSAGE_DUMP, 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=update.effective_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(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: text = "" keyb = [] parseMode = ParseMode.HTML buttons = sql.get_buttons(chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: text = markdown_to_html(text) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): bot.send_message( update.effective_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]( update.effective_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." ) LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id)) LOGGER.warning("Message was: %s", str(note.value)) return if show_none: message.reply_text("This note doesn't exist")
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] if user.id not in _TELE_GRAM_ID_S: admin_user = chat.get_member(user.id) if not (admin_user.can_restrict_members or admin_user.status == "creator"): return user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text( "നിങ്ങൾ ഒരു ഉപയോക്താവിനെ സൂചിപ്പിക്കുന്നതായി തോന്നുന്നില്ല.") return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("എനിക്ക് ഈ ഉപയോക്താവിനെ കണ്ടെത്താനാകുന്നില്ല") return "" else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text("അഡ്മിൻ ആണ്... ബാൻ ചെയ്യാൻ പറ്റില്ല!") return "" if user_id == bot.id: message.reply_text("ഞാൻ എന്നെത്തന്നെ ബാൻ ചെയ്യണം എന്നാണോ പറയുന്നത്?") 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) # banhammer marie sticker keyboard = [] reply = "{} ന് ബണ്ണ് കൊടുത്തു വിട്ടിട്ടുണ്ട് !".format( mention_html(member.user.id, member.user.first_name)) message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply reply = "{} ന് ബണ്ണ് കൊടുത്തു വിട്ടിട്ടുണ്ട് !".format( mention_html(member.user.id, member.user.first_name)) message.reply_text(reply, reply_markup=keyboard, 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( "കൊള്ളാം, എനിക്ക് ആ ഉപയോക്താവിനെ നിരോധിക്കാൻ കഴിയില്ല.") return ""
def extract_user_and_text(message: Message, args: List[str]) -> (Optional[int], Optional[str]): 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( "I don't have that user in my db. You'll be able to interact with them if " "you reply to that person's message instead, or forward one of that user's messages." ) 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( "I don't seem to have interacted with this user before - please forward a message from " "them to give me control!") else: LOGGER.exception("Exception %s on user %s", excp.message, user_id) return None, None return user_id, text
def get(bot, update, notename, show_none=True, no_format=False): 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 MESSAGE_DUMP: try: bot.forward_message(chat_id=chat_id, from_chat_id=MESSAGE_DUMP, 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: text = note.value 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 " "@MarieSupport 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")
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 modülü için şu ayarlara sahiptir: *{}* 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("Merhaba! {} için epeyce ayar var - devam edin ve neyi seçin " "ilgileniyorsun.".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("Merhaba! {} için epeyce ayar var - devam edin ve neyi seçin " "ilgileniyorsun.".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="Merhaba! {} için epeyce ayar var - devam edin ve neyi seçin " "ilgileniyorsun.".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 == "Mesaj değiştirilmedi": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Mesaj silinmez!": pass else: LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def rban(bot: Bot, update: Update, args: List[str]): message = update.effective_message if not args: message.reply_text( "Görünür söhbət və ya istifadəçi haqqında danışmırsız.") return user_id, chat_id = extract_user_and_text(message, args) if not user_id: message.reply_text("Bir istifadəçini seçməmisiniz.") return elif not chat_id: message.reply_text("Bir söhbəti seçməmisiniz.") 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 else: raise if chat.type == 'private': message.reply_text("Mən üzgünəm( Bu qrup gizlidi.") return if not is_bot_admin(chat, bot.id) or not chat.get_member( bot.id).can_restrict_members: message.reply_text( "İstifadəçiləri bloklaya bilmirəm. Admin olduğumdan və istifadəçiləri qadağa etmə özəlliyimin açıq olduğuna fikir ver)" ) return try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("Bu istifadəçini tapa bilmirəm") return else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text( "Kaş adminləri ban edə biləcək super güclərim olsa...") return if user_id == bot.id: message.reply_text("Ha ha ha çox gülməlidi. Mən özümü ban etməyəcəm!") return try: chat.kick_member(user_id) message.reply_text("Ban olundu!") 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( "Lənət olsun. Bu istifadəçini qadağa edə bilmirəm")
def temp_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("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("你先把他管理员撤了") return "" if user_id == bot.id: message.reply_text("这个宇宙太疯狂,大海掀翻李中毛") return "" if not reason: message.reply_text("你用的是暂时封禁指令,要加上时间m/h/d的") 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> {}" \ "\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), 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("好的,暂时封他{}".format(time_val)) 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 send(update, message, keyboard, backup_message): try: msg = update.effective_message.reply_text( message, parse_mode=ParseMode.HTML, reply_markup=keyboard ) 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.HTML, ) 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.HTML, ) 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.HTML, ) 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.HTML, ) 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.HTML, ) LOGGER.warning(message) LOGGER.warning(keyboard) LOGGER.exception("Could not parse! got invalid url host errors") 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.HTML, ) LOGGER.exception() return msg
def rban(bot: Bot, update: Update, args: List[str]): 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.") return elif 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 else: 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("常识:我是一个管理机器人,所以如果你要用我需要给我管理员权限") 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("你先把他管理员撤了") return if user_id == bot.id: message.reply_text("这个宇宙太疯狂,你压力封了李中毛") return try: chat.kick_member(user_id) message.reply_text("踢了") 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 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 = "*{}* ha le seguenti impostazioni *{}* per il modulo:\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( "Ciao! Ci sono alcune impostazioni disponibili per il modulo {} - continua pure e " "scegli cosa modificare.".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( "Ciao! Ci sono alcune impostazioni disponibili per il modulo {} - continua pure e " "scegli cosa modificare.".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( "Ciao! Ci sono alcune impostazioni disponibili per il modulo {} - continua pure e " "scegli cosa modificare.".format(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 runban(bot: Bot, update: Update, args: List[str]): 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.") return elif 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 else: 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 else: raise if is_user_in_chat(chat, user_id): message.reply_text( "Why are you trying to remotely unban someone that's already in that chat?" ) return if user_id == bot.id: message.reply_text("不要乱玩指令") return try: chat.unban_member(user_id) message.reply_text("已解封") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text('已解封', quote=False) elif excp.message in RUNBAN_ERRORS: message.reply_text(excp.message) else: LOGGER.warning(update) LOGGER.exception( "ERROR unbanning 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 unban that user.")
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] 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("Try targeting a user next time bud.") return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("This user is ded mate.") return "" else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text( "One day I'll find out how to work around the bot API. " "Today is not that day.") return "" if user_id == bot.id: message.reply_text("You can't ban the THONK!") return "" if not reason: message.reply_text( "I don't know how long I'm supposed to ban them 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("Rekt! User will be ded for {}.".format(time_val)) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( "Rekt! User will be ded 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("Heck'n heck, I can't ban that user.") return ""