def get_user_id(username): # ensure valid userid if len(username) <= 5: return None if username.startswith('@'): username = username[1:] users = sql.get_userid_by_name(username) if not users: return None elif len(users) == 1: return users[0].user_id else: for user_obj in users: try: userdat = dispatcher.bot.get_chat(user_obj.user_id) if userdat.username == username: return userdat.id except BadRequest as excp: if excp.message == 'Chat not found': pass else: LOGGER.exception("Error extracting user ID") return None
def del_lockables(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message for lockable, filter in LOCK_TYPES.items(): if filter(message) and sql.is_locked(chat.id, lockable) and can_delete( chat, bot.id): if lockable == "bots": new_members = update.effective_message.new_chat_members for new_mem in new_members: if new_mem.is_bot: if not is_bot_admin(chat, bot.id): message.reply_text( tld(chat.id, "locks_lock_bots_no_admin")) return chat.kick_member(new_mem.id) message.reply_text(tld(chat.id, "locks_lock_bots_kick")) else: try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in lockables") break
def ban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text(tld(chat.id, "common_err_no_user")) return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found.": message.reply_text(tld(chat.id, "bans_err_usr_not_found")) return "" else: raise if user_id == bot.id: message.reply_text(tld(chat.id, "bans_err_usr_is_bot")) return "" if is_user_ban_protected(chat, user_id, member): message.reply_text(tld(chat.id, "bans_err_usr_is_admin")) return "" log = tld(chat.id, "bans_logger").format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) reply = tld(chat.id, "bans_banned_success").format( mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), html.escape(chat.title)) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) reply += tld(chat.id, "bans_logger_reason").format(reason) try: chat.kick_member(user_id) message.reply_text(reply, parse_mode=ParseMode.HTML) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, quote=False, parse_mode=ParseMode.HTML) return log else: LOGGER.warning(update) LOGGER.exception("ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text( tld(chat.id, "bans_err_unknown").format("banning")) return ""
def rest_handler(bot: Bot, update: Update): msg = update.effective_message chat = update.effective_chat for restriction, filter in RESTRICTION_TYPES.items(): if filter(msg) and sql.is_restr_locked( chat.id, restriction) and can_delete(chat, bot.id): try: msg.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in restrictions") break
def get_help(bot: Bot, update: Update): chat = update.effective_chat args = update.effective_message.text.split(None, 1) # ONLY send help in PM if chat.type != chat.PRIVATE: update.effective_message.reply_text( tld(chat.id, 'help_pm_only'), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text=tld(chat.id, 'btn_help'), url="t.me/{}?start=help".format( bot.username)) ]])) return if len(args) >= 2: mod_name = None for x in HELPABLE: if args[1].lower() == HELPABLE[x].lower(): mod_name = tld(chat.id, "modname_" + x).strip() module = x break if mod_name: help_txt = tld(chat.id, module + "_help") if not help_txt: LOGGER.exception(f"Help string for {module} not found!") text = tld(chat.id, "here_is_help").format(mod_name, help_txt) send_help( chat.id, text, InlineKeyboardMarkup([[ InlineKeyboardButton(text=tld(chat.id, "btn_go_back"), callback_data="help_back") ]])) return update.effective_message.reply_text(tld( chat.id, "help_not_found").format(args[1]), parse_mode=ParseMode.HTML) return send_help( chat.id, tld(chat.id, "send-help").format(dispatcher.bot.first_name, tld(chat.id, "cmd_multitrigger")))
def send_log(bot: Bot, log_chat_id: str, orig_chat_id: str, result: str): try: bot.send_message(log_chat_id, result, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Chat not found": bot.send_message(orig_chat_id, "This log channel has been deleted - unsetting.") sql.stop_chat_logging(orig_chat_id) else: LOGGER.warning(excp.message) LOGGER.warning(result) LOGGER.exception("Could not parse") bot.send_message( log_chat_id, result + "\n\nFormatting has been disabled due to an unexpected error.")
def help_button(bot: Bot, update: Update): query = update.callback_query chat = update.effective_chat back_match = re.match(r"help_back", query.data) mod_match = re.match(r"help_module\((.+?)\)", query.data) try: if mod_match: module = mod_match.group(1) mod_name = tld(chat.id, "modname_" + module).strip() help_txt = tld( chat.id, module + "_help") # tld_help(chat.id, HELPABLE[module].__mod_name__) if not help_txt: LOGGER.exception(f"Help string for {module} not found!") text = tld(chat.id, "here_is_help").format(mod_name, help_txt) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text=tld(chat.id, "btn_go_back"), callback_data="help_back") ]]), disable_web_page_preview=True) elif back_match: bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=tld(chat.id, "send-help").format( dispatcher.bot.first_name, tld(chat.id, "cmd_multitrigger")), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(chat.id, 0, HELPABLE, "help")), disable_web_page_preview=True) # ensure no spinny white circle bot.answer_callback_query(query.id) # query.message.delete() except BadRequest: pass
def del_blacklist_url(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message parsed_entities = message.parse_entities(types=["url"]) extracted_domains = [] for obj, url in parsed_entities.items(): extract_url = tldextract.extract(url) extracted_domains.append(extract_url.domain + "." + extract_url.suffix) for url in sql.get_blacklisted_urls(chat.id): if url in extracted_domains: try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def sban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] update.effective_message.delete() user_id, reason = extract_user_and_text(message, args) if not user_id: return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": return "" else: raise if is_user_ban_protected(chat, user_id, member): return "" if user_id == bot.id: return "" log = tld(chat.id, "bans_sban_logger").format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) try: chat.kick_member(user_id) return log except BadRequest as excp: if excp.message == "Reply message not found": return log else: LOGGER.warning(update) LOGGER.exception("ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) return ""
def 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 setlog(bot: Bot, update: Update): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: message.reply_text(tld(chat.id, "log_channel_fwd_cmd")) elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception( "Error deleting message in log channel. Should work anyway though." ) try: bot.send_message( message.forward_from_chat.id, tld(chat.id, "log_channel_chn_curr_conf").format(chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message(chat.id, tld(chat.id, "log_channel_link_success")) else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, tld(chat.id, "log_channel_link_success")) else: message.reply_text(tld(chat.id, "log_channel_invalid_message"), ParseMode.MARKDOWN)
def extract_user_and_text(message: Message, args: List[str]) -> (Optional[int], Optional[str]): chat = message.chat prev_message = message.reply_to_message split_text = message.text.split(None, 1) if len(split_text) < 2: return id_from_reply(message) # only option possible text_to_parse = split_text[1] text = "" entities = list(message.parse_entities([MessageEntity.TEXT_MENTION])) if len(entities) > 0: ent = entities[0] else: ent = None # if entity offset matches (command end/text start) then all good if entities and ent and ent.offset == len( message.text) - len(text_to_parse): ent = entities[0] user_id = ent.user.id text = message.text[ent.offset + ent.length:] elif len(args) >= 1 and args[0][0] == '@': user = args[0] user_id = get_user_id(user) if not user_id: message.reply_text(tld(chat.id, 'helpers_user_not_in_db')) return None, None else: user_id = user_id res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif len(args) >= 1 and args[0].isdigit(): user_id = int(args[0]) res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif prev_message: user_id, text = id_from_reply(message) else: return None, None try: message.bot.get_chat(user_id) except BadRequest as excp: if excp.message in ("User_id_invalid", "Chat not found"): message.reply_text(tld(chat.id, 'helpers_user_not_in_db')) else: LOGGER.exception("Exception %s on user %s", excp.message, user_id) return None, None return user_id, text
def send(update, message, keyboard, backup_message): chat = update.effective_chat cleanserv = sql.clean_service(chat.id) reply = update.message.message_id # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False try: msg = update.effective_message.reply_text( message, parse_mode=ParseMode.HTML, reply_markup=keyboard, reply_to_message_id=reply, disable_web_page_preview=True) except IndexError: msg = update.effective_message.reply_text( markdown_parser(backup_message + "\nNote: the current message was " "invalid due to markdown issues. Could be " "due to the user's name."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply) except KeyError: msg = update.effective_message.reply_text( markdown_parser(backup_message + "\nNote: the current message is " "invalid due to an issue with some misplaced " "curly brackets. Please update"), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply) except BadRequest as excp: if excp.message == "Button_url_invalid": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has an invalid url " "in one of its buttons. Please update."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply) elif excp.message == "Unsupported url protocol": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has buttons which " "use url protocols that are unsupported by " "telegram. Please update."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply) elif excp.message == "Wrong url host": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has some bad urls. " "Please update."), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply) LOGGER.warning(message) LOGGER.warning(keyboard) LOGGER.exception("Could not parse! got invalid url host errors") else: try: msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: An error occured when sending the " "custom message. Please update."), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN) except BadRequest: return "" return msg
def temp_nomedia(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message conn = connected(bot, update, chat, user.id) if conn: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": return else: chatD = chat user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text(tld(chat.id, "mute_not_refer")) return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text(tld(chat.id, "mute_not_existed")) return "" else: raise if is_user_admin(chat, user_id, member): message.reply_text(tld(chat.id, "restrict_is_admin")) return "" if user_id == bot.id: message.reply_text(tld(chat.id, "restrict_is_bot")) return "" if not reason: message.reply_text(tld(chat.id, "nomedia_need_time")) return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = "<b>{}:</b>" \ "\n#TEMP RESTRICTED" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>" \ "\n<b>• Time:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id, time_val) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) try: if member.can_send_messages is None or member.can_send_messages: bot.restrict_chat_member(chat.id, user_id, until_date=mutetime, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) message.reply_text( tld(chat.id, "nomedia_success").format(time_val, chatD.title)) return log else: message.reply_text( tld(chat.id, "restrict_already_restricted").format(chatD.title)) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(tld(chat.id, "nomedia_success").format( time_val, chatD.title), quote=False) return log else: LOGGER.warning(update) LOGGER.exception("ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text(tld(chat.id, "restrict_cant_restricted")) return ""
def report(bot: Bot, update: Update) -> str: message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] if chat and message.reply_to_message and sql.chat_should_report(chat.id): reported_user = message.reply_to_message.from_user # type: Optional[User] chat_name = chat.title or chat.first or chat.username admin_list = chat.get_administrators() if int(reported_user.id) == int(user.id): return if chat.username and chat.type == Chat.SUPERGROUP: msg = "<b>{}:</b>" \ "\n<b>Reported user:</b> {} (<code>{}</code>)" \ "\n<b>Reported by:</b> {} (<code>{}</code>)".format(html.escape(chat.title), mention_html( reported_user.id, reported_user.first_name), reported_user.id, mention_html(user.id, user.first_name), user.id) link = "\n<b>Link:</b> " \ "<a href=\"http://telegram.me/{}/{}\">click here</a>".format(chat.username, message.message_id) should_forward = True keyboard = [[ InlineKeyboardButton( u"➡ Message", url="https://t.me/{}/{}".format( chat.username, str(message.reply_to_message.message_id))) ], [ InlineKeyboardButton( u"⚠ Kick", callback_data="report_{}=kick={}={}".format( chat.id, reported_user.id, reported_user.first_name)), InlineKeyboardButton( u"⛔️ Ban", callback_data="report_{}=banned={}={}".format( chat.id, reported_user.id, reported_user.first_name)) ], [ InlineKeyboardButton( u"❎ Delete Message", callback_data="report_{}=delete={}={}".format( chat.id, reported_user.id, message.reply_to_message.message_id)) ]] reply_markup = InlineKeyboardMarkup(keyboard) else: msg = "{} is calling for admins in \"{}\"!".format( mention_html(user.id, user.first_name), html.escape(chat_name)) link = "" should_forward = True for admin in admin_list: if admin.user.is_bot: # can't message bots continue if sql.user_should_report(admin.user.id): try: if not chat.type == Chat.SUPERGROUP: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML, disable_web_page_preview=True) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) if not chat.username: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML, disable_web_page_preview=True) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) if chat.username and chat.type == Chat.SUPERGROUP: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML, reply_markup=reply_markup, disable_web_page_preview=True) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) except Unauthorized: pass except BadRequest as excp: # TODO: cleanup exceptions LOGGER.exception( f"Exception while reporting user : {excp}") message.reply_to_message.reply_text(tld( chat.id, "reports_success").format(mention_html(user.id, user.first_name)), parse_mode=ParseMode.HTML, disable_web_page_preview=True) return msg return ""
def get(bot, update, notename, show_none=True, no_format=False): chat = update.effective_chat user = update.effective_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 if note: pass elif notename[0] == "#": hashnote = sql.get_note(chat_id, notename[1:]) if hashnote: note = hashnote elif show_none: message.reply_text(tld(chat.id, "note_not_existed")) 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 and 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(tld(chat.id, "note_lost")) 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(tld(chat.id, "note_msg_del")) sql.rm_note(chat_id, notename) else: raise else: if note: text = note.value else: text = None 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 and note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): try: bot.send_message(send_id, 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 == "Wrong http url": failtext = tld(chat.id, "note_url_invalid") failtext += "\n\n```\n{}```".format( note.value + revert_buttons(buttons)) message.reply_text(failtext, parse_mode="markdown") else: if note: ENUM_FUNC_MAP[note.msgtype](send_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(tld(chat.id, "note_mention_invalid")) elif FILE_MATCHER.match(note.value): message.reply_text(tld(chat.id, "note_incorrect_import")) sql.rm_note(chat_id, notename) else: message.reply_text(tld(chat.id, "note_cannot_send")) LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id)) LOGGER.warning("Message was: %s", str(note.value)) return
def reply_filter(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message if 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): filt = sql.get_filter(chat.id, keyword) if filt.is_sticker: message.reply_sticker(filt.reply) elif filt.is_document: try: message.reply_document(filt.reply) except Exception: print("L") 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: try: message.reply_video(filt.reply) except Exception: print("Nut") elif filt.has_markdown: buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: message.reply_text(filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Unsupported url protocol": message.reply_text( tld(chat.id, "cust_filters_err_protocol")) 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: try: message.reply_text( tld(chat.id, "cust_filters_err_badformat")) 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)) except Exception: print("Nut") else: # LEGACY - all new filters will have has_markdown set to True. message.reply_text(filt.reply) break