def connected(bot: Bot, update: Update, chat, user_id, need_admin=True): user = update.effective_user if chat.type == chat.PRIVATE and sql.get_connected_chat(user_id): conn_id = sql.get_connected_chat(user_id).chat_id getstatusadmin = bot.get_chat_member( conn_id, update.effective_message.from_user.id) isadmin = getstatusadmin.status in ("administrator", "creator") ismember = getstatusadmin.status in ("member") isallow = sql.allow_connect_to_chat(conn_id) if ((isadmin) or (isallow and ismember) or (user.id in SUDO_USERS) or (user.id in DEV_USERS)): if need_admin == True: if (getstatusadmin.status in ("administrator", "creator") or user_id in SUDO_USERS or user.id in DEV_USERS): return conn_id else: send_message( update.effective_message, "Debe ser un administrador en el grupo conectado!", ) else: return conn_id else: send_message( update.effective_message, "El grupo cambió los derechos de conexión o ya no eres administrador.\nTe desconecté.", ) disconnect_chat(update, bot) else: return False
def disconnect_chat(update, context): if update.effective_chat.type == "private": disconnection_status = sql.disconnect( update.effective_message.from_user.id) if disconnection_status: sql.disconnected_chat = send_message(update.effective_message, "Desconectado del chat!") else: send_message(update.effective_message, "No estas conectado!") else: send_message(update.effective_message, "Este comando solo está disponible en PM.")
def help_connect_chat(update, context): args = context.args if update.effective_message.chat.type != "private": send_message( update.effective_message, "Hazme un privado con ese comando para obtener ayuda.", ) return else: send_message(update.effective_message, CONN_HELP, parse_mode="markdown")
def commands(update, context): chat = update.effective_chat user = update.effective_user conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "Este comando está destinado a ser utilizado en grupo, no en privado", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id text = build_curr_disabled(chat.id) send_message(update.effective_message, text, parse_mode=ParseMode.MARKDOWN)
def connection_chat(update, context): chat = update.effective_chat user = update.effective_user 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": return chat = update.effective_chat chat_name = update.effective_message.chat.title if conn: message = "Actualmente estás conectado a {}.\n".format(chat_name) else: message = "Actualmente no estás conectado en ningún grupo.\n" send_message(update.effective_message, message, parse_mode="markdown")
def welcome(update: Update, context: CallbackContext): bot = context.bot args = context.args chat = update.effective_chat if not args: pref, welcome_m, cust_content, welcome_type = sql.get_welc_pref( chat.id) send_message( update.effective_message, f"Este chat tiene su configuración de bienvenida establecida en: `{pref}`.\n", parse_mode=ParseMode.MARKDOWN, ) if welcome_type == sql.Types.BUTTON_TEXT or welcome_type == sql.Types.TEXT: buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) update.effective_message.reply_text(chat.id, welcome_m, keyboard, sql.DEFAULT_WELCOME) else: buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) ENUM_FUNC_MAP[welcome_type]( chat.id, cust_content, caption=welcome_m, reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, ) elif args[0].lower() == "noformat": pref, welcome_m, cust_content, welcome_type = sql.get_welc_pref( chat.id) send_message( update.effective_message, f"*El mensaje de bienvenida (sin llenar los* `{{}}`*) es:*", parse_mode=ParseMode.MARKDOWN, ) if welcome_type == sql.Types.BUTTON_TEXT or welcome_type == sql.Types.TEXT: buttons = sql.get_welc_buttons(chat.id) welcome_m += revert_buttons(buttons) send_message(update.effective_message, welcome_m) else: buttons = sql.get_welc_buttons(chat.id) welcome_m += revert_buttons(buttons) ENUM_FUNC_MAP[welcome_type](chat.id, cust_content, caption=welcome_m) elif len(args) >= 1: if args[0].lower() in ("on"): sql.set_welc_preference(str(chat.id), True) update.effective_message.reply_text( "Bueno! Saludaré a los miembros cuando se unan.") elif args[0].lower() in ("off"): sql.set_welc_preference(str(chat.id), False) update.effective_message.reply_text( "Ok, voy a holgazanear y no dar la bienvenida a nadie entonces." ) else: update.effective_message.reply_text("Solo entiendo 'on' y 'off'!")
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 grupos, no en privado", ) 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 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 privado", ) return "" chat = update.effective_chat chat_name = update.effective_message.chat.title res = build_lock_message(chat.id) if conn: res = res.replace("Bloqueado en", "*{}*".format(chat_name)) send_message(update.effective_message, res, parse_mode=ParseMode.MARKDOWN)
def disable(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user args = context.args 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": send_message( update.effective_message, "Este comando está destinado a ser utilizado en grupo, no en privado", ) return "" chat = update.effective_chat chat_name = update.effective_message.chat.title if len(args) >= 1: disable_cmd = args[0] if disable_cmd.startswith(CMD_STARTERS): disable_cmd = disable_cmd[1:] if disable_cmd in set(DISABLE_CMDS + DISABLE_OTHER): sql.disable_command(chat.id, disable_cmd) if conn: text = "Se deshabilitó el uso del comando `{}` en *{}*!".format( disable_cmd, chat_name) else: text = "Se deshabilitó el uso del comando `{}`!".format( disable_cmd) send_message( update.effective_message, text, parse_mode=ParseMode.MARKDOWN, ) else: send_message(update.effective_message, "Este comando no se puede deshabilitar") else: send_message(update.effective_message, "Que quieres que desactive?")
def enable(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user 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 ser utilizado en grupo, no en privado", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if len(args) >= 1: enable_cmd = args[0] if enable_cmd.startswith(CMD_STARTERS): enable_cmd = enable_cmd[1:] if sql.enable_command(chat.id, enable_cmd): if conn: text = "Se habilitó el uso del comando `{}` en *{}*!".format( enable_cmd, chat_name) else: text = "Se habilitó el uso del comando `{}`!".format( enable_cmd) send_message( update.effective_message, text, parse_mode=ParseMode.MARKDOWN, ) else: send_message(update.effective_message, "Estaba deshabilitado?") else: send_message(update.effective_message, "Que debo habilitar?")
def stop_filter(update, context): chat = update.effective_chat user = update.effective_user args = update.effective_message.text.split(None, 1) 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 len(args) < 2: send_message(update.effective_message, "Que trigger debo borrar?") return chat_filters = sql.get_chat_triggers(chat_id) if not chat_filters: send_message(update.effective_message, "No hay triggers aquí!") return for keyword in chat_filters: if keyword == args[1]: sql.remove_filter(chat_id, args[1]) send_message( update.effective_message, "Ok, dejaré de responder a ese trigger en *{}*.".format( chat_name), parse_mode=telegram.ParseMode.MARKDOWN, ) raise DispatcherHandlerStop send_message( update.effective_message, "Ese no es un trigger actual: Pon `/triggers` para ver todos los triggers activos.", parse_mode=ParseMode.MARKDOWN, )
def list_handlers(update, context): chat = update.effective_chat user = update.effective_user conn = connected(context.bot, update, chat, user.id, need_admin=False) if not conn is False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title filter_list = "*Triggers en {}:*\n" else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "Local filters" filter_list = "*Triggers Locales:*\n" else: chat_name = chat.title filter_list = "*Triggers en {}*:\n" all_handlers = sql.get_chat_triggers(chat_id) if not all_handlers: send_message( update.effective_message, "No hay triggers guardados en{}!".format(chat_name), ) return for keyword in all_handlers: entry = " • `{}`\n".format(escape_markdown(keyword)) if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH: send_message( update.effective_message, filter_list.format(chat_name), parse_mode=telegram.ParseMode.MARKDOWN, ) filter_list = entry else: filter_list += entry send_message( update.effective_message, filter_list.format(chat_name), parse_mode=telegram.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 privado", ) 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#Desbloqueo" "\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 privado", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = "Desbloqueado {} para todos!".format(ltype) can_change_info = chat.get_member( context.bot.id).can_change_info if not can_change_info: send_message( update.effective_message, "No tengo permisos para cambiar la información del grupo.", parse_mode="markdown", ) return 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#Desbloqueo" "\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?... \nPruebe `/locktypes` para ver la lista de bloqueables.", parse_mode="markdown", ) 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#BloqueoMedia" "\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 privado", ) 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#PermisoBloqueado" "\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?...\nPruebe `/locktypes` para la lista de bloqueables", parse_mode="markdown", ) 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 connect_chat(update, context): chat = update.effective_chat user = update.effective_user args = context.args if update.effective_chat.type == "private": if args and len(args) >= 1: try: connect_chat = int(args[0]) getstatusadmin = context.bot.get_chat_member( connect_chat, update.effective_message.from_user.id) except ValueError: try: connect_chat = str(args[0]) get_chat = context.bot.getChat(connect_chat) connect_chat = get_chat.id getstatusadmin = context.bot.get_chat_member( connect_chat, update.effective_message.from_user.id) except BadRequest: send_message(update.effective_message, "ID de chat no válido!") return except BadRequest: send_message(update.effective_message, "ID de chat no válido!") return isadmin = getstatusadmin.status in ("administrator", "creator") ismember = getstatusadmin.status in ("member") isallow = sql.allow_connect_to_chat(connect_chat) if (isadmin) or (isallow and ismember) or (user.id in SUDO_USERS): connection_status = sql.connect( update.effective_message.from_user.id, connect_chat) if connection_status: conn_chat = dispatcher.bot.getChat( connected(context.bot, update, chat, user.id, need_admin=False)) chat_name = conn_chat.title send_message( update.effective_message, "Conectado exitosamente a *{}*. \nUsa /helpconnect para ver los comandos disponibles." .format(chat_name), parse_mode=ParseMode.MARKDOWN, ) sql.add_history_conn(user.id, str(conn_chat.id), chat_name) else: send_message(update.effective_message, "La conexión falló!") else: send_message(update.effective_message, "No se permite la conexión a este chat!") else: gethistory = sql.get_history_conn(user.id) if gethistory: buttons = [ InlineKeyboardButton(text="❎ Cerrar", callback_data="connect_close"), InlineKeyboardButton(text="🧹 Limpiar historial", callback_data="connect_clear"), ] else: buttons = [] conn = connected(context.bot, update, chat, user.id, need_admin=False) if conn: connectedchat = dispatcher.bot.getChat(conn) text = "Actualmente estás conectado a *{}* (`{}`)".format( connectedchat.title, conn) buttons.append( InlineKeyboardButton(text="🔌 Desconectar", callback_data="connect_disconnect")) else: text = "Escriba el ID de chat o la etiqueta para conectarse!" if gethistory: text += "\n\n*Historial de conexiones:*\n" text += "╒═══「 *Info* 」\n" text += "│ Ordenado: 'Más nuevo'\n" text += "│\n" buttons = [buttons] for x in sorted(gethistory.keys(), reverse=True): htime = time.strftime("%d/%m/%Y", time.localtime(x)) text += "╞═「 *{}* 」\n│ `{}`\n│ `{}`\n".format( gethistory[x]["chat_name"], gethistory[x]["chat_id"], htime) text += "│\n" buttons.append([ InlineKeyboardButton( text=gethistory[x]["chat_name"], callback_data="connect({})".format( gethistory[x]["chat_id"]), ) ]) text += "╘══「 Total {} Chats 」".format( str(len(gethistory)) + " (max)" if len(gethistory) == 5 else str(len(gethistory))) conn_hist = InlineKeyboardMarkup(buttons) elif buttons: conn_hist = InlineKeyboardMarkup([buttons]) else: conn_hist = None send_message( update.effective_message, text, parse_mode="markdown", reply_markup=conn_hist, ) else: getstatusadmin = context.bot.get_chat_member( chat.id, update.effective_message.from_user.id) isadmin = getstatusadmin.status in ("administrator", "creator") ismember = getstatusadmin.status in ("member") isallow = sql.allow_connect_to_chat(chat.id) if (isadmin) or (isallow and ismember) or (user.id in SUDO_USERS): connection_status = sql.connect( update.effective_message.from_user.id, chat.id) if connection_status: chat_name = dispatcher.bot.getChat(chat.id).title send_message( update.effective_message, "Conectado exitosamente a *{}*.".format(chat_name), parse_mode=ParseMode.MARKDOWN, ) try: sql.add_history_conn(user.id, str(chat.id), chat_name) context.bot.send_message( update.effective_message.from_user.id, "Estas conectado a *{}*. \nUsa `/helpconnect` para ver los comandos disponibles." .format(chat_name), parse_mode="markdown", ) except BadRequest: pass except Unauthorized: pass else: send_message(update.effective_message, "La conexión falló!") else: send_message(update.effective_message, "No se permite la conexión a este chat!")
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 grupos, no en Privado", ) 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 check_flood(update, context) -> str: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] msg = update.effective_message # type: Optional[Message] if not user: # ignore channels return "" # ignore admins and whitelists if (is_user_admin(chat, user.id) or user.id in WHITELIST_USERS or user.id in FROG_USERS): sql.update_flood(chat.id, None) return "" should_ban = sql.update_flood(chat.id, user.id) if not should_ban: return "" try: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: chat.kick_member(user.id) execstrings = "Banned" tag = "Baneado." elif getmode == 2: chat.kick_member(user.id) chat.unban_member(user.id) execstrings = "Kicked" tag = "Expulsado." elif getmode == 3: context.bot.restrict_chat_member( chat.id, user.id, permissions=ChatPermissions(can_send_messages=False)) execstrings = "Muted" tag = "Muteado." elif getmode == 4: bantime = extract_time(msg, getvalue) chat.kick_member(user.id, until_date=bantime) execstrings = "Baneado por {}".format(getvalue) tag = "TBAN" elif getmode == 5: mutetime = extract_time(msg, getvalue) context.bot.restrict_chat_member( chat.id, user.id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False), ) execstrings = "Muteado por {}".format(getvalue) tag = "TMUTE" send_message( update.effective_message, "Maravilloso, me gusta dejar hacer explosiones y dejar desastres naturales pero tú, " "solo fuiste una decepción {}!".format(execstrings), ) return ("<b>{}:</b>" "\n#{}" "\n<b>Usuario:</b> {}" "\nFloodeó en el grupo.".format( html.escape(chat.title), tag, mention_html(user.id, user.first_name))) except BadRequest: msg.reply_text( "No puedo restringir a las personas aquí, dame permisos primero! Hasta entonces, desactivaré el anti-flood." ) sql.set_flood(chat.id, 0) return ( "<b>{}:</b>" "\n#Info" "\nNo tengo suficientes permisos para restringir a los usuarios, por lo que la función anti-flood se desactivará automáticamente" .format(chat.title))
def adminlist(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] args = context.args bot = context.bot if update.effective_message.chat.type == "private": send_message(update.effective_message, "Este comando sólo funciona en grupos.") return chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title try: msg = update.effective_message.reply_text( "Obteniendo administradores del grupo...", parse_mode=ParseMode.HTML) except BadRequest: msg = update.effective_message.reply_text( "Obteniendo administradores del grupo...", quote=False, parse_mode=ParseMode.HTML, ) administrators = bot.getChatAdministrators(chat_id) text = "Administradores en <b>{}</b>:".format( html.escape(update.effective_chat.title)) bot_admin_list = [] for admin in administrators: user = admin.user status = admin.status custom_title = admin.custom_title if user.first_name == "": name = "☠ Cuenta Eliminada" else: name = "{}".format( mention_html( user.id, html.escape(user.first_name + " " + (user.last_name or "")))) # if user.username: # name = escape_markdown("@" + user.username) if status == "creator": text += "\n👑 <b>Propietario:</b>" text += "\n<code> • </code>{}\n".format(name) if custom_title: text += f"<b>Apodo:</b> <code>{html.escape(custom_title)}</code>\n" text += "\n🔱 <b>Administradores:</b>" custom_admin_list = {} normal_admin_list = [] for admin in administrators: user = admin.user status = admin.status custom_title = admin.custom_title if user.first_name == "": name = "☠ Cuenta Eliminada" else: name = "{}".format( mention_html( user.id, html.escape(user.first_name + " " + (user.last_name or "")))) # if user.username: # name = escape_markdown("@" + user.username) if status == "administrator": if custom_title: try: custom_admin_list[custom_title].append(name) except KeyError: custom_admin_list.update({custom_title: [name]}) else: normal_admin_list.append(name) for admin in normal_admin_list: text += "\n<code> • </code>{}".format(admin) for admin_group in custom_admin_list.copy(): if len(custom_admin_list[admin_group]) == 1: text += "\n<code> • </code>{} | <code>{}</code>".format( custom_admin_list[admin_group][0], html.escape(admin_group)) custom_admin_list.pop(admin_group) text += "\n" for admin_group in custom_admin_list: text += "\n🚨 <code>{}</code>".format(admin_group) for admin in custom_admin_list[admin_group]: text += "\n<code> • </code>{}".format(admin) text += "\n" try: msg.edit_text(text, parse_mode=ParseMode.HTML) except BadRequest: # if original message is deleted return
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, "Proporcione la palabra clave para que este trigger responda!", ) return if msg.reply_to_message: if len(args) < 2: send_message( update.effective_message, "Proporcione la palabra clave para que este trigger responda!", ) 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, "No hay mensaje de nota: No puede SÓLO tener botones, necesita un mensaje para acompañarlo!", ) 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, "Proporcione la palabra clave para que este trigger responda!", ) 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, "No hay mensaje de nota: No puede SÓLO tener botones, necesita un mensaje para acompañarlo!", ) return else: send_message(update.effective_message, "Trigger no válido!") 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 is True: send_message( update.effective_message, "Trigger '{}' guardado en *{}*!".format(keyword, chat_name), parse_mode=telegram.ParseMode.MARKDOWN, ) raise DispatcherHandlerStop
def allow_connections(update, context) -> str: chat = update.effective_chat args = context.args if chat.type != chat.PRIVATE: if len(args) >= 1: var = args[0] if var == "no": sql.set_allow_connect_to_chat(chat.id, False) send_message( update.effective_message, "La conexión se ha inhabilitado para este chat", ) elif var == "si": sql.set_allow_connect_to_chat(chat.id, True) send_message( update.effective_message, "Se ha habilitado la conexión para este chat", ) else: send_message( update.effective_message, "Por favor escribe `si` o `no`!", parse_mode=ParseMode.MARKDOWN, ) else: get_settings = sql.allow_connect_to_chat(chat.id) if get_settings: send_message( update.effective_message, "La conexion a este grupo esta *permitida* para los miembros!", parse_mode=ParseMode.MARKDOWN, ) else: send_message( update.effective_message, "La conexión a este grupo *no está permitida* para los miembros!", parse_mode=ParseMode.MARKDOWN, ) else: send_message(update.effective_message, "Este comando es solo para grupos. No en privado!")
def del_lockables(update, context): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] for lockable, filter in LOCK_TYPES.items(): if lockable == "rtl": if sql.is_locked(chat.id, lockable) and can_delete( chat, context.bot.id): if message.caption: check = ad.detect_alphabet(u"{}".format(message.caption)) if "ARABIC" in check: try: message.delete() except BadRequest as excp: if excp.message == "Mensaje para eliminar no encontrado": pass else: LOGGER.exception("ERROR en bloqueables") break if message.text: check = ad.detect_alphabet(u"{}".format(message.text)) if "ARABIC" in check: try: message.delete() except BadRequest as excp: if excp.message == "Mensaje para eliminar no encontrado": pass else: LOGGER.exception("ERROR en bloqueables") break continue if lockable == "button": if sql.is_locked(chat.id, lockable) and can_delete( chat, context.bot.id): if message.reply_markup and message.reply_markup.inline_keyboard: try: message.delete() except BadRequest as excp: if excp.message == "Mensaje para eliminar no encontrado": pass else: LOGGER.exception("ERROR en bloqueables") break continue if lockable == "inline": if sql.is_locked(chat.id, lockable) and can_delete( chat, context.bot.id): if message and message.via_bot: try: message.delete() except BadRequest as excp: if excp.message == "Mensaje para eliminar no encontrado": pass else: LOGGER.exception("ERROR en bloqueables") break continue if (filter(update) and sql.is_locked(chat.id, lockable) and can_delete(chat, context.bot.id)): if lockable == "bots": new_members = update.effective_message.new_chat_members for new_mem in new_members: if new_mem.is_bot: if not is_bot_admin(chat, context.bot.id): send_message( update.effective_message, "Veo un bot y me han dicho que evite que se unan..." "Pero no tengo admin! :(", ) return chat.kick_member(new_mem.id) send_message( update.effective_message, "Solo los admins pueden agregar bots en este chat! Fuera de aquí.", ) break else: try: message.delete() except BadRequest as excp: if excp.message == "Mensaje para eliminar no encontrado": pass else: LOGGER.exception("ERROR en bloqueables") break
def reply_filter(update, context): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] if not update.effective_user or update.effective_user.id == 777000: return to_match = extract_text(message) if not to_match: return chat_filters = sql.get_chat_triggers(chat.id) for keyword in chat_filters: pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])" if re.search(pattern, to_match, flags=re.IGNORECASE): filt = sql.get_filter(chat.id, keyword) if filt.reply == "there is should be a new reply": buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) VALID_WELCOME_FORMATTERS = [ "first", "last", "fullname", "username", "id", "chatname", "mention", "user1", "user2", ] if filt.reply_text: valid_format = escape_invalid_curly_brackets( filt.reply_text, VALID_WELCOME_FORMATTERS) if valid_format: filtext = valid_format.format( first=escape(message.from_user.first_name), last=escape(message.from_user.last_name or message.from_user.first_name), fullname=" ".join( [ escape(message.from_user.first_name), escape(message.from_user.last_name), ] if message.from_user.last_name else [escape(message.from_user.first_name)]), username="******" + escape(message.from_user.username) if message.from_user.username else mention_html( message.from_user.id, message.from_user.first_name), mention=mention_html(message.from_user.id, message.from_user.first_name), chatname=escape(message.chat.title) if message.chat.type != "private" else escape( message.from_user.first_name), id=message.from_user.id, ) else: filtext = "" else: filtext = "" if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): try: context.bot.send_message( chat.id, markdown_to_html(filtext), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: error_catch = get_exception(excp, filt, chat) if error_catch == "noreply": try: context.bot.send_message( chat.id, markdown_to_html(filtext), parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) send_message( update.effective_message, get_exception(excp, filt, chat), ) else: try: send_message( update.effective_message, get_exception(excp, filt, chat), ) except BadRequest as excp: LOGGER.exception("Failed to send message: " + excp.message) pass else: if ENUM_FUNC_MAP[ filt.file_type] == dispatcher.bot.send_sticker: ENUM_FUNC_MAP[filt.file_type]( chat.id, filt.file_id, reply_to_message_id=message.message_id, reply_markup=keyboard, ) else: ENUM_FUNC_MAP[filt.file_type]( chat.id, filt.file_id, caption=markdown_to_html(filtext), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML, reply_markup=keyboard, ) break else: if filt.is_sticker: message.reply_sticker(filt.reply) elif filt.is_document: message.reply_document(filt.reply) elif filt.is_image: message.reply_photo(filt.reply) elif filt.is_audio: message.reply_audio(filt.reply) elif filt.is_voice: message.reply_voice(filt.reply) elif filt.is_video: message.reply_video(filt.reply) elif filt.has_markdown: buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) try: send_message( update.effective_message, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: if excp.message == "Protocolo de URL no admitido": try: send_message( update.effective_message, "Parece que intentas utilizar un protocolo de URL no compatible. Telegram " "no admite botones para algunos protocolos, como tg://. Por favor, inténtalo " f"de nuevo, o pregunta en {SUPPORT_CHAT} por ayuda.", ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass elif excp.message == "Reply message not found": try: context.bot.send_message( chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass else: try: send_message( update.effective_message, "Este mensaje no se pudo enviar porque tiene un formato incorrecto.", ) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass LOGGER.warning("Message %s could not be parsed", str(filt.reply)) LOGGER.exception( "Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id), ) else: # LEGACY - all new filters will have has_markdown set to True. try: send_message(update.effective_message, filt.reply) except BadRequest as excp: LOGGER.exception("Error in filters: " + excp.message) pass break
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 grupos, no en privado", ) 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#ConfigFlood" "\n<b>Administrador:</b> {}" "\nDesactivó 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#ConfigFlood" "\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 ""