def list_handlers(bot: Bot, update: Update): 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 chat_name = dispatcher.bot.getChat(conn).title filter_list = "*Filters in {}:*\n" else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local filters" filter_list = "*local filters:*\n" else: chat_name = chat.title filter_list = "*Filters in {}*:\n".format(chat_name) all_handlers = sql.get_chat_triggers(chat_id) if not all_handlers: update.effective_message.reply_text("No filters in *{}*!".format(chat_name), parse_mode=telegram.ParseMode.MARKDOWN) return for keyword in all_handlers: entry = " - {}\n".format(escape_markdown(keyword)) if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH: update.effective_message.reply_text(filter_list, parse_mode=telegram.ParseMode.MARKDOWN) filter_list = entry else: filter_list += entry if not filter_list == BASIC_FILTER_STRING: update.effective_message.reply_text(filter_list, parse_mode=telegram.ParseMode.MARKDOWN)
def stop_filter(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] args = update.effective_message.text.split(None, 1) conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = chat.id if chat.type == "private": chat_name = "local notes" else: chat_name = chat.title if len(args) < 2: return chat_filters = sql.get_chat_triggers(chat_id) if not chat_filters: update.effective_message.reply_text("No filters are active in *{}*!".format(chat_name), parse_mode=telegram.ParseMode.MARKDOWN) return for keyword in chat_filters: if keyword == args[1]: sql.remove_filter(chat_id, args[1]) update.effective_message.reply_text("Yep, I'll stop replying to that in *{}*.".format(chat_name), parse_mode=telegram.ParseMode.MARKDOWN) raise DispatcherHandlerStop update.effective_message.reply_text("That's not a current filter - run /filters for all active filters.")
def blackliststicker(bot: Bot, update: Update, args: List[str]): msg = update.effective_message # type: Optional[Message] 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 chat_name = dispatcher.bot.getChat(conn).title else: if chat.type == "private": return else: chat_id = update.effective_chat.id chat_name = chat.title sticker_list = "<b>List black stickers currently in {}:</b>\n".format( chat_name) all_stickerlist = sql.get_chat_stickers(chat_id) if len(args) > 0 and args[0].lower() == 'copy': for trigger in all_stickerlist: sticker_list += "<code>{}</code>\n".format(html.escape(trigger)) elif len(args) == 0: for trigger in all_stickerlist: sticker_list += " - <code>{}</code>\n".format(html.escape(trigger)) split_text = split_message(sticker_list) for text in split_text: if sticker_list == "<b>List black stickers currently in {}:</b>\n".format( chat_name).format(chat_name): send_message(update.effective_message, "There is no blacklist sticker in <b>{}</b>!".format( chat_name), parse_mode=ParseMode.HTML) return send_message(update.effective_message, text, parse_mode=ParseMode.HTML)
def add_blackliststicker(bot: Bot, update: Update): 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) 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( set(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]), chat_name), parse_mode=ParseMode.HTML) else: send_message( update.effective_message, "<code>{}</code> stickers added to blacklist sticker in <b>{}</b>!" .format(added, chat_name), parse_mode=ParseMode.HTML) elif msg.reply_to_message: added = 0 trigger = msg.reply_to_message.sticker.set_name if trigger == 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, chat_name), parse_mode=ParseMode.HTML) else: send_message( update.effective_message, "Tell me what stickers you want to add to the blacklist stickers.")
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 unblackliststicker(bot: Bot, update: Update): 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) 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( set(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]), chat_name), parse_mode=ParseMode.HTML) else: send_message(update.effective_message, "This is not on the blacklist stickers...!") elif successful == len(to_unblacklist): send_message( update.effective_message, "Sticker <code>{}</code> deleted from blacklist in <b>{}</b>!". format(successful, chat_name), parse_mode=ParseMode.HTML) elif not successful: send_message( update.effective_message, "None of these stickers exist, so they cannot be removed.". format(successful, len(to_unblacklist) - successful), 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 == 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 stickers.")
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("Filter '{}' added in *{}*!".format(keyword, chat_name), parse_mode=telegram.ParseMode.MARKDOWN) raise DispatcherHandlerStop
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] 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! try again") # 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 @Telegram 😂 !" ) 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.Try Again!" ) 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 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 != 1491765026: put_chat(chat_id, new_jam, chat_data) else: if user.id != 1491765026: 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) 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("aurora{}.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('aurora{}.backup'.format(chat_id), 'rb'), caption= "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This 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("cinderella{}.backup".format(chat_id)) # Cleaning file