def log_action(update, context, *args, **kwargs): result = func(update, context, *args, **kwargs) chat = update.effective_chat message = update.effective_message if result: if chat.type == chat.SUPERGROUP and chat.username: result += ( "\n<b>Link:</b> " '<a href="http://telegram.me/{}/{}">click here</a>'. format(chat.username, message.message_id)) log_chat = db.get_chat_log_channel(chat.id) if log_chat: try: send_log(context.bot, log_chat, chat.id, result) except Unauthorized: db.stop_chat_logging(chat.id) elif result == "": pass else: LOGGER.warning( "%s was set as loggable, but had no return statement.", func, ) return result
def command_func(update, context, *args, **kwargs): try: context.bot.send_chat_action( chat_id=update.effective_chat.id, action=ChatAction.TYPING ) return func(update, context, *args, **kwargs) except error.BadRequest as err: if str(err) == "Have no rights to send a message": LOGGER.warning("Bot muted in {} {}".format( update.effective_message.chat.title, update.effective_message.chat.id ) )
def get_exception(excp, filt, chat): if excp.message == "Unsupported url protocol": return "You seem to be trying to use the URL protocol which is not supported. Telegram does not support key for multiple protocols, such as tg: //. Please try again!" elif excp.message == "Reply message not found": return "noreply" else: LOGGER.warning("Message %s could not be parsed", str(filt.reply)) LOGGER.exception( "Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id), ) return ( "This data could not be sent because it is incorrectly formatted.")
def sed(update, context): sed_result = separate_sed(update.effective_message.text) if sed_result and update.effective_message.reply_to_message: if update.effective_message.reply_to_message.text: to_fix = update.effective_message.reply_to_message.text elif update.effective_message.reply_to_message.caption: to_fix = update.effective_message.reply_to_message.caption else: return repl, repl_with, flags = sed_result if not repl: update.effective_message.reply_to_message.reply_text( "You're trying to replace... " "nothing with something?") return try: # Protects bot from retarded geys -_- if infinite_checker(repl): return update.effective_message.reply_text("Nice try -_-") if "i" in flags and "g" in flags: text = re.sub(repl, repl_with, to_fix, flags=re.I).strip() elif "i" in flags: text = re.sub(repl, repl_with, to_fix, count=1, flags=re.I).strip() elif "g" in flags: text = re.sub(repl, repl_with, to_fix).strip() else: text = re.sub(repl, repl_with, to_fix, count=1).strip() except sre_constants.error: LOGGER.warning(update.effective_message.text) LOGGER.exception("SRE constant error") update.effective_message.reply_text( "Do you even sed? Apparently not.") return # empty string errors -_- if len(text) >= telegram.MAX_MESSAGE_LENGTH: update.effective_message.reply_text( "The result of the sed command was too long for \ telegram!") elif text: update.effective_message.reply_to_message.reply_text(text)
def snipe(update, context): args = context.args try: chat_id = str(args[0]) del args[0] except (TypeError, IndexError): update.effective_message.reply_text( "Please give me a chat to echo to!") to_send = " ".join(args) if len(to_send) >= 2: try: context.bot.sendMessage(int(chat_id), str(to_send)) except TelegramError: LOGGER.warning("Couldn't send to group %s", str(chat_id)) update.effective_message.reply_text( "Couldn't send the message. Perhaps I'm not part of that group?" ) else: update.effective_message.reply_text( "Where should i send??\nGive me the chat id!")
def broadcast(update, context): to_send = update.effective_message.text.split(None, 1) if len(to_send) >= 2: chats = users_db.get_all_chats() or [] failed = 0 for chat in chats: try: context.bot.sendMessage(int(chat["chat_id"]), to_send[1]) sleep(0.1) except TelegramError: failed += 1 LOGGER.warning( "Couldn't send broadcast to %s, group name %s", str(chat["chat_id"]), str(chat["chat_name"]), ) update.effective_message.reply_text( "Broadcast complete. {} groups failed to receive the message, probably " "due to being kicked.".format(failed))
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.", ) db.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 get(bot, update, notename, show_none=True, no_format=False): chat_id = update.effective_chat.id chat = update.effective_chat user = update.effective_user conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chat_id = conn user.id else: chat_id = update.effective_chat.id note = sql.get_note(chat_id, notename) message = update.effective_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=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: if ( ENUM_FUNC_MAP[note.msgtype] == dispatcher.bot.send_sticker ): ENUM_FUNC_MAP[note.msgtype]( chat_id, note.file, reply_to_message_id=reply_id, 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, 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 elif show_none: message.reply_text("This note doesn't exist")
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("diem bentar ya asu {}!".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("diem bentar ya asu {}!".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 send(update, message, keyboard, backup_message): chat = update.effective_chat cleanserv = sql.clean_service(chat.id) reply = update.message.message_id # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False try: msg = update.effective_message.reply_text( message, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard, reply_to_message_id=reply, ) except BadRequest as excp: if excp.message == "Button_url_invalid": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has an invalid url " "in one of its buttons. Please update." ), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) elif excp.message == "Unsupported url protocol": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has buttons which " "use url protocols that are unsupported by " "telegram. Please update." ), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) elif excp.message == "Wrong url host": msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: the current message has some bad urls. " "Please update." ), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) LOGGER.warning(message) LOGGER.warning(keyboard) LOGGER.exception("Could not parse! got invalid url host errors") elif excp.message == "Have no rights to send a message": return else: msg = update.effective_message.reply_text( markdown_parser( backup_message + "\nNote: An error occured when sending the " "custom message. Please update." ), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=reply, ) LOGGER.exception() return msg
def reply_filter(update, context): chat = update.effective_chat message = update.effective_message 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.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: valid_format = escape_invalid_curly_brackets( filt.reply_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, 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, 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) else: if (ENUM_FUNC_MAP[filt.file_type] == dispatcher.bot.send_sticker): ENUM_FUNC_MAP[filt.file_type]( chat.id, filt.file_id, reply_to_message_id=message.message_id, reply_markup=keyboard, ) else: ENUM_FUNC_MAP[filt.file_type]( chat.id, filt.file_id, caption=markdown_to_html(filtext), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML, reply_markup=keyboard, ) break else: if filt.is_sticker: message.reply_sticker(filt.reply) elif filt.is_document: message.reply_document(filt.reply) elif filt.is_image: message.reply_photo(filt.reply) elif filt.is_audio: message.reply_audio(filt.reply) elif filt.is_voice: message.reply_voice(filt.reply) elif filt.is_video: message.reply_video(filt.reply) elif filt.has_markdown: buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) try: send_message( update.effective_message, filt.reply, parse_mode=ParseMode.MARKDOWN, 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) elif excp.message == "Reply message not found": try: context.bot.send_message( chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard, ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) 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) 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) break
def ban(update, context): chat = update.effective_chat user = update.effective_user message = update.effective_message args = context.args if user_can_ban(chat, user, context.bot.id) is False: message.reply_text("You don't have enough rights to ban users!") return "" user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("Dude atleast refer some user to ban!") 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'm not gonna ban an admin, don't make fun of yourself!") return "" if user_id == context.bot.id: message.reply_text("I'm not gonna BAN myself, are you crazy or wot?") 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) # context.bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie # sticker context.bot.sendMessage( chat.id, "BANGSAT KAU {} TERBANNED .".format( mention_html(member.user.id, member.user.first_name)), parse_mode=ParseMode.HTML, ) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text("Banned!", quote=False) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Well damn, I can't ban that user.") return ""
def temp_ban(update, context): chat = update.effective_chat user = update.effective_user message = update.effective_message args = context.args if user_can_ban(chat, user, context.bot.id) is False: message.reply_text( "You don't have enough rights to temporarily ban someone!") return "" user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("Dude! atleast refer some user to ban...") 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("Wow! let's start banning Admins themselves?...") return "" if user_id == context.bot.id: message.reply_text("I'm not gonna BAN myself, are you crazy or wot?") 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) # context.bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie # sticker message.reply_text("Banned! Karena kamu jelek {}.".format(time_val)) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( "Goodbye.. we'll meet after {}.".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 ""