def fed_broadcast(bot: Bot, update: Update, args: List[str]): msg = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] if args: chat = update.effective_chat # type: Optional[Chat] fed_id = sql.get_fed_id(chat.id) fedinfo = sql.get_fed_info(fed_id) text = "*New broadcast from the Federation {}*\n".format(fedinfo['fname']) # Parsing md raw_text = msg.text args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args txt = args[1] offset = len(txt) - len(raw_text) # set correct offset relative to command text_parser = markdown_parser(txt, entities=msg.parse_entities(), offset=offset) text += text_parser try: broadcaster = user.first_name except: broadcaster = user.first_name + " " + user.last_name text += "\n\n- {}".format(mention_markdown(user.id, broadcaster)) chat_list = sql.all_fed_chats(fed_id) failed = 0 for chat in chat_list: try: bot.sendMessage(chat, text, parse_mode="markdown") except TelegramError: failed += 1 LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name)) send_text = "The federation broadcast is complete" if failed >= 1: send_text += "{} the group failed to receive the message, probably because it left the Federation.".format(failed) update.effective_message.reply_text(send_text)
def new_fed(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message if chat.type != "private": update.effective_message.reply_text("Do it in PM?") return fednam = message.text.split(None, 1)[1] if not fednam == '': fed_id = str(uuid.uuid4()) fed_name = fednam LOGGER.info(fed_id) x = sql.new_fed(user.id, fed_name, fed_id) if not x: update.effective_message.reply_text("Federation creation failed! Keep in the mind that this rarely happened! Ask in @axelAyaGroup for help!") return update.effective_message.reply_text("*You have successfully created a new federation!*"\ "\nName: `{}`"\ "\nID: `{}`" "\n\nUse the command below to join the federation:" "\n`/joinfed {}`".format(fed_name, fed_id, fed_id), parse_mode=ParseMode.MARKDOWN) try: bot.send_message(OWNER_ID, "Federation <b>{}</b> have been created with ID: <pre>{}</pre>".format(fed_name, fed_id), parse_mode=ParseMode.HTML) except: LOGGER.warning("Cannot send a message to MESSAGE_DUMP") else: update.effective_message.reply_text("Please write down the name of the federation")
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 "" 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 message.reply_text("Banned!") 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 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 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: 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(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("You seem to be trying to use an unsupported url protocol. Telegram " "doesn't support buttons for some protocols, such as tg://. Please try " "again, or ask in @MarieSupport for help.") elif excp.message == "Reply message not found": bot.send_message(chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard) else: message.reply_text("This note could not be sent, as it is incorrectly formatted. Ask in " "@MarieSupport if you can't figure out why!") LOGGER.warning("Message %s could not be parsed", str(filt.reply)) LOGGER.exception("Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id)) else: # LEGACY - all new filters will have has_markdown set to True. message.reply_text(filt.reply) break
def 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 sed(bot: Bot, update: Update): 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: check = re.match(repl, to_fix, flags=re.IGNORECASE) if check and check.group(0).lower() == to_fix.lower(): update.effective_message.reply_to_message.reply_text( "Hey everyone, {} is trying to make " "me say stuff I don't wanna " "say!".format(update.effective_user.first_name)) return 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 broadcast(bot: Bot, update: Update): to_send = update.effective_message.text.split(None, 1) if len(to_send) >= 2: chats = sql.get_all_chats() or [] failed = 0 for chat in chats: try: 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 log_action(bot: Bot, update: Update, *args, **kwargs): result = func(bot, update, *args, **kwargs) chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[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 = sql.get_chat_log_channel(chat.id) if log_chat: send_log(bot, log_chat, chat.id, result) elif result == "": pass else: LOGGER.warning("%s was set as loggable, but had no return statement.", func) return result
def send(update, message, keyboard, backup_message): try: msg = update.effective_message.reply_text(message, parse_mode=ParseMode.MARKDOWN, 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.MARKDOWN) 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) 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) 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) 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) 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.MARKDOWN) LOGGER.exception() return msg
def user_join_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] fed_id = sql.get_fed_id(chat.id) if is_user_fed_owner(fed_id, user.id): user_id = extract_user(msg, args) if user_id: user = bot.get_chat(user_id) elif not msg.reply_to_message and not args: user = msg.from_user elif not msg.reply_to_message and (not args or ( len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not msg.parse_entities( [MessageEntity.TEXT_MENTION]))): msg.reply_text("I cannot extract users from this message") return else: LOGGER.warning('error') getuser = sql.search_user_in_fed(fed_id, user_id) fed_id = sql.get_fed_id(chat.id) info = sql.get_fed_info(fed_id) get_owner = eval(info['fusers'])['owner'] get_owner = bot.get_chat(get_owner).id if user_id == get_owner: update.effective_message.reply_text("Why are you trying to promote a federation owner?") return if getuser: update.effective_message.reply_text("I cannot promote users who are already federation admins! But I can remove them if you want!") return if user_id == bot.id: update.effective_message.reply_text("I already am a federation admin in all federations!") return res = sql.user_join_fed(fed_id, user_id) if res: update.effective_message.reply_text("Successfully Promoted!") else: update.effective_message.reply_text("Failed to promote!") else: update.effective_message.reply_text("Only federation owners can do this!")
def user_demote_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] fed_id = sql.get_fed_id(chat.id) if is_user_fed_owner(fed_id, user.id): msg = update.effective_message # type: Optional[Message] user_id = extract_user(msg, args) if user_id: user = bot.get_chat(user_id) elif not msg.reply_to_message and not args: user = msg.from_user elif not msg.reply_to_message and (not args or ( len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not msg.parse_entities( [MessageEntity.TEXT_MENTION]))): msg.reply_text("I cannot extract users from this message") return else: LOGGER.warning('error') if user_id == bot.id: update.effective_message.reply_text("Are you trying to demote me as a federation admin? Do you think I am stupid?") return if sql.search_user_in_fed(fed_id, user_id) == False: update.effective_message.reply_text("I cannot demote people who are not federation admins!") return res = sql.user_demote_fed(fed_id, user_id) if res == True: update.effective_message.reply_text("Get out of here!") else: update.effective_message.reply_text("Demotion failed!") else: update.effective_message.reply_text("Only federation owners can do this!") return
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 unfban(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] fed_id = sql.get_fed_id(chat.id) if not fed_id: update.effective_message.reply_text("This group is not a part of any federation!") return info = sql.get_fed_info(fed_id) if is_user_fed_admin(fed_id, user.id) == False: update.effective_message.reply_text("Only federation admins can do this!") return user_id = extract_user(message, args) if not user_id: message.reply_text("You do not seem to be referring to a user.") return user_chat = bot.get_chat(user_id) if user_chat.type != 'private': message.reply_text("That's not a user!") return fban, fbanreason = sql.get_fban_user(fed_id, user_id) if fban == False: message.reply_text("This user is not fbanned!") return banner = update.effective_user # type: Optional[User] message.reply_text("I'll give {} a second chance in this federation".format(user_chat.first_name)) chat_list = sql.all_fed_chats(fed_id) for chat in chat_list: try: member = bot.get_chat_member(chat, user_id) if member.status == 'kicked': bot.unban_chat_member(chat, user_id) """ bot.send_message(chat, "<b>Un-FedBan</b>" \ "\n<b>Federation:</b> {}" \ "\n<b>Federation Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>User ID:</b> <code>{}</code>".format(info['fname'], mention_html(user.id, user.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id), parse_mode="HTML") """ except BadRequest as excp: if excp.message in UNFBAN_ERRORS: pass else: LOGGER.warning("Cannot remove fban on {} because: {}".format(chat, excp.message)) except TelegramError: pass try: x = sql.un_fban_user(fed_id, user_id) if not x: message.reply_text("Fban failure, this user may have been un-fedbanned!") return except: pass message.reply_text("This person is un-fbanned.") FEDADMIN = sql.all_fed_users(fed_id)
def fed_ban(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] fed_id = sql.get_fed_id(chat.id) if not fed_id: update.effective_message.reply_text("This group is not a part of any federation!") return info = sql.get_fed_info(fed_id) OW = bot.get_chat(info['owner']) HAHA = OW.id FEDADMIN = sql.all_fed_users(fed_id) FEDADMIN.append(int(HAHA)) if is_user_fed_admin(fed_id, user.id) == False: update.effective_message.reply_text("Only federation admins can do this!") return message = update.effective_message # type: Optional[Message] user_id, reason = extract_user_and_text(message, args) fban, fbanreason = sql.get_fban_user(fed_id, user_id) if not user_id: message.reply_text("You don't seem to be referring to a user") return if user_id == bot.id: message.reply_text("What is funnier than kicking the group creator? Self sacrifice.") return if is_user_fed_owner(fed_id, user_id) == True: message.reply_text("Why did you try the federation fban?") return if is_user_fed_admin(fed_id, user_id) == True: message.reply_text("He is a federation admin, I can't fban him.") return if user_id == OWNER_ID: message.reply_text("I don't want to block my master, that's a very stupid idea!") return if int(user_id) in SUDO_USERS: message.reply_text("I will not use sudo fban!") return if int(user_id) in WHITELIST_USERS: message.reply_text("This person is whitelisted, so they can't be fban!") return try: user_chat = bot.get_chat(user_id) except BadRequest as excp: message.reply_text(excp.message) return if user_chat.type != 'private': message.reply_text("That's not a user!") return if fban: user_target = mention_html(user_chat.id, user_chat.first_name) fed_name = info['fname'] starting = "The reason fban is replaced for {} in the Federation <b>{}</b>.".format(user_target, fed_name) update.effective_message.reply_text(starting, parse_mode=ParseMode.HTML) if reason == "": reason = "No reason given." temp = sql.un_fban_user(fed_id, user_id) if not temp: message.reply_text("Failed to update the reason for fedban!") return x = sql.fban_user(fed_id, user_id, user_chat.first_name, user_chat.last_name, user_chat.username, reason) if not x: message.reply_text("Failed to ban from the federation! If this problem continues, contact @onepunchsupport.") return fed_chats = sql.all_fed_chats(fed_id) for chat in fed_chats: try: bot.kick_chat_member(chat, user_id) except BadRequest as excp: if excp.message in FBAN_ERRORS: pass else: LOGGER.warning("Could not fban on {} because: {}".format(chat, excp.message)) except TelegramError: pass send_to_list(bot, FEDADMIN, "<b>FedBan reason updated</b>" \ "\n<b>Federation:</b> {}" \ "\n<b>Federation Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>User ID:</b> <code>{}</code>" \ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id, reason), html=True) message.reply_text("FedBan reason has been updated.") return user_target = mention_html(user_chat.id, user_chat.first_name) fed_name = info['fname'] starting = "Starting a federation ban for {} in the Federation <b>{}</b>.".format(user_target, fed_name) update.effective_message.reply_text(starting, parse_mode=ParseMode.HTML) if reason == "": reason = "No reason given." x = sql.fban_user(fed_id, user_id, user_chat.first_name, user_chat.last_name, user_chat.username, reason) if not x: message.reply_text("Failed to ban from the federation! If this problem continues, contact @onepunchsupport.") return fed_chats = sql.all_fed_chats(fed_id) for chat in fed_chats: try: bot.kick_chat_member(chat, user_id) except BadRequest as excp: if excp.message in FBAN_ERRORS: try: dispatcher.bot.getChat(chat) except Unauthorized: sql.chat_leave_fed(chat) LOGGER.info("Chat {} has leave fed {} because bot is kicked".format(chat, info['fname'])) continue else: LOGGER.warning("Cannot fban on {} because: {}".format(chat, excp.message)) except TelegramError: pass send_to_list(bot, FEDADMIN, "<b>New FedBan</b>" \ "\n<b>Federation:</b> {}" \ "\n<b>Federation Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>User ID:</b> <code>{}</code>" \ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id, reason), html=True) message.reply_text("This person has been fbanned")
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("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 == 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: 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("This user is already muted.") 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 ""