def flood(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message conn = connected(context.bot, update, chat, user.id, need_admin=False) 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, "Este comando está destinado a usarse en grupo, no en PM") return chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title limit = sql.get_flood_limit(chat_id) if limit == 0: if conn: text = msg.reply_text( "No estoy imponiendo ningún control de flood en {}!".format(chat_name)) else: text = msg.reply_text("No estoy imponiendo ningún control de flood aquí!") else: if conn: text = msg.reply_text( "Actualmente estoy restringiendo miembros después de {} mensajes consecutivos en {}." .format(limit, chat_name)) else: text = msg.reply_text( "Actualmente estoy restringiendo miembros después de {} mensajes consecutivos." .format(limit))
def blackliststicker(update: Update, context: CallbackContext): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] bot, args = context.bot, context.args 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>Lista de stickers en la lista negra actualmente en {}:</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>Lista de stickers en la lista negra actualmente en {}:</b>\n".format( chat_name).format(chat_name): send_message( update.effective_message, "No hay stickers de lista negra en <b>{}</b>!".format( chat_name), parse_mode=ParseMode.HTML) return send_message(update.effective_message, text, parse_mode=ParseMode.HTML)
def list_locks(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # Connection check conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_name = chat.title else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "Este comando está destinado a usarse en grupo, no en PM", ) return "" chat = update.effective_chat chat_name = update.effective_message.chat.title res = build_lock_message(chat.id) if conn: res = res.replace("Bloquear en", "*{}*".format(chat_name)) send_message(update.effective_message, res, parse_mode=ParseMode.MARKDOWN)
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 = "Mensajes {} desbloqueados para todos en {}!".format( ltype, chat_name) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "Este comando está destinado a usarse en grupo, no en PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "{} mensajes desbloqueados para todos!".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>Administrador:</b> {}" "\nUnlocked <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, )) elif 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 = "Desbloqueado {} para todos en {}!".format( ltype, chat_name) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "Este comando está destinado a usarse en grupo, no en PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Desbloqueado {} para todos!".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>Administrador:</b> {}" "\nUnlocked <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, )) else: send_message( update.effective_message, "¿Qué estás intentando desbloquear ...? Pruebe /locktypes para la lista de bloqueables.", ) else: send_message(update.effective_message, "Que estas tratando de desbloquear...?") 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 = "Se bloquearon todos los {} mensajes para los miembros en {}!".format( ltype, chat_name) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "Este comando está destinado a usarse en grupo, no en PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Se bloquearon todos los {} mensajes para los miembros.".format( ltype) sql.update_lock(chat.id, ltype, locked=True) send_message( update.effective_message, text, parse_mode="markdown") return ("<b>{}:</b>" "\n#MediaLock" "\n<b>Administrador:</b> {}" "\nBloqueo a <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, )) elif 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 = "Bloqueado {} para todos los no administradores en {}!".format( ltype, chat_name) else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "Este comando está destinado a usarse en grupo, no en PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Bloqueado {} para todos los miembros!".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>Administrador:</b> {}" "\nLock <code>{}</code>.".format( html.escape(chat.title), mention_html(user.id, user.first_name), ltype, )) else: send_message( update.effective_message, "¿Qué estás intentando bloquear...? Pruebe /locktypes para la lista de bloqueables", ) else: send_message(update.effective_message, "Que estas tratando de bloquear...?") else: send_message( update.effective_message, "No soy administradora o no tengo suficientes derechos.", ) return ""
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, "Este comando está destinado a usarse en grupo, no en 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 = """Parece que intentó establecer un valor de tiempo para el antiflood pero no especificó el tiempo; Prueba, `/setfloodmode tban <valor de tiempo>`. Ejemplos de valor de tiempo: 4m = 4 minutos, 3h = 3 horas, 6d = 6 días, 5w = 5 semanas.""" 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 = update.effective_message, """Parece que intentó establecer un valor de tiempo para el antiflood pero no especificó el tiempo; Prueba, `/setfloodmode tmute <valor de tiempo>`. Ejemplos de valor de tiempo: 4m = 4 minutos, 3h = 3 horas, 6d = 6 días, 5w = 5 semanas.""" 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, "Solo entiendo /ban /kick /mute /tban /tmute!") return if conn: text = msg.reply_text( "Exceder el límite de flood consecutivos resultará en {} en {}!" .format(settypeflood, chat_name)) else: text = msg.reply_text( "Exceder el límite de flood consecutivo resultará en {}!".format( settypeflood)) return "<b>{}:</b>\n" \ "<b>Administrador:</b> {}\n" \ "Ha cambiado el modo anti-flood. Al usuario {}.".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 = ('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( "Enviar más mensajes que el límite de flood resultará en {} en {}." .format(settypeflood, chat_name)) else: text = msg.reply_text( "Enviar más mensajes que el límite de flood resultará en {}." .format(settypeflood)) 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, "Este comando está destinado a usarse en grupo, no en 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( "El anti-flood ha sido deshabilitado en {}.".format(chat_name)) else: text = message.reply_text("El anti-flood ha sido deshabilitado.") elif val.isdigit(): amount = int(val) if amount <= 0: sql.set_flood(chat_id, 0) if conn: text = message.reply_text( "El anti-flood ha sido deshabilitado en {}.".format(chat_name)) else: text = message.reply_text("El anti-flood ha sido deshabilitado.") return "<b>{}:</b>" \ "\n#SetFlood" \ "\n<b>Administrador:</b> {}" \ "\nDesactivo el anti-flood.".format(html.escape(chat_name), mention_html(user.id, user.first_name)) elif amount < 3: send_message( update.effective_message, "El anti-flood debe ser 0 (desactivado) o un número mayor que 3!" ) return "" else: sql.set_flood(chat_id, amount) if conn: text = message.reply_text( " El anti-flood se ha configurado en {} en el chat: {}".format( amount, chat_name)) else: text = message.reply_text( "Límite anti-flood actualizado con éxito para {}!".format( amount)) return "<b>{}:</b>" \ "\n#SETFLOOD" \ "\n<b>Administrador:</b> {}" \ "\nEstablecer anti-flood en <code>{}</code>.".format(html.escape(chat_name), mention_html(user.id, user.first_name), amount) else: message.reply_text( "Argumento no válido, utilice un número, 'off' o 'no'") else: message.reply_text(( "Use `/setflood (numero)` para habilitar anti-flood.\nO use `/setflood off` para deshabilitar anti-flood!." ), parse_mode="markdown") return ""
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( "Este es un comando solo para grupos!") 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( "Intente descargar y cargar el archivo usted mismo nuevamente, este me aparece roto!" ) 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( "Hay más de un grupo en este archivo y el chat.id no es el mismo. ¿Cómo se supone que debo importarlo??" ) return # Check if backup is this chat try: if data.get(str(chat.id)) == None: if conn: text = "La copia de seguridad proviene de otro chat, no puedo devolver otro chat al chat *{}*".format( chat_name) else: text = "La copia de seguridad proviene de otro chat, no puedo devolver otro chat a este chat" return msg.reply_text(text, parse_mode="markdown") except Exception: return msg.reply_text("Hubo un problema al importar los datos!") # Check if backup is from self try: if str(context.bot.id) != str(data[str(chat.id)]["bot"]): return msg.reply_text( "La copia de seguridad de otro bot que no se sugiere puede causar el problema, los documentos, las fotos, los videos, los audios, los registros pueden no funcionar como deberían.." ) 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( "Se produjo un error al recuperar sus datos. El proceso falló. Si tiene algún problema con esto, llévelo a @MeguSupport" ) LOGGER.exception( "Falló la importación para el chat %s con el nombre %s.", str(chat.id), str(chat.title), ) return # TODO: some of that link logic # NOTE: consider default permissions stuff? if conn: text = "Copia de seguridad completamente restaurada en *{}*.".format( chat_name) else: text = "Copia de seguridad completamente restaurada" msg.reply_text(text, parse_mode="markdown")
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( "Este es un comando solo para grupos!") 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( "Solo puedes hacer una copia de seguridad una vez al día!\nPuedes hacer una copia de seguridad de nuevo en aproximadamente `{}`" .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("MeguBot{}.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())) try: context.bot.sendMessage( MESSAGE_DUMP, "*Copia de seguridad importada con éxito:*\nChat: `{}`\nChat ID: `{}`\nEn: `{}`" .format(chat.title, chat_id, tgl), parse_mode=ParseMode.MARKDOWN, ) except BadRequest: pass context.bot.sendDocument( current_chat_id, document=open("MeguBot{}.backup".format(chat_id), "rb"), caption= "*Copia de seguridad exportada con éxito:*\nChat: `{}`\nChat ID: `{}`\nEn: `{}`\n\nNota: Este `MeguBot-Backup`fue hecho especialmente para mensajes." .format(chat.title, chat_id, tgl), timeout=360, reply_to_message_id=msg.message_id, parse_mode=ParseMode.MARKDOWN, ) os.remove("MeguBot{}.backup".format(chat_id)) # Cleaning file
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( 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, "No se pudo encontrar el sticker `{}`!".format(trigger), parse_mode="markdown") if added == 0: return if len(to_blacklist) == 1: send_message( update.effective_message, "Sticker <code>{}</code> agregado a la lista negra de stickers en <b>{}</b>!" .format(html.escape(to_blacklist[0]), chat_name), parse_mode=ParseMode.HTML) else: send_message( update.effective_message, "<code>{}</code> stickers añadidos a los stickers de la lista negra en <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 is None: send_message(update.effective_message, "El sticker no es válido!") return try: get = bot.getStickerSet(trigger) sql.add_to_stickers(chat_id, trigger.lower()) added += 1 except BadRequest: send_message( update.effective_message, "No se pudo encontrar el sticker `{}`!".format(trigger), parse_mode="markdown") if added == 0: return send_message( update.effective_message, "Sticker <code>{}</code> agregado a la lista negra de stickers en <b>{}</b>!" .format(trigger, chat_name), parse_mode=ParseMode.HTML) else: send_message(update.effective_message, "Dame los stickers que quieres agregar a la lista negra.")
def blacklist_mode(update: Update, context: CallbackContext): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] bot, args = context.bot, context.args 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, "Solo puede usar este comando en grupos, no 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 = """Parece que está intentando establecer un valor temporal en la lista negra, pero no ha determinado la hora; use `/blstickermode tban <valor de tiempo>`. Ejemplos de valores de tiempo: 4m = 4 minutos, 3h = 3 horas, 6d = 6 días, 5w = 5 semanas.""" send_message( update.effective_message, teks, parse_mode="markdown") return settypeblacklist = 'Prohibido temporalmente para {}'.format(args[1]) sql.set_blacklist_strength(chat_id, 6, str(args[1])) elif args[0].lower() == 'tmute': if len(args) == 1: teks = """Parece que está intentando establecer un valor temporal en la lista negra, pero no ha determinado la hora; use `/blstickermode tmute <valor de tiempo>`. Ejemplos de valores de tiempo: 4m = 4 minutos, 3h = 3 horas, 6d = 6 días, 5w = 5 semanas.""" send_message( update.effective_message, teks, parse_mode="markdown") return settypeblacklist = 'temporarily muted for {}'.format(args[1]) sql.set_blacklist_strength(chat_id, 7, str(args[1])) else: send_message( update.effective_message, "Solo entiendo off/del/warn/ban/kick/mute/tban/tmute!") return if conn: text = "El modo de stickers de lista negra ha cambiado, los usuarios serán `{}` a *{}*!".format( settypeblacklist, chat_name) else: text = "El modo de etiqueta de lista negra ha cambiado, los usuarios serán `{}`!".format( settypeblacklist) send_message(update.effective_message, text, parse_mode="markdown") return "<b>{}:</b>\n" \ "<b>Administrador:</b> {}\n" \ "Changed sticker blacklist mode. users will be {}.".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 = "Temporalmente prohibido para {}".format(getvalue) elif getmode == 7: settypeblacklist = "Temporalmente silenciado por {}".format(getvalue) if conn: text = "El modo de stickers de lista negra está configurado actualmente en *{}* en *{}*.".format( settypeblacklist, chat_name) else: text = "El modo de stickers de lista negra está configurado actualmente en *{}*.".format( settypeblacklist) send_message( update.effective_message, text, parse_mode=ParseMode.MARKDOWN) return ""
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( 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> eliminado de la lista negra en <b>{}</b>!" .format(html.escape(to_unblacklist[0]), chat_name), parse_mode=ParseMode.HTML) else: send_message(update.effective_message, "Este sticker no está en la lista negra...!") elif successful == len(to_unblacklist): send_message( update.effective_message, "Sticker <code>{}</code> eliminado de la lista negra en <b>{}</b>!" .format(successful, chat_name), parse_mode=ParseMode.HTML) elif not successful: send_message( update.effective_message, "Ninguna de estos stickers existe, por lo que no se pueden quitar.." .format(successful, len(to_unblacklist) - successful), parse_mode=ParseMode.HTML) else: send_message( update.effective_message, "Sticker <code>{}</code> eliminado de la lista negra. {} no existía, por lo que no se borro." .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, "El sticker no es válido!") return success = sql.rm_from_stickers(chat_id, trigger.lower()) if success: send_message( update.effective_message, "Sticker <code>{}</code> eliminado de la lista negra en <b>{}</b>!" .format(trigger, chat_name), parse_mode=ParseMode.HTML) else: send_message( update.effective_message, "{} no se encuentra en los stickers de la lista negra...!".format(trigger)) else: send_message(update.effective_message, "Dame los stickers que quieres agregar a la lista negra.")