def filters(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] args = msg.text.split(None, 1) # use python's maxsplit to separate Cmd, keyword, and reply_text conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local filters" else: chat_name = chat.title if len(args) < 2: return # check irfst if BMERNU_SCUT_SRELFTI: total_fs = sql.num_filters_per_chat(chat_id) if total_fs > BMERNU_SCUT_SRELFTI: msg.reply_text( f"You currently have {total_fs} filters. " f"The maximum number of filters allowed is {BMERNU_SCUT_SRELFTI}. " "You need to delete some filters " "before being allowed to add more." ) return extracted = split_quotes(args[1]) if len(extracted) < 1: return # set trigger -> lower, so as to avoid adding duplicate filters with different cases keyword = extracted[0].lower() is_sticker = False is_document = False is_image = False is_voice = False is_audio = False is_video = False media_caption = None has_caption = False content = None # :\ buttons = [] # determine what the contents of the filter are - text, image, sticker, etc if len(extracted) >= 2: offset = len(extracted[1]) - len(msg.text) # set correct offset relative to command + notename content, buttons = button_markdown_parser(extracted[1], entities=msg.parse_entities(), offset=offset) content = content.strip() # https://t.me/c/1279877202/3508 if msg.reply_to_message and msg.reply_to_message.sticker: content = msg.reply_to_message.sticker.file_id is_sticker = True # stickers don't have caption in BOT API -_- elif msg.reply_to_message and msg.reply_to_message.document: offset = len(msg.reply_to_message.caption or "") media_caption, buttons = button_markdown_parser(msg.reply_to_message.caption, entities=msg.reply_to_message.parse_entities(), offset=offset) content = msg.reply_to_message.document.file_id is_document = True has_caption = True elif msg.reply_to_message and msg.reply_to_message.photo: offset = len(msg.reply_to_message.caption or "") media_caption, buttons = button_markdown_parser(msg.reply_to_message.caption, entities=msg.reply_to_message.parse_entities(), offset=offset) content = msg.reply_to_message.photo[-1].file_id # last elem = best quality is_image = True has_caption = True elif msg.reply_to_message and msg.reply_to_message.audio: offset = len(msg.reply_to_message.caption or "") media_caption, buttons = button_markdown_parser(msg.reply_to_message.caption, entities=msg.reply_to_message.parse_entities(), offset=offset) content = msg.reply_to_message.audio.file_id is_audio = True has_caption = True elif msg.reply_to_message and msg.reply_to_message.voice: offset = len(msg.reply_to_message.caption or "") media_caption, buttons = button_markdown_parser(msg.reply_to_message.caption, entities=msg.reply_to_message.parse_entities(), offset=offset) content = msg.reply_to_message.voice.file_id is_voice = True has_caption = True elif msg.reply_to_message and msg.reply_to_message.video: offset = len(msg.reply_to_message.caption or "") media_caption, buttons = button_markdown_parser(msg.reply_to_message.caption, entities=msg.reply_to_message.parse_entities(), offset=offset) content = msg.reply_to_message.video.file_id is_video = True has_caption = True elif msg.reply_to_message and msg.reply_to_message.text: content = msg.reply_to_message.text elif not content: # msg.reply_text("You didn't specify what to reply with!") msg.reply_text("There is no note message - You can't JUST have buttons, you need a message to go with it!") return # print(media_caption) # print(buttons) # print(content) # Add the filter # Note: perhaps handlers can be removed somehow using sql.get_chat_filters for handler in dispatcher.handlers.get(HANDLER_GROUP, []): if handler.filters == (keyword, chat.id): dispatcher.remove_handler(handler, HANDLER_GROUP) sql.add_filter(chat_id, keyword, content, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons, media_caption, has_caption) msg.reply_text("Handler '{}' added in *{}*!".format(keyword, chat_name), parse_mode=telegram.ParseMode.MARKDOWN) raise DispatcherHandlerStop
def filters(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] args = msg.text.split(None, 1) # use python's maxsplit to separate Cmd, keyword, and reply_text conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local filters" else: chat_name = chat.title if len(args) < 2: return extracted = split_quotes(args[1]) if len(extracted) < 1: return # set trigger -> lower, so as to avoid adding duplicate filters with different cases keyword = extracted[0].lower() is_sticker = False is_document = False is_image = False is_voice = False is_audio = False is_video = False buttons = [] # determine what the contents of the filter are - text, image, sticker, etc if len(extracted) >= 2: offset = len(extracted[1]) - len(msg.text) # set correct offset relative to command + notename content, buttons = button_markdown_parser(extracted[1], entities=msg.parse_entities(), offset=offset) content = content.strip() if not content: msg.reply_text("There is no note message - You can't JUST have buttons, you need a message to go with it!") return elif msg.reply_to_message and msg.reply_to_message.sticker: content = msg.reply_to_message.sticker.file_id is_sticker = True elif msg.reply_to_message and msg.reply_to_message.document: content = msg.reply_to_message.document.file_id is_document = True elif msg.reply_to_message and msg.reply_to_message.photo: offset = len(msg.reply_to_message.caption) ignore_underscore_case, buttons = button_markdown_parser(msg.reply_to_message.caption, entities=msg.reply_to_message.parse_entities(), offset=offset) content = msg.reply_to_message.photo[-1].file_id # last elem = best quality is_image = True elif msg.reply_to_message and msg.reply_to_message.audio: content = msg.reply_to_message.audio.file_id is_audio = True elif msg.reply_to_message and msg.reply_to_message.voice: content = msg.reply_to_message.voice.file_id is_voice = True elif msg.reply_to_message and msg.reply_to_message.video: content = msg.reply_to_message.video.file_id is_video = True else: msg.reply_text("You didn't specify what to reply with!") return # Add the filter # Note: perhaps handlers can be removed somehow using sql.get_chat_filters for handler in dispatcher.handlers.get(HANDLER_GROUP, []): if handler.filters == (keyword, chat.id): dispatcher.remove_handler(handler, HANDLER_GROUP) sql.add_filter(chat_id, keyword, content, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons) msg.reply_text("Handler '{}' added in *{}*!".format(keyword, chat_name), parse_mode=telegram.ParseMode.MARKDOWN) raise DispatcherHandlerStop
def unlock(update, context) -> str: args = context.args chat = update.effective_chat user = update.effective_user message = update.effective_message if is_user_admin(chat, message.from_user.id): if len(args) >= 1: ltype = args[0].lower() if ltype in LOCK_TYPES: # Connection check conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = chat.title text = "Unlocked {} for everyone in {}!".format(ltype, chat_name) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Unlocked {} for everyone!".format(ltype) sql.update_lock(chat.id, ltype, locked=False) send_message(update.effective_message, text, parse_mode="markdown") return ( "<b>{}:</b>" "\n#UNLOCK" "\n<b>Admin:</b> {}" "\nUnlocked <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, ) ) if ltype in UNLOCK_CHAT_RESTRICTION: # Connection check conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = chat.title text = "Unlocked {} for everyone in {}!".format(ltype, chat_name) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Unlocked {} for everyone!".format(ltype) current_permission = context.bot.getChat(chat_id).permissions context.bot.set_chat_permissions( chat_id=chat_id, permissions=get_permission_list( eval(str(current_permission)), UNLOCK_CHAT_RESTRICTION[ltype.lower()], ), ) send_message(update.effective_message, text, parse_mode="markdown") return ( "<b>{}:</b>" "\n#UNLOCK" "\n<b>Admin:</b> {}" "\nUnlocked <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, ) ) send_message( update.effective_message, "What are you trying to unlock...? Try /locktypes for the list of lockables.", ) else: send_message(update.effective_message, "What are you trying to unlock...?") return ""
def set_flood(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" conn = connected(bot, update, chat, user.id, need_admin=True) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": send_message(update.effective_message, "This command is meant to use in group not in PM") return "" chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if len(args) >= 1: val = args[0].lower() if val == "off" or val == "no" or val == "0": sql.set_flood(chat_id, 0) if conn: text = message.reply_text( f"Antiflood has been disabled in {chat_name}.") else: text = message.reply_text("Antiflood has been disabled.") elif val.isdigit(): amount = int(val) if amount <= 0: sql.set_flood(chat_id, 0) if conn: text = message.reply_text( f"Antiflood has been disabled in {chat_name}.") else: text = message.reply_text("Antiflood has been disabled.") return f"<b>{html.escape(chat_name)}:</b>" \ f"\n#SETFLOOD" \ f"\n<b>Admin:</b> {mention_html(user.id, user.first_name)}" \ f"\nDisable antiflood." elif amount <= 3: send_message( update.effective_message, "Antiflood must be either 0 (disabled) or number greater than 3!" ) return "" else: sql.set_flood(chat_id, amount) if conn: text = message.reply_text( f"Anti-flood has been set to {amount} in chat: {chat_name}" ) else: text = message.reply_text( f"Successfully updated anti-flood limit to {amount}!") return f"<b>{html.escape(chat_name)}:</b>" \ f"\n#SETFLOOD" \ f"\n<b>Admin:</b> {mention_html(user.id, user.first_name)}" \ f"\nSet antiflood to <code>{amount}</code>." else: message.reply_text( "Invalid argument please use a number, 'off' or 'no'") else: message.reply_text(( "Use `/setflood number` to enable anti-flood.\nOr use `/setflood off` to disable antiflood!." ), parse_mode="markdown") return ""
def promote(bot: Bot, update: Update, args: List[str]) -> str: message = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: chatD = update.effective_chat if chat.type == "private": exit(1) if not chatD.get_member(bot.id).can_promote_members: update.effective_message.reply_text( "I can't promote/demote people here! " "Make sure I'm admin and can appoint new admins.") exit(1) user_id = extract_user(message, args) if not user_id: message.reply_text( tld(chat.id, "You don't seem to be referring to a user.")) return "" user_member = chatD.get_member(user_id) if user_member.status == 'administrator' or user_member.status == 'creator': message.reply_text( tld(chat.id, "How am I meant to promote someone that's already an admin?")) return "" if user_id == bot.id: message.reply_text( tld(chat.id, "I can't promote myself! Get an admin to do it for me.")) return "" # set same perms as bot - bot can't assign higher perms than itself! bot_member = chatD.get_member(bot.id) bot.promoteChatMember( chatD.id, user_id, can_change_info=bot_member.can_change_info, can_post_messages=bot_member.can_post_messages, can_edit_messages=bot_member.can_edit_messages, can_delete_messages=bot_member.can_delete_messages, #can_invite_users=bot_member.can_invite_users, can_restrict_members=bot_member.can_restrict_members, can_pin_messages=bot_member.can_pin_messages, can_promote_members=bot_member.can_promote_members) message.reply_text(tld( chat.id, f"Successfully promoted {mention_html(user_member.user.id, user_member.user.first_name)} in {html.escape(chatD.title)}!" ), parse_mode=ParseMode.HTML) return f"<b>{html.escape(chatD.title)}:</b>" \ "\n#PROMOTED" \ f"\n<b>Admin:</b> {mention_html(user.id, user.first_name)}" \ f"\n<b>User:</b> {mention_html(user_member.user.id, user_member.user.first_name)}"
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 export_data(bot: Bot, update: Update, chat_data): msg = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] chat_id = update.effective_chat.id chat = update.effective_chat current_chat_id = update.effective_chat.id 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 used on group, not PM") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title note_list = sql.get_all_chat_notes(chat_id) backup = {} notes = {} button = "" buttonlist = [] namacat = "" isicat = "" rules = "" count = 0 countbtn = 0 # Backuping notes note_list = notesql.get_all_chat_notes(chat_id) notes = [] for note in note_list: buttonlist = "" note_tag = note.name note_type = note.msgtype getnote = notesql.get_note(chat_id, note.name) if not note.value: note_data = "" else: tombol = notesql.get_buttons(chat_id, note_tag) keyb = [] buttonlist = "" for btn in tombol: if btn.same_line: buttonlist += "[{}](buttonurl:{}:same)\n".format(btn.name, btn.url) else: buttonlist += "[{}](buttonurl:{})\n".format(btn.name, btn.url) note_data = "{}\n\n{}".format(note.value, buttonlist) note_file = note.file if not note_file: note_file = "" notes.append({"note_tag": note_tag, "note_data": note_data, "note_file": note_file, "note_type": note_type}) # Rules rules = rulessql.get_rules(chat_id) # Blacklist bl = list(blacklistsql.get_chat_blacklist(chat_id)) # Disabled command disabledcmd = list(disabledsql.get_all_disabled(chat_id)) # Filters (TODO) """ all_filters = list(filtersql.get_chat_triggers(chat_id)) export_filters = {} for filters in all_filters: filt = filtersql.get_filter(chat_id, filters) # print(vars(filt)) if filt.is_sticker: tipefilt = "sticker" elif filt.is_document: tipefilt = "doc" elif filt.is_image: tipefilt = "img" elif filt.is_audio: tipefilt = "audio" elif filt.is_voice: tipefilt = "voice" elif filt.is_video: tipefilt = "video" elif filt.has_buttons: tipefilt = "button" buttons = filtersql.get_buttons(chat.id, filt.keyword) print(vars(buttons)) elif filt.has_markdown: tipefilt = "text" if tipefilt == "button": content = "{}#=#{}|btn|{}".format(tipefilt, filt.reply, buttons) else: content = "{}#=#{}".format(tipefilt, filt.reply) print(content) export_filters[filters] = content print(export_filters) """ # Welcome (TODO) # welc = welcsql.get_welc_pref(chat_id) # Locked locks = locksql.get_locks(chat_id) locked = [] if locks: if locks.sticker: locked.append('sticker') if locks.document: locked.append('document') if locks.contact: locked.append('contact') if locks.audio: locked.append('audio') if locks.game: locked.append('game') if locks.bots: locked.append('bots') if locks.gif: locked.append('gif') if locks.photo: locked.append('photo') if locks.video: locked.append('video') if locks.voice: locked.append('voice') if locks.location: locked.append('location') if locks.forward: locked.append('forward') if locks.url: locked.append('url') restr = locksql.get_restr(chat_id) if restr.other: locked.append('other') if restr.messages: locked.append('messages') if restr.preview: locked.append('preview') if restr.media: locked.append('media') # Warns (TODO) # warns = warnssql.get_warns(chat_id) # Backing up backup[chat_id] = {'bot': bot.id, 'hashes': {'info': {'rules': rules}, 'extra': notes, 'blacklist': bl, 'disabled': disabledcmd, 'locks': locked}} baccinfo = json.dumps(backup, indent=4) f=open("Ctrl{}.backup".format(chat_id), "w") f.write(str(baccinfo)) f.close() bot.sendChatAction(current_chat_id, "upload_document") tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time())) try: bot.sendMessage(MESSAGE_DUMP, "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`".format(chat.title, chat_id, tgl), parse_mode=ParseMode.MARKDOWN) except BadRequest: pass bot.sendDocument(current_chat_id, document=open('Ctrl{}.backup'.format(chat_id), 'rb'), caption="*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This `Ctrl's Backup` is specially made for notes.".format(chat.title, chat_id, tgl), timeout=360, reply_to_message_id=msg.message_id, parse_mode=ParseMode.MARKDOWN) os.remove("CTRL{}.backup".format(chat_id)) # Cleaning file
def export_data(bot: Bot, update: Update, chat_data): msg = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] chat_id = update.effective_chat.id chat = update.effective_chat current_chat_id = update.effective_chat.id 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 used on group, not PM") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title jam = time.time() new_jam = jam + 10800 checkchat = get_chat(chat_id, chat_data) if checkchat.get('status'): if jam <= int(checkchat.get('value')): timeformatt = time.strftime("%H:%M:%S %d/%m/%Y", time.localtime(checkchat.get('value'))) update.effective_message.reply_text( "You can only backup once a day!\nYou can backup again in about `{}`" .format(timeformatt), parse_mode=ParseMode.MARKDOWN) return else: if user.id != 866838349: put_chat(chat_id, new_jam, chat_data) else: if user.id != 866838349: put_chat(chat_id, new_jam, chat_data) note_list = sql.get_all_chat_notes(chat_id) backup = {} notes = {} button = "" buttonlist = [] namacat = "" isicat = "" rules = "" count = 0 countbtn = 0 # Notes for note in note_list: count += 1 getnote = sql.get_note(chat_id, note.name) namacat += '{}<###splitter###>'.format(note.name) if note.msgtype == 1: tombol = sql.get_buttons(chat_id, note.name) keyb = [] for btn in tombol: countbtn += 1 if btn.same_line: buttonlist.append( ('{}'.format(btn.name), '{}'.format(btn.url), True)) else: buttonlist.append( ('{}'.format(btn.name), '{}'.format(btn.url), False)) isicat += '###button###: {}<###button###>{}<###splitter###>'.format( note.value, str(buttonlist)) buttonlist.clear() elif note.msgtype == 2: isicat += '###sticker###:{}<###splitter###>'.format(note.file) elif note.msgtype == 3: isicat += '###file###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 4: isicat += '###photo###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 5: isicat += '###audio###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 6: isicat += '###voice###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 7: isicat += '###video###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 8: isicat += '###video_note###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) else: isicat += '{}<###splitter###>'.format(note.value) for x in range(count): notes['#{}'.format( namacat.split("<###splitter###>")[x])] = '{}'.format( isicat.split("<###splitter###>")[x]) # Rules rules = rulessql.get_rules(chat_id) # Blacklist bl = list(blacklistsql.get_chat_blacklist(chat_id)) # Disabled command disabledcmd = list(disabledsql.get_all_disabled(chat_id)) # Filters (TODO) """ all_filters = list(filtersql.get_chat_triggers(chat_id)) export_filters = {} for filters in all_filters: filt = filtersql.get_filter(chat_id, filters) # print(vars(filt)) if filt.is_sticker: tipefilt = "sticker" elif filt.is_document: tipefilt = "doc" elif filt.is_image: tipefilt = "img" elif filt.is_audio: tipefilt = "audio" elif filt.is_voice: tipefilt = "voice" elif filt.is_video: tipefilt = "video" elif filt.has_buttons: tipefilt = "button" buttons = filtersql.get_buttons(chat.id, filt.keyword) print(vars(buttons)) elif filt.has_markdown: tipefilt = "text" if tipefilt == "button": content = "{}#=#{}|btn|{}".format(tipefilt, filt.reply, buttons) else: content = "{}#=#{}".format(tipefilt, filt.reply) print(content) export_filters[filters] = content print(export_filters) """ # Welcome (TODO) # welc = welcsql.get_welc_pref(chat_id) # Locked locks = locksql.get_locks(chat_id) locked = [] if locks: if locks.sticker: locked.append('sticker') if locks.document: locked.append('document') if locks.contact: locked.append('contact') if locks.audio: locked.append('audio') if locks.game: locked.append('game') if locks.bots: locked.append('bots') if locks.gif: locked.append('gif') if locks.photo: locked.append('photo') if locks.video: locked.append('video') if locks.voice: locked.append('voice') if locks.location: locked.append('location') if locks.forward: locked.append('forward') if locks.url: locked.append('url') restr = locksql.get_restr(chat_id) if restr.other: locked.append('other') if restr.messages: locked.append('messages') if restr.preview: locked.append('preview') if restr.media: locked.append('media') # Warns (TODO) # warns = warnssql.get_warns(chat_id) # Backing up backup[chat_id] = { 'bot': bot.id, 'hashes': { 'info': { 'rules': rules }, 'extra': notes, 'blacklist': bl, 'disabled': disabledcmd, 'locks': locked } } baccinfo = json.dumps(backup, indent=4) f = open("tg_botb{}.backup".format(chat_id), "w") f.write(str(baccinfo)) f.close() bot.sendChatAction(current_chat_id, "upload_document") tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time())) try: bot.sendMessage( MESSAGE_DUMP, "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`" .format(chat.title, chat_id, tgl), parse_mode=ParseMode.MARKDOWN) except BadRequest: pass bot.sendDocument( current_chat_id, document=open('tg_botb{}.backup'.format(chat_id), 'rb'), caption= "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This `Bot-Backup` is specially made for notes." .format(chat.title, chat_id, tgl), timeout=360, reply_to_message_id=msg.message_id, parse_mode=ParseMode.MARKDOWN) os.remove("tg_botb{}.backup".format(chat_id)) # Cleaning file
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: 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) # 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 @BotSupportGroup 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. However, You can still request a feature regarding this in @BotSupportGroup !" ) 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 @BotSupportGroup . My owner and community will be happy to help. Also, bugs report makes me even better!\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 filters(update, context): chat = update.effective_chat user = update.effective_user msg = update.effective_message args = msg.text.split( None, 1) # use python's maxsplit to separate Cmd, keyword, and reply_text conn = connected(context.bot, update, chat, user.id) if not conn is False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local filters" else: chat_name = chat.title if not msg.reply_to_message and len(args) < 2: send_message( update.effective_message, "Please provide keyboard keyword for this filter to reply with!", ) return if msg.reply_to_message: if len(args) < 2: send_message( update.effective_message, "Please provide keyword for this filter to reply with!", ) return else: keyword = args[1] else: extracted = split_quotes(args[1]) if len(extracted) < 1: return # set trigger -> lower, so as to avoid adding duplicate filters with different cases keyword = extracted[0].lower() # Add the filter # Note: perhaps handlers can be removed somehow using sql.get_chat_filters for handler in dispatcher.handlers.get(HANDLER_GROUP, []): if handler.filters == (keyword, chat_id): dispatcher.remove_handler(handler, HANDLER_GROUP) text, file_type, file_id = get_filter_type(msg) if not msg.reply_to_message and len(extracted) >= 2: offset = len(extracted[1]) - len( msg.text) # set correct offset relative to command + notename text, buttons = button_markdown_parser(extracted[1], entities=msg.parse_entities(), offset=offset) text = text.strip() if not text: send_message( update.effective_message, "There is no note message - You can't JUST have buttons, you need a message to go with it!", ) return elif msg.reply_to_message and len(args) >= 2: if msg.reply_to_message.text: text_to_parsing = msg.reply_to_message.text elif msg.reply_to_message.caption: text_to_parsing = msg.reply_to_message.caption else: text_to_parsing = "" offset = len(text_to_parsing ) # set correct offset relative to command + notename text, buttons = button_markdown_parser(text_to_parsing, entities=msg.parse_entities(), offset=offset) text = text.strip() elif not text and not file_type: send_message( update.effective_message, "Please provide keyword for this filter reply with!", ) return elif msg.reply_to_message: if msg.reply_to_message.text: text_to_parsing = msg.reply_to_message.text elif msg.reply_to_message.caption: text_to_parsing = msg.reply_to_message.caption else: text_to_parsing = "" offset = len(text_to_parsing ) # set correct offset relative to command + notename text, buttons = button_markdown_parser(text_to_parsing, entities=msg.parse_entities(), offset=offset) text = text.strip() if (msg.reply_to_message.text or msg.reply_to_message.caption) and not text: send_message( update.effective_message, "There is no note message - You can't JUST have buttons, you need a message to go with it!", ) return else: send_message(update.effective_message, "Invalid filter!") return add = addnew_filter(update, chat_id, keyword, text, file_type, file_id, buttons) # This is an old method # sql.add_filter(chat_id, keyword, content, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons) if add == True: send_message( update.effective_message, "Saved filter '{}' in *{}*!".format(keyword, chat_name), parse_mode=telegram.ParseMode.MARKDOWN, ) raise DispatcherHandlerStop
def set_flood_mode(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] args = context.args conn = connected(context.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": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if args: if args[0].lower() == "ban": settypeflood = "ban" sql.set_flood_strength(chat_id, 1, "0") elif args[0].lower() == "kick": settypeflood = "kick" sql.set_flood_strength(chat_id, 2, "0") elif args[0].lower() == "mute": settypeflood = "mute" sql.set_flood_strength(chat_id, 3, "0") elif args[0].lower() == "tban": if len(args) == 1: teks = """It looks like you tried to set time value for antiflood but you didn't specified time; Try, `/setfloodmode tban <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return settypeflood = "tban for {}".format(args[1]) sql.set_flood_strength(chat_id, 4, str(args[1])) elif args[0].lower() == "tmute": if len(args) == 1: teks = """It looks like you tried to set time value for antiflood but you didn't specified time; Try, `/setfloodmode tmute <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return settypeflood = "tmute for {}".format(args[1]) sql.set_flood_strength(chat_id, 5, str(args[1])) else: send_message(update.effective_message, "I only understand ban/kick/mute/tban/tmute!") return if conn: text = msg.reply_text( "Exceeding consecutive flood limit will result in {} in {}!". format(settypeflood, chat_name)) else: text = msg.reply_text( "Exceeding consecutive flood limit will result in {}!".format( settypeflood)) send_message(update.effective_message, text, parse_mode="markdown") return ("<b>{}:</b>\n" "<b>Admin:</b> {}\n" "Has changed antiflood mode. User will {}.".format( settypeflood, html.escape(chat.title), mention_html(user.id, user.first_name), )) getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: settypeflood = "ban" elif getmode == 2: settypeflood = "kick" elif getmode == 3: settypeflood = "mute" elif getmode == 4: settypeflood = "tban for {}".format(getvalue) elif getmode == 5: settypeflood = "tmute for {}".format(getvalue) if conn: text = msg.reply_text( "Sending more messages than flood limit will result in {} in {}.". format(settypeflood, chat_name)) else: text = msg.reply_text( "Sending more message than flood limit will result in {}.".format( settypeflood)) send_message(update.effective_message, text, parse_mode=ParseMode.MARKDOWN) return ""
def add_blackliststicker(update: Update, context: CallbackContext): bot = context.bot msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] words = msg.text.split(None, 1) bot = context.bot conn = connected(bot, update, chat, user.id) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": return else: chat_name = chat.title if len(words) > 1: text = words[1].replace("https://t.me/addstickers/", "") to_blacklist = list( { trigger.strip() for trigger in text.split("\n") if trigger.strip() }, ) added = 0 for trigger in to_blacklist: try: get = bot.getStickerSet(trigger) sql.add_to_stickers(chat_id, trigger.lower()) added += 1 except BadRequest: send_message( update.effective_message, "Sticker `{}` can not be found!".format(trigger), parse_mode="markdown", ) if added == 0: return if len(to_blacklist) == 1: send_message( update.effective_message, "Sticker <code>{}</code> added to blacklist stickers in <b>{}</b>!" .format( html.escape(to_blacklist[0]), html.escape(chat_name), ), parse_mode=ParseMode.HTML, ) else: send_message( update.effective_message, "<code>{}</code> stickers added to blacklist sticker in <b>{}</b>!" .format( added, html.escape(chat_name), ), parse_mode=ParseMode.HTML, ) elif msg.reply_to_message: added = 0 trigger = msg.reply_to_message.sticker.set_name if trigger is None: send_message(update.effective_message, "Sticker is invalid!") return try: get = bot.getStickerSet(trigger) sql.add_to_stickers(chat_id, trigger.lower()) added += 1 except BadRequest: send_message( update.effective_message, "Sticker `{}` can not be found!".format(trigger), parse_mode="markdown", ) if added == 0: return send_message( update.effective_message, "Sticker <code>{}</code> added to blacklist stickers in <b>{}</b>!" .format( trigger, html.escape(chat_name), ), parse_mode=ParseMode.HTML, ) else: send_message( update.effective_message, "Tell me what stickers you want to add to the blacklist.", )
def unblackliststicker(update: Update, context: CallbackContext): bot = context.bot msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] words = msg.text.split(None, 1) bot = context.bot conn = connected(bot, update, chat, user.id) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": return else: chat_name = chat.title if len(words) > 1: text = words[1].replace("https://t.me/addstickers/", "") to_unblacklist = list( { trigger.strip() for trigger in text.split("\n") if trigger.strip() }, ) successful = 0 for trigger in to_unblacklist: success = sql.rm_from_stickers(chat_id, trigger.lower()) if success: successful += 1 if len(to_unblacklist) == 1: if successful: send_message( update.effective_message, "Sticker <code>{}</code> deleted from blacklist in <b>{}</b>!" .format( html.escape(to_unblacklist[0]), html.escape(chat_name), ), parse_mode=ParseMode.HTML, ) else: send_message( update.effective_message, "This sticker is not on the blacklist...!", ) elif successful == len(to_unblacklist): send_message( update.effective_message, "Sticker <code>{}</code> deleted from blacklist in <b>{}</b>!". format( successful, html.escape(chat_name), ), parse_mode=ParseMode.HTML, ) elif not successful: send_message( update.effective_message, "None of these stickers exist, so they cannot be removed.", parse_mode=ParseMode.HTML, ) else: send_message( update.effective_message, "Sticker <code>{}</code> deleted from blacklist. {} did not exist, so it's not deleted." .format( successful, len(to_unblacklist) - successful, ), parse_mode=ParseMode.HTML, ) elif msg.reply_to_message: trigger = msg.reply_to_message.sticker.set_name if trigger is None: send_message(update.effective_message, "Sticker is invalid!") return success = sql.rm_from_stickers(chat_id, trigger.lower()) if success: send_message( update.effective_message, "Sticker <code>{}</code> deleted from blacklist in <b>{}</b>!". format( trigger, chat_name, ), parse_mode=ParseMode.HTML, ) else: send_message( update.effective_message, "{} not found on blacklisted stickers...!".format(trigger), ) else: send_message( update.effective_message, "Tell me what stickers you want to add to the blacklist.", )
def set_flood_mode(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] 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( tld(update.effective_message, "Use This Command in Groups,NOT in PM")) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if args: if args[0].lower() == 'ban': settypeflood = tld(update.effective_message, 'Banned') sql.set_flood_strength(chat_id, 1, "0") elif args[0].lower() == 'kick': settypeflood = tld(update.effective_message, 'Kicked') sql.set_flood_strength(chat_id, 2, "0") elif args[0].lower() == 'mute': settypeflood = tld(update.effective_message, 'Muted') sql.set_flood_strength(chat_id, 3, "0") elif args[0].lower() == 'tban': if len(args) == 1: teks = tld( update.effective_message, """It looks like you tried to set a time value for the anti-flood, but did not specify a time; use `/setfloodmode tban <timevalue>`. Examples of the value of time: 4m = 4 minute, 3h = 3 Hours, 6d = 6 days, 5w = 5 weeks.""" ) msg.reply_text(teks, parse_mode="markdown") return settypeflood = tld(update.effective_message, "temporarily ban during {}").format(args[1]) sql.set_flood_strength(chat_id, 4, str(args[1])) elif args[0].lower() == 'tmute': if len(args) == 1: teks = tld( update.effective_message, """It looks like you tried to set a time value for the anti-flood, but did not specify a time; use `/setfloodmode tban <timevalue>`. Examples of the value of time: 4m = 4 minute, 3h = 3 Hours, 6d = 6 days, 5w = 5 weeks.""" ) msg.reply_text(teks, parse_mode="markdown") return settypeflood = tld(update.effective_message, 'temporarily mute during {}').format(args[1]) sql.set_flood_strength(chat_id, 5, str(args[1])) else: msg.reply_text( tld(update.effective_message, "I understand only ban/kick/mute/tban/tmute")) return if conn: text = tld( update.effective_message, "Too many sent messages Result Will Be `{}` on *{}*!").format( settypeflood, chat_title) else: text = tld(update.effective_message, "Too many sent messages Result Will Be `{}`!").format( settypeflood) msg.reply_text(text, parse_mode="markdown") return "<b>{}:</b>\n" \ "<b>Admin:</b> {}\n" \ "Has changed antiflood mode. User will {}.".format(settypeflood, html.escape(chat.title), mention_html(user.id, user.first_name)) else: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: settypeflood = tld(update.effective_message, 'banned') elif getmode == 2: settypeflood = tld(update.effective_message, 'kick') elif getmode == 3: settypeflood = tld(update.effective_message, 'mute') elif getmode == 4: settypeflood = tld(update.effective_message, 'Blocking while during {}'.format(getvalue)) elif getmode == 5: settypeflood = tld(update.effective_message, 'temporarily mute during {}'.format(getvalue)) if conn: text = tld( update.effective_message, "If the member sends a message straight, then he will *di {}* on *{}*." ).format(settypeflood, chat_name) else: text = tld( update.effective_message, "If the member sends a message straight, then he will *di {}*." ).format(settypeflood) msg.reply_text(text, parse_mode=ParseMode.MARKDOWN) return ""
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 not conn == False: 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 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: text = note.value keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(chat_id, notename) should_preview_disabled = True if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) if "telegra.ph" in text or "youtu.be" in text: should_preview_disabled = False 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=should_preview_disabled, 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=should_preview_disabled, 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 control_panel(bot, update): print("Panel") chat = update.effective_chat user = update.effective_user #Support to run from command handler query = update.callback_query if query: query.message.delete() M_match = re.match(r"cntrl_panel_M", query.data) U_match = re.match(r"cntrl_panel_U", query.data) G_match = re.match(r"cntrl_panel_G", query.data) back_match = re.match(r"help_back", query.data) print(query.data) else: M_match = "Mia is best bot" if M_match: text = "*Control panel* 🛠 (beta)" keyboard = [[ InlineKeyboardButton(text="👤 My settings", callback_data="cntrl_panel_U(1)") ]] #Show connected chat and add chat settings button conn = connected(bot, update, chat, user.id, need_admin=False) if not conn == False: chatG = bot.getChat(conn) admin_list = chatG.get_administrators() #If user admin member = chatG.get_member(user.id) if member.status in ('administrator', 'creator'): text += "\nConnected chat - *{}* (you {})".format( chatG.title, member.status) keyboard += [[ InlineKeyboardButton(text="👥 Group settings", callback_data="cntrl_panel_G_back") ]] elif user.id in SUDO_USERS: text += "\nConnected chat - *{}* (you sudo)".format( chatG.title) keyboard += [[ InlineKeyboardButton(text="👥 Group settings (SUDO)", callback_data="cntrl_panel_G_back") ]] else: text += "\nConnected chat - *{}* (you don't admin!)".format( chatG.title) else: text += "\nNo chat connected!" keyboard += [[ InlineKeyboardButton(text="⬅️ Back", callback_data="bot_start") ]] update.effective_message.reply_text( text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.MARKDOWN) elif U_match: mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data) chatP = update.effective_chat # type: Optional[Chat] if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__user_settings__(bot, update, user) text = "You has the following settings for the *{}* module:\n\n".format( CHAT_SETTINGS[module].__mod_name__) + R[0] keyboard = R[1] keyboard += [[ InlineKeyboardButton(text="⬅️ Back", callback_data="cntrl_panel_U(1)") ]] query.message.reply_text( text=text, arse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif back_match: text = "*User control panel* 🛠" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, USER_SETTINGS, "cntrl_panel_U"))) elif G_match: mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data) prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data) next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_G_back", query.data) chatP = chat conn = connected(bot, update, chat, user.id) if not conn == False: chat = bot.getChat(conn) else: query.message.reply_text(text="Error with connection to chat") exit(1) if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__chat_settings__( bot, update, chat, chatP, user) if type(R) is list: text = R[0] keyboard = R[1] else: text = R keyboard = [] text = "*{}* has the following settings for the *{}* module:\n\n".format( escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + text keyboard += [[ InlineKeyboardButton(text="⬅️ Back", callback_data="cntrl_panel_G_back") ]] query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) 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(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, CHAT_SETTINGS, "cntrl_panel_G", 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(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, CHAT_SETTINGS, "cntrl_panel_G", chat=chat_id))) elif back_match: text = "Test" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, CHAT_SETTINGS, "cntrl_panel_G")))
def blacklist_mode(update, context): chat = update.effective_chat user = update.effective_user msg = update.effective_message args = context.args conn = connected(context.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": send_message( update.effective_message, "This command can be only used in group not in PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if args: if (args[0].lower() == "off" or args[0].lower() == "nothing" or args[0].lower() == "no"): settypeblacklist = "do nothing" sql.set_blacklist_strength(chat_id, 0, "0") elif args[0].lower() == "del" or args[0].lower() == "delete": settypeblacklist = "will delete blacklisted message" sql.set_blacklist_strength(chat_id, 1, "0") elif args[0].lower() == "warn": settypeblacklist = "warn the sender" sql.set_blacklist_strength(chat_id, 2, "0") elif args[0].lower() == "mute": settypeblacklist = "mute the sender" sql.set_blacklist_strength(chat_id, 3, "0") elif args[0].lower() == "kick": settypeblacklist = "kick the sender" sql.set_blacklist_strength(chat_id, 4, "0") elif args[0].lower() == "ban": settypeblacklist = "ban the sender" sql.set_blacklist_strength(chat_id, 5, "0") elif args[0].lower() == "tban": if len(args) == 1: teks = """It looks like you tried to set time value for blacklist but you didn't specified time; Try, `/blacklistmode tban <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return "" restime = extract_time(msg, args[1]) if not restime: teks = """Invalid time value! Example of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return "" settypeblacklist = "temporarily ban for {}".format(args[1]) sql.set_blacklist_strength(chat_id, 6, str(args[1])) elif args[0].lower() == "tmute": if len(args) == 1: teks = """It looks like you tried to set time value for blacklist but you didn't specified time; try, `/blacklistmode tmute <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return "" restime = extract_time(msg, args[1]) if not restime: teks = """Invalid time value! Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return "" settypeblacklist = "temporarily mute for {}".format(args[1]) sql.set_blacklist_strength(chat_id, 7, str(args[1])) else: send_message( update.effective_message, "I only understand: off/del/warn/ban/kick/mute/tban/tmute!", ) return "" if conn: text = "Changed blacklist mode: `{}` in *{}*!".format( settypeblacklist, chat_name) else: text = "Changed blacklist mode: `{}`!".format(settypeblacklist) send_message(update.effective_message, text, parse_mode="markdown") log_message = ("<b>{}:</b>\n" "<b>Admin:</b> {}\n" "Changed the blacklist mode. will {}.".format( html.escape(chat.title), mention_html(user.id, user.first_name), settypeblacklist, )) return log_message getmode, getvalue = sql.get_blacklist_setting(chat.id) if getmode == 0: settypeblacklist = "do nothing" elif getmode == 1: settypeblacklist = "delete" elif getmode == 2: settypeblacklist = "warn" elif getmode == 3: settypeblacklist = "mute" elif getmode == 4: settypeblacklist = "kick" elif getmode == 5: settypeblacklist = "ban" elif getmode == 6: settypeblacklist = "temporarily ban for {}".format(getvalue) elif getmode == 7: settypeblacklist = "temporarily mute for {}".format(getvalue) if conn: text = "Current blacklistmode: *{}* in *{}*.".format( settypeblacklist, chat_name) else: text = "Current blacklistmode: *{}*.".format(settypeblacklist) send_message(update.effective_message, text, parse_mode=ParseMode.MARKDOWN) return ""
def export_data(update, context): chat_data = context.chat_data msg = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] chat_id = update.effective_chat.id chat = update.effective_chat current_chat_id = update.effective_chat.id conn = connected(context.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 is a group only command!") return "" chat = update.effective_chat chat_id = update.effective_chat.id # chat_name = update.effective_message.chat.title jam = time.time() new_jam = jam + 10800 checkchat = get_chat(chat_id, chat_data) if checkchat.get("status"): if jam <= int(checkchat.get("value")): timeformatt = time.strftime("%H:%M:%S %d/%m/%Y", time.localtime(checkchat.get("value"))) update.effective_message.reply_text( "You can only backup once a day!\nYou can backup again in about `{}`" .format(timeformatt), parse_mode=ParseMode.MARKDOWN, ) return else: if user.id != OWNER_ID: put_chat(chat_id, new_jam, chat_data) else: if user.id != OWNER_ID: put_chat(chat_id, new_jam, chat_data) note_list = sql.get_all_chat_notes(chat_id) backup = {} notes = {} # button = "" buttonlist = [] namacat = "" isicat = "" rules = "" count = 0 countbtn = 0 # Notes for note in note_list: count += 1 # getnote = sql.get_note(chat_id, note.name) namacat += "{}<###splitter###>".format(note.name) if note.msgtype == 1: tombol = sql.get_buttons(chat_id, note.name) # keyb = [] for btn in tombol: countbtn += 1 if btn.same_line: buttonlist.append( ("{}".format(btn.name), "{}".format(btn.url), True)) else: buttonlist.append( ("{}".format(btn.name), "{}".format(btn.url), False)) isicat += "###button###: {}<###button###>{}<###splitter###>".format( note.value, str(buttonlist)) buttonlist.clear() elif note.msgtype == 2: isicat += "###sticker###:{}<###splitter###>".format(note.file) elif note.msgtype == 3: isicat += "###file###:{}<###TYPESPLIT###>{}<###splitter###>".format( note.file, note.value) elif note.msgtype == 4: isicat += "###photo###:{}<###TYPESPLIT###>{}<###splitter###>".format( note.file, note.value) elif note.msgtype == 5: isicat += "###audio###:{}<###TYPESPLIT###>{}<###splitter###>".format( note.file, note.value) elif note.msgtype == 6: isicat += "###voice###:{}<###TYPESPLIT###>{}<###splitter###>".format( note.file, note.value) elif note.msgtype == 7: isicat += "###video###:{}<###TYPESPLIT###>{}<###splitter###>".format( note.file, note.value) elif note.msgtype == 8: isicat += "###video_note###:{}<###TYPESPLIT###>{}<###splitter###>".format( note.file, note.value) else: isicat += "{}<###splitter###>".format(note.value) for x in range(count): notes["#{}".format( namacat.split("<###splitter###>")[x])] = "{}".format( isicat.split("<###splitter###>")[x]) # Rules rules = rulessql.get_rules(chat_id) # Blacklist bl = list(blacklistsql.get_chat_blacklist(chat_id)) # Disabled command disabledcmd = list(disabledsql.get_all_disabled(chat_id)) # Filters (TODO) """ all_filters = list(filtersql.get_chat_triggers(chat_id)) export_filters = {} for filters in all_filters: filt = filtersql.get_filter(chat_id, filters) # print(vars(filt)) if filt.is_sticker: tipefilt = "sticker" elif filt.is_document: tipefilt = "doc" elif filt.is_image: tipefilt = "img" elif filt.is_audio: tipefilt = "audio" elif filt.is_voice: tipefilt = "voice" elif filt.is_video: tipefilt = "video" elif filt.has_buttons: tipefilt = "button" buttons = filtersql.get_buttons(chat.id, filt.keyword) print(vars(buttons)) elif filt.has_markdown: tipefilt = "text" if tipefilt == "button": content = "{}#=#{}|btn|{}".format(tipefilt, filt.reply, buttons) else: content = "{}#=#{}".format(tipefilt, filt.reply) print(content) export_filters[filters] = content print(export_filters) """ # Welcome (TODO) # welc = welcsql.get_welc_pref(chat_id) # Locked curr_locks = locksql.get_locks(chat_id) curr_restr = locksql.get_restr(chat_id) if curr_locks: locked_lock = { "sticker": curr_locks.sticker, "audio": curr_locks.audio, "voice": curr_locks.voice, "document": curr_locks.document, "video": curr_locks.video, "contact": curr_locks.contact, "photo": curr_locks.photo, "gif": curr_locks.gif, "url": curr_locks.url, "bots": curr_locks.bots, "forward": curr_locks.forward, "game": curr_locks.game, "location": curr_locks.location, "rtl": curr_locks.rtl, } else: locked_lock = {} if curr_restr: locked_restr = { "messages": curr_restr.messages, "media": curr_restr.media, "other": curr_restr.other, "previews": curr_restr.preview, "all": all([ curr_restr.messages, curr_restr.media, curr_restr.other, curr_restr.preview, ]), } else: locked_restr = {} locks = {"locks": locked_lock, "restrict": locked_restr} # Warns (TODO) # warns = warnssql.get_warns(chat_id) # Backing up backup[chat_id] = { "bot": context.bot.id, "hashes": { "info": { "rules": rules }, "extra": notes, "blacklist": bl, "disabled": disabledcmd, "locks": locks, }, } baccinfo = json.dumps(backup, indent=4) f = open("YuiiChan{}.backup".format(chat_id), "w") f.write(str(baccinfo)) f.close() context.bot.sendChatAction(current_chat_id, "upload_document") tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time())) context.bot.sendDocument( current_chat_id, document=open("YuiiChan{}.backup".format(chat_id), "rb"), caption= "*Successfully Exported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This `YuiiChan-Backup` was specially made for notes." .format(chat.title, chat_id, tgl), timeout=360, reply_to_message_id=msg.message_id, parse_mode=ParseMode.MARKDOWN, ) os.remove("YuiiChan{}.backup".format(chat_id)) # Cleaning file
def unblacklist(bot: Bot, update: Update): msg = update.effective_message chat = update.effective_chat user = update.effective_user words = msg.text.split(None, 1) conn = connected(bot, update, chat, user.id) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": return else: chat_name = chat.title if len(words) > 1: text = words[1] to_unblacklist = list({ trigger.strip() for trigger in text.split("\n") if trigger.strip() }) successful = 0 for trigger in to_unblacklist: success = sql.rm_from_blacklist(chat_id, trigger.lower()) if success: successful += 1 if len(to_unblacklist) == 1: if successful: send_message( update.effective_message, "Removed <code>{}</code> from blacklist in <b>{}</b>!". format(html.escape(to_unblacklist[0]), chat_name), parse_mode=ParseMode.HTML, ) else: send_message(update.effective_message, "This is not a blacklist trigger!") elif successful == len(to_unblacklist): send_message( update.effective_message, "Removed <code>{}</code> from blacklist in <b>{}</b>!".format( successful, chat_name), parse_mode=ParseMode.HTML, ) elif not successful: send_message( update.effective_message, "None of these triggers exist so it can't be removed.".format( successful, len(to_unblacklist) - successful), parse_mode=ParseMode.HTML, ) else: send_message( update.effective_message, "Removed <code>{}</code> from blacklist. {} did not exist, " "so were not removed.".format(successful, len(to_unblacklist) - successful), parse_mode=ParseMode.HTML, ) else: send_message( update.effective_message, "Tell me which words you would like to remove from blacklist!", )
def import_data(update, context): msg = update.effective_message chat = update.effective_chat user = update.effective_user # TODO: allow uploading doc with command, not just as reply # only work with a doc conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": update.effective_message.reply_text( "This is a group only command!") return "" chat = update.effective_chat chat_name = update.effective_message.chat.title if msg.reply_to_message and msg.reply_to_message.document: try: file_info = context.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 to me!" ) return with BytesIO() as file: file_info.download(out=file) file.seek(0) data = json.load(file) # 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)) is 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 Exception: return msg.reply_text( "There was a problem while importing the data!") # Check if backup is from self try: if str(context.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 Exception: 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 take it to @yuiichansupport" ) log.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 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 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] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id = extract_user(message, args) if not user_id: message.reply_text( tld( chat.id, "You'll need to either give me a username to restrict, or reply to someone to be restricted." )) return "" if user_id == bot.id: message.reply_text(tld(chat.id, "I'm not restricting myself!")) return "" member = chatD.get_member(int(user_id)) if member: if is_user_admin(chatD, user_id, member=member): message.reply_text(tld(chat.id, "Afraid I can't restrict admins!")) elif member.can_send_messages is None or member.can_send_messages: bot.restrict_chat_member(chatD.id, user_id, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) keyboard = [] reply = tld(chat.id, "{} is restricted from sending media in {}!").format( mention_html(member.user.id, member.user.first_name), chatD.title) message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) return "<b>{}:</b>" \ "\n#RESTRICTED" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".format(html.escape(chatD.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) else: message.reply_text( tld(chat.id, "This user is already restricted in {}!")) else: message.reply_text( tld(chat.id, "This user isn't in the {}!").format(chatD.title)) return ""
def set_flood_mode(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] 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": send_message(update.effective_message, "This command is meant to use in group not in PM") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if args: if args[0].lower() == 'ban': settypeflood = ('ban') sql.set_flood_strength(chat_id, 1, "0") elif args[0].lower() == 'kick': settypeflood = ('kick') sql.set_flood_strength(chat_id, 2, "0") elif args[0].lower() == 'mute': settypeflood = ('mute') sql.set_flood_strength(chat_id, 3, "0") elif args[0].lower() == 'tban': if len(args) == 1: teks = update.effective_message, """It looks like you tried to set time value for antiflood but you didn't specified time; Try, `/setfloodmode tban <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return settypeflood = (f"tban for {args[1]}") sql.set_flood_strength(chat_id, 4, str(args[1])) elif args[0].lower() == 'tmute': if len(args) == 1: teks = update.effective_message, """It looks like you tried to set time value for antiflood but you didn't specified time; Try, `/setfloodmode tmute <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return settypeflood = (f"tmute for {args[1]}") sql.set_flood_strength(chat_id, 5, str(args[1])) else: send_message(update.effective_message, "I only understand ban/kick/mute/tban/tmute!") return if conn: text = msg.reply_text( f"Exceeding consecutive flood limit will result in {settypeflood} in {chat_name}!" ) else: text = msg.reply_text( f"Exceeding consecutive flood limit will result in {settypeflood}!" ) return f"<b>{settypeflood}:</b>\n" \ f"<b>Admin:</b> {html.escape(chat.title)}\n" \ f"Has changed antiflood mode. User will {mention_html(user.id, user.first_name)}." else: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: settypeflood = ('ban') elif getmode == 2: settypeflood = ('kick') elif getmode == 3: settypeflood = ('mute') elif getmode == 4: settypeflood = (f'tban for {getvalue}') elif getmode == 5: settypeflood = (f'tmute for {getvalue}') if conn: text = msg.reply_text( f"Sending more messages than flood limit will result in {settypeflood} in {chat_name}." ) else: text = msg.reply_text( f"Sending more message than flood limit will result in {settypeflood}." ) return ""
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] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text( tld(chat.id, "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(tld(chat.id, "I can't seem to find this user")) return "" else: raise if is_user_admin(chat, user_id, member): message.reply_text( tld(chat.id, "I really wish I could restrict admins...")) return "" if user_id == bot.id: message.reply_text( tld(chat.id, "I'm not gonna RESTRICT myself, are you crazy?")) return "" if not reason: message.reply_text( tld(chat.id, "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( tld(chat.id, "Restricted from sending media for {} in {}!").format( time_val, chatD.title)) return log else: message.reply_text( tld(chat.id, "This user is already restricted in {}.").format( chatD.title)) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(tld(chat.id, "Restricted for {} in {}!").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, "Well damn, I can't restrict that user.")) return ""
def demote(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: chatD = update.effective_chat if chat.type == "private": exit(1) if not chatD.get_member(bot.id).can_promote_members: update.effective_message.reply_text( "I can't promote/demote people here! " "Make sure I'm admin and can appoint new admins.") exit(1) user_id = extract_user(message, args) if not user_id: message.reply_text( tld(chat.id, "You don't seem to be referring to a user.")) return "" user_member = chatD.get_member(user_id) if user_member.status == 'creator': message.reply_text( tld(chat.id, "This person CREATED the chat, how would I demote them?")) return "" if not user_member.status == 'administrator': message.reply_text(tld(chat.id, "Can't demote what wasn't promoted!")) return "" if user_id == bot.id: message.reply_text(tld(chat.id, "I can't demote myself!")) return "" try: bot.promoteChatMember(int(chatD.id), int(user_id), can_change_info=False, can_post_messages=False, can_edit_messages=False, can_delete_messages=False, can_invite_users=False, can_restrict_members=False, can_pin_messages=False, can_promote_members=False) message.reply_text(tld(chat.id, f"Successfully demoted in *{chatD.title}*!"), parse_mode=ParseMode.MARKDOWN) return f"<b>{html.escape(chatD.title)}:</b>" \ "\n#DEMOTED" \ f"\n<b>Admin:</b> {mention_html(user.id, user.first_name)}" \ f"\n<b>User:</b> {mention_html(user_member.user.id, user_member.user.first_name)}" except BadRequest: message.reply_text( tld( chat.id, "Could not demote. I might not be admin, or the admin status was appointed by another user, so I can't act upon them!" )) return ""
def unmute(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] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id = extract_user(message, args) if not user_id: message.reply_text( tld( chat.id, "You'll need to either give me a username to unmute, or reply to someone to be unmuted." )) return "" member = chatD.get_member(int(user_id)) if member.status != 'kicked' and member.status != 'left': if member.can_send_messages and member.can_send_media_messages \ and member.can_send_other_messages and member.can_add_web_page_previews: message.reply_text( tld(chat.id, "This user already has the right to speak in {}.").format( chatD.title)) else: bot.restrict_chat_member(chatD.id, int(user_id), can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True) keyboard = [] reply = tld(chat.id, "Yep, {} can start talking again in {}!").format( mention_html(member.user.id, member.user.first_name), chatD.title) message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) return "<b>{}:</b>" \ "\n#UNMUTE" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".format(html.escape(chatD.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) else: message.reply_text( tld( chat.id, "This user isn't even in the chat, unmuting them won't make them talk more than they " "already do!")) return ""
def lock(update, context) -> str: args = context.args chat = update.effective_chat user = update.effective_user if ( can_delete(chat, context.bot.id) or update.effective_message.chat.type == "private" ): if len(args) >= 1: ltype = args[0].lower() if ltype in LOCK_TYPES: # Connection check conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = chat.title text = "Locked {} for non-admins in {}!".format(ltype, chat_name) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Locked {} for non-admins!".format(ltype) sql.update_lock(chat.id, ltype, locked=True) send_message(update.effective_message, text, parse_mode="markdown") return ( "<b>{}:</b>" "\n#LOCK" "\n<b>Admin:</b> {}" "\nLocked <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, ) ) if ltype in LOCK_CHAT_RESTRICTION: # Connection check conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = chat.title text = "Locked {} for all non-admins in {}!".format( ltype, chat_name ) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Locked {} for all non-admins!".format(ltype) current_permission = context.bot.getChat(chat_id).permissions context.bot.set_chat_permissions( chat_id=chat_id, permissions=get_permission_list( eval(str(current_permission)), LOCK_CHAT_RESTRICTION[ltype.lower()], ), ) send_message(update.effective_message, text, parse_mode="markdown") return ( "<b>{}:</b>" "\n#Permission_LOCK" "\n<b>Admin:</b> {}" "\nLocked <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, ) ) send_message( update.effective_message, "What are you trying to lock...? Try /locktypes for the list of lockables", ) else: send_message(update.effective_message, "What are you trying to lock...?") else: send_message( update.effective_message, "I am not administrator or haven't got enough rights.", ) return ""
def blacklist_mode(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] 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": send_message(update.effective_message, "You can do this command in groups, not PM") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if args: if args[0].lower() == 'off' or args[0].lower() == 'nothing' or args[0].lower() == 'no': settypeblacklist = 'turn off' sql.set_blacklist_strength(chat_id, 0, "0") elif args[0].lower() == 'del' or args[0].lower() == 'delete': settypeblacklist = 'left, the message will be deleted' sql.set_blacklist_strength(chat_id, 1, "0") elif args[0].lower() == 'warn': settypeblacklist = 'warned' sql.set_blacklist_strength(chat_id, 2, "0") elif args[0].lower() == 'mute': settypeblacklist = 'muted' sql.set_blacklist_strength(chat_id, 3, "0") elif args[0].lower() == 'kick': settypeblacklist = 'kicked' sql.set_blacklist_strength(chat_id, 4, "0") elif args[0].lower() == 'ban': settypeblacklist = 'banned' sql.set_blacklist_strength(chat_id, 5, "0") elif args[0].lower() == 'tban': if len(args) == 1: teks = """It looks like you are trying to set a temporary value to blacklist, but has not determined the time; use `/blstickermode tban <timevalue>`. Examples of time values: 4m = 4 minute, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return settypeblacklist = 'temporary banned for {}'.format(args[1]) sql.set_blacklist_strength(chat_id, 6, str(args[1])) elif args[0].lower() == 'tmute': if len(args) == 1: teks = """It looks like you are trying to set a temporary value to blacklist, but has not determined the time; use `/blstickermode tmute <timevalue>`. Examples of time values: 4m = 4 minute, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return settypeblacklist = tl(update.effective_message, 'temporary muted for {}').format(args[1]) sql.set_blacklist_strength(chat_id, 7, str(args[1])) else: send_message(update.effective_message, "I only understand off/del/warn/ban/kick/mute/tban/tmute!") return if conn: text = "Blacklist sticker mode changed, will `{}` at *{}*!".format(settypeblacklist, chat_name) else: text = "Blacklist sticker mode changed, will `{}`!".format(settypeblacklist) send_message(update.effective_message, text, parse_mode="markdown") return "<b>{}:</b>\n" \ "<b>Admin:</b> {}\n" \ "Changed sticker blacklist mode. Will {}.".format(html.escape(chat.title), mention_html(user.id, user.first_name), settypeblacklist) else: getmode, getvalue = sql.get_blacklist_setting(chat.id) if getmode == 0: settypeblacklist = "not active" elif getmode == 1: settypeblacklist = "hapus" elif getmode == 2: settypeblacklist = "warn" elif getmode == 3: settypeblacklist = "mute" elif getmode == 4: settypeblacklist = "kick" elif getmode == 5: settypeblacklist = "ban" elif getmode == 6: settypeblacklist = "temporarily banned for {}".format(getvalue) elif getmode == 7: settypeblacklist = "temporarily muted for {}".format(getvalue) if conn: text = "Blacklist sticker mode is currently set to *{}* in *{}*.".format(settypeblacklist, chat_name) else: text = "Blacklist sticker mode is currently set to *{}*.".format(settypeblacklist) send_message(update.effective_message, text, parse_mode=ParseMode.MARKDOWN) return ""
def set_flood(update, context) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] args = context.args conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if len(args) >= 1: val = args[0].lower() if val == "off" or val == "on" or val == "0": sql.set_flood(chat_id, 0) if conn: text = message.reply_text( "Antiflood has been disabled in {}.".format(chat_name)) else: text = message.reply_text("Antiflood has been disabled.") send_message(update.effective_message, text, parse_mode="markdown") elif val.isdigit(): amount = int(val) if amount <= 0: sql.set_flood(chat_id, 0) if conn: text = message.reply_text( "Antiflood has been disabled in {}.".format(chat_name)) else: text = message.reply_text("Antiflood has been disabled.") return ("<b>{}:</b>" "\n#SETFLOOD" "\n<b>Admin:</b> {}" "\nDisable antiflood.".format( html.escape(chat_name), mention_html(user.id, user.first_name), )) elif amount < 3: send_message( update.effective_message, "Antiflood must be either 0 (disabled) or number greater than 3!", ) return "" else: sql.set_flood(chat_id, amount) if conn: text = message.reply_text( "Anti-flood has been set to {} in chat: {}".format( amount, chat_name)) else: text = message.reply_text( "Successfully updated anti-flood limit to {}!".format( amount)) send_message(update.effective_message, text, parse_mode="markdown") return ("<b>{}:</b>" "\n#SETFLOOD" "\n<b>Admin:</b> {}" "\nSet antiflood to <code>{}</code>.".format( html.escape(chat_name), mention_html(user.id, user.first_name), amount, )) else: message.reply_text( "Invalid argument please use a number, 'off' or 'on'") else: message.reply_text( ("Use `/setflood number` to enable anti-flood.\nOr use `/setflood off` to disable antiflood!." ), parse_mode="markdown", ) return ""
def control_panel(bot, update): chat = update.effective_chat user = update.effective_user # ONLY send help in PM if chat.type != chat.PRIVATE: update.effective_message.reply_text( "Contact me in PM to access the control panel.", reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="Control Panel", url=f"t.me/{bot.username}?start=controlpanel") ]])) return #Support to run from command handler query = update.callback_query if query: try: query.message.delete() except BadRequest as ee: update.effective_message.reply_text( f"Failed to delete query, {ee}") M_match = re.match(r"cntrl_panel_M", query.data) U_match = re.match(r"cntrl_panel_U", query.data) G_match = re.match(r"cntrl_panel_G", query.data) back_match = re.match(r"help_back", query.data) else: M_match = "Haruka Aya is best bot" #LMAO, don't uncomment if M_match: text = "*Control panel* 🛠" keyboard = [[ InlineKeyboardButton(text="👤 My settings", callback_data="cntrl_panel_U(1)") ]] #Show connected chat and add chat settings button conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chatG = bot.getChat(conn) #admin_list = chatG.get_administrators() #Unused variable #If user admin member = chatG.get_member(user.id) if member.status in ('administrator', 'creator'): text += f"\nConnected chat - *{chatG.title}* (you {member.status})" keyboard += [[ InlineKeyboardButton(text="👥 Group settings", callback_data="cntrl_panel_G_back") ]] elif user.id in SUDO_USERS: text += f"\nConnected chat - *{chatG.title}* (you sudo)" keyboard += [[ InlineKeyboardButton(text="👥 Group settings (SUDO)", callback_data="cntrl_panel_G_back") ]] else: text += f"\nConnected chat - *{chatG.title}* (you aren't an admin!)" else: text += "\nNo chat connected!" keyboard += [[ InlineKeyboardButton(text="⬅️ Back", callback_data="bot_start") ]] update.effective_message.reply_text( text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.MARKDOWN) elif U_match: mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data) chatP = update.effective_chat # type: Optional[Chat] if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__user_settings__(bot, update, user) text = "You has the following settings for the *{}* module:\n\n".format( CHAT_SETTINGS[module].__mod_name__) + R[0] keyboard = R[1] keyboard += [[ InlineKeyboardButton(text="⬅️ Back", callback_data="cntrl_panel_U(1)") ]] query.message.reply_text( text=text, arse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif back_match: text = "*User control panel* 🛠" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, USER_SETTINGS, "cntrl_panel_U"))) elif G_match: mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data) prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data) next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_G_back", query.data) chatP = chat conn = connected(bot, update, chat, user.id) if not conn == False: chat = bot.getChat(conn) else: query.message.reply_text(text="Error with connection to chat") exit(1) if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__chat_settings__( bot, update, chat, chatP, user) if type(R) is list: text = R[0] keyboard = R[1] else: text = R keyboard = [] text = "*{}* has the following settings for the *{}* module:\n\n".format( escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + text keyboard += [[ InlineKeyboardButton(text="Back", callback_data="cntrl_panel_G_back") ]] query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) 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(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, 0, CHAT_SETTINGS, "cntrl_panel_G", 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(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, 0, CHAT_SETTINGS, "cntrl_panel_G", chat=chat_id))) elif back_match: text = "Control Panel :3" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, CHAT_SETTINGS, "cntrl_panel_G")))