def reply_filter(update, context): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] if not update.effective_user or update.effective_user.id == 777000: return to_match = extract_text(message) if not to_match: return chat_filters = sql.get_chat_triggers(chat.id) for keyword in chat_filters: pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])" if re.search(pattern, to_match, flags=re.IGNORECASE): if MessageHandlerChecker.check_user(update.effective_user.id): return filt = sql.get_filter(chat.id, keyword) if filt.reply == "there is should be a new reply": buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) VALID_WELCOME_FORMATTERS = [ "first", "last", "fullname", "username", "id", "chatname", "mention", ] if filt.reply_text: if '%%%' in filt.reply_text: split = filt.reply_text.split('%%%') if all(split): text = random.choice(split) else: text = filt.reply_text else: text = filt.reply_text if text.startswith('~!') and text.endswith('!~'): sticker_id = text.replace('~!', '').replace('!~', '') try: context.bot.send_sticker( chat.id, sticker_id, reply_to_message_id=message.message_id) return except BadRequest as excp: if excp.message == 'Wrong remote file identifier specified: wrong padding in the string': context.bot.send_message( chat.id, "Message couldn't be sent, Is the sticker id valid?" ) return else: LOGGER.exception("Error in filters: " + excp.message) return valid_format = escape_invalid_curly_brackets( text, VALID_WELCOME_FORMATTERS) if valid_format: filtext = valid_format.format( first=escape(message.from_user.first_name), last=escape(message.from_user.last_name or message.from_user.first_name), fullname=" ".join( [ escape(message.from_user.first_name), escape(message.from_user.last_name), ] if message.from_user.last_name else [escape(message.from_user.first_name)]), username="******" + escape(message.from_user.username) if message.from_user.username else mention_html( message.from_user.id, message.from_user.first_name), mention=mention_html(message.from_user.id, message.from_user.first_name), chatname=escape(message.chat.title) if message.chat.type != "private" else escape( message.from_user.first_name), id=message.from_user.id, ) else: filtext = "" else: filtext = "" if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): try: context.bot.send_message( chat.id, markdown_to_html(filtext), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: error_catch = get_exception(excp, filt, chat) if error_catch == "noreply": try: context.bot.send_message( chat.id, markdown_to_html(filtext), parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) send_message( update.effective_message, get_exception(excp, filt, chat), ) else: try: send_message( update.effective_message, get_exception(excp, filt, chat), ) except BadRequest as excp: LOGGER.exception("Failed to send message: " + excp.message) pass else: try: ENUM_FUNC_MAP[filt.file_type]( chat.id, filt.file_id, caption=markdown_to_html(filtext), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest: send_message( message, "I don't have the permission to send the content of the filter." ) break else: if filt.is_sticker: message.reply_sticker(filt.reply) elif filt.is_document: message.reply_document(filt.reply) elif filt.is_image: message.reply_photo(filt.reply) elif filt.is_audio: message.reply_audio(filt.reply) elif filt.is_voice: message.reply_voice(filt.reply) elif filt.is_video: message.reply_video(filt.reply) elif filt.has_markdown: buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) try: send_message( update.effective_message, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: if excp.message == "Unsupported url protocol": try: send_message( update.effective_message, "You seem to be trying to use an unsupported url protocol. " "Telegram doesn't support buttons for some protocols, such as tg://. Please try " "again...", ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass elif excp.message == "Reply message not found": try: context.bot.send_message( chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass else: try: send_message( update.effective_message, "This message couldn't be sent as it's incorrectly formatted.", ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass LOGGER.warning("Message %s could not be parsed", str(filt.reply)) LOGGER.exception( "Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id), ) else: # LEGACY - all new filters will have has_markdown set to True. try: send_message(update.effective_message, filt.reply) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass break
def left_member(update: Update, context: CallbackContext): bot = context.bot chat = update.effective_chat user = update.effective_user should_goodbye, cust_goodbye, goodbye_type = sql.get_gdbye_pref(chat.id) if user.id == bot.id: return if should_goodbye: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False left_mem = update.effective_message.left_chat_member if left_mem: # Thingy for spamwatched users if sw is not None: sw_ban = sw.get_ban(left_mem.id) if sw_ban: return # Dont say goodbyes to gbanned users if is_user_gbanned(left_mem.id): return # Ignore bot being kicked if left_mem.id == bot.id: return # Give the owner a special goodbye if left_mem.id == OWNER_ID: update.effective_message.reply_text("Oi! Genos! He left..", reply_to_message_id=reply) return # Give the devs a special goodbye elif left_mem.id in DEV_USERS: update.effective_message.reply_text( "See you later dev!", reply_to_message_id=reply, ) return # if media goodbye, use appropriate function for it if goodbye_type != sql.Types.TEXT and goodbye_type != sql.Types.BUTTON_TEXT: ENUM_FUNC_MAP[goodbye_type](chat.id, cust_goodbye) return first_name = (left_mem.first_name or "PersonWithNoName" ) # edge case of empty name - occurs for some bugs. if cust_goodbye: if cust_goodbye == sql.DEFAULT_GOODBYE: cust_goodbye = random.choice( sql.DEFAULT_GOODBYE_MESSAGES).format( first=escape_markdown(first_name)) if left_mem.last_name: fullname = escape_markdown( f"{first_name} {left_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_members_count() mention = mention_markdown(left_mem.id, first_name) if left_mem.username: username = "******" + escape_markdown(left_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_goodbye, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(left_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=left_mem.id, ) buttons = sql.get_gdbye_buttons(chat.id) keyb = build_keyboard(buttons) else: res = random.choice( sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name) keyb = [] keyboard = InlineKeyboardMarkup(keyb) send( update, res, keyboard, random.choice( sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name), )
def get(update: Update, context: CallbackContext, notename, show_none=True, no_format=False): bot = context.bot user = update.effective_user chat_id = update.effective_message.chat.id note_chat_id = update.effective_chat.id note = sql.get_note(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 JOIN_LOGGER: try: bot.forward_message( chat_id=chat_id, from_chat_id=JOIN_LOGGER, message_id=note.value ) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "This message seems to have been lost - I'll remove it " "from your notes list." ) sql.rm_note(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(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: if not no_format: if "%%%" in valid_format: split = valid_format.split("%%%") if all(split): text = random.choice(split) else: text = valid_format else: text = valid_format else: text = valid_format text = text.format( first=escape_markdown(message.from_user.first_name), last=escape_markdown( message.from_user.last_name or message.from_user.first_name ), fullname=escape_markdown( " ".join( [message.from_user.first_name, message.from_user.last_name] if message.from_user.last_name else [message.from_user.first_name] ) ), username="******" + message.from_user.username if message.from_user.username else mention_markdown( message.from_user.id, message.from_user.first_name ), mention=mention_markdown( message.from_user.id, message.from_user.first_name ), chatname=escape_markdown( message.chat.title if message.chat.type != "private" else message.from_user.first_name ), id=message.from_user.id, ) else: text = "" keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(note_chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: setting = getprivatenotes(chat_id) if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): if setting: bot.send_message( user.id, text, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard, ) else: delmsg = bot.send_message( chat_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard, ) cleartime = get_clearcmd(chat_id, "notes") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time) elif note.msgtype in (sql.Types.STICKER, sql.Types.STICKER): if setting: ENUM_FUNC_MAP[note.msgtype]( user.id, note.file, reply_to_message_id=reply_id, reply_markup=keyboard, ) else: delmsg = ENUM_FUNC_MAP[note.msgtype]( chat_id, note.file, reply_to_message_id=reply_id, reply_markup=keyboard, ) cleartime = get_clearcmd(chat_id, "notes") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time) else: if setting: ENUM_FUNC_MAP[note.msgtype]( user.id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, 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, ) cleartime = get_clearcmd(chat_id, "notes") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time) 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(note_chat_id, notename) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted. Ask in " f"@{SUPPORT_CHAT} if you can't figure out why!" ) LOGGER.exception( "Could not parse message #%s in chat %s", notename, str(note_chat_id), ) LOGGER.warning("Message was: %s", str(note.value)) return elif show_none: message.reply_text("This note doesn't exist")
def new_member(update: Update, context: CallbackContext): bot, job_queue = context.bot, context.job_queue chat = update.effective_chat user = update.effective_user msg = update.effective_message should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref( chat.id) welc_mutes = sql.welcome_mutes(chat.id) human_checks = sql.get_human_checks(user.id, chat.id) new_members = update.effective_message.new_chat_members for new_mem in new_members: welcome_log = None res = None sent = None should_mute = True welcome_bool = True media_wel = False if sw is not None: sw_ban = sw.get_ban(new_mem.id) if sw_ban: return if should_welc: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "Oh, Genos? Let's get this moving.", reply_to_message_id=reply) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Owner just joined the chat") continue # Welcome Devs elif new_mem.id in DEV_USERS: update.effective_message.reply_text( "Whoa! A developer user just joined!", reply_to_message_id=reply, ) continue # Welcome Sudos elif new_mem.id in SUDO_USERS: update.effective_message.reply_text( "Huh! A sudo user just joined! Stay Alert!", reply_to_message_id=reply, ) continue # Welcome Support elif new_mem.id in SUPPORT_USERS: update.effective_message.reply_text( "Huh! A support user just joined!", reply_to_message_id=reply, ) continue # Welcome Whitelisted elif new_mem.id in WHITELIST_USERS: update.effective_message.reply_text( "Oof! A Wolf disaster just joined!", reply_to_message_id=reply) continue # Welcome yourself elif new_mem.id == bot.id: creator = None for x in bot.bot.get_chat_administrators( update.effective_chat.id): if x.status == 'creator': creator = x.user break if creator: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>\n<b>Creator:</b> <code>{}</code>" .format(html.escape(chat.title), chat.id, html.escape(creator)), parse_mode=ParseMode.HTML) else: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>" .format(html.escape(chat.title), chat.id), parse_mode=ParseMode.HTML) update.effective_message.reply_text("Hello everybody!", reply_to_message_id=reply) continue else: buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT): media_wel = True first_name = ( new_mem.first_name or "PersonWithNoName" ) # edge case of empty name - occurs for some bugs. if cust_welcome: if cust_welcome == sql.DEFAULT_WELCOME: cust_welcome = random.choice( sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) if new_mem.last_name: fullname = escape_markdown( f"{first_name} {new_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_members_count() mention = mention_markdown(new_mem.id, escape_markdown(first_name)) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id, ) else: res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) keyb = [] backup_message = random.choice( sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) keyboard = InlineKeyboardMarkup(keyb) else: welcome_bool = False res = None keyboard = None backup_message = None reply = None # User exceptions from welcomemutes if (is_user_ban_protected(chat, new_mem.id, chat.get_member( new_mem.id)) or human_checks): should_mute = False # Join welcome: soft mute if new_mem.is_bot: should_mute = False if user.id == new_mem.id: if should_mute: if welc_mutes == "soft": bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_add_web_page_previews=False, ), until_date=(int(time.time() + 24 * 60 * 60)), ) if welc_mutes == "strong": welcome_bool = False if not media_wel: VERIFIED_USER_WAITLIST.update({ new_mem.id: { "should_welc": should_welc, "media_wel": False, "status": False, "update": update, "res": res, "keyboard": keyboard, "backup_message": backup_message, } }) else: VERIFIED_USER_WAITLIST.update({ new_mem.id: { "should_welc": should_welc, "chat_id": chat.id, "status": False, "media_wel": True, "cust_content": cust_content, "welc_type": welc_type, "res": res, "keyboard": keyboard, } }) new_join_mem = f'<a href="tg://user?id={user.id}">{html.escape(new_mem.first_name)}</a>' message = msg.reply_text( f"{new_join_mem}, click the button below to prove you're human.\nYou have 120 seconds.", reply_markup=InlineKeyboardMarkup([{ InlineKeyboardButton( text="Yes, I'm human.", callback_data=f"user_join_({new_mem.id})", ) }]), parse_mode=ParseMode.HTML, reply_to_message_id=reply, ) bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, ), ) job_queue.run_once( partial(check_not_bot, new_mem, chat.id, message.message_id), 120, name="welcomemute", ) if welcome_bool: if media_wel: sent = ENUM_FUNC_MAP[welc_type]( chat.id, cust_content, caption=res, reply_markup=keyboard, reply_to_message_id=reply, parse_mode="markdown", ) else: sent = send(update, res, keyboard, backup_message) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) if welcome_log: return welcome_log return (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"<b>User</b>: {mention_html(user.id, user.first_name)}\n" f"<b>ID</b>: <code>{user.id}</code>") return ""