def check_and_ban(update, user_id, should_message=True):
    chat = update.effective_chat
    message = update.effective_message
    try:
        sw_ban = sw.get_ban(int(user_id))
    except AttributeError:
        sw_ban = None

    if sw_ban:
        chat.kick_member(user_id)
        if should_message:
            chat.send_message(
                f"<b>Alerta:</b>\n"
                f"Este usuario está baneado a nivel global.\n"
                f"<b>Chat de apelación</b>: @SpamWatchSupport\n"
                f"<b>ID</b>: <code>{sw_ban.id}</code>\n"
                f"<b>Razón</b>: <code>{html.escape(sw_ban.reason)}</code>",
                parse_mode=ParseMode.HTML,
            )
        return

    if sql.is_user_gbanned(user_id):
        chat.kick_member(user_id)
        if should_message:
            text = (f"<b>Alerta</b>:\n"
                    f"Este usuario está baneado a nivel global.\n"
                    f"<b>Chat de apelación</b>: @{SUPPORT_CHAT}\n"
                    f"<b>ID de usuario</b>: <code>{user_id}</code>")
            user = sql.get_gbanned_user(user_id)
            if user.reason:
                text += f"\n<b>Razón:</b> <code>{html.escape(user.reason)}</code>"
            chat.send_message(text, parse_mode=ParseMode.HTML)
Example #2
0
def hpmanager(user):
    total_hp = (get_user_num_chats(user.id) + 10) * 10

    if not is_user_gbanned(user.id):

        # Assign new var `new_hp` since we need `total_hp` in
        # end to calculate percentage.
        new_hp = total_hp

        # if no username decrease 25% of hp.
        if not user.username:
            new_hp -= no_by_per(total_hp, 25)
        try:
            dispatcher.bot.get_user_profile_photos(user.id).photos[0][-1]
        except IndexError:
            # no profile photo ==> -25% of hp
            new_hp -= no_by_per(total_hp, 25)
        # if no /setme exist ==> -20% of hp
        if not sql.get_user_me_info(user.id):
            new_hp -= no_by_per(total_hp, 20)
        # if no bio exsit ==> -10% of hp
        if not sql.get_user_bio(user.id):
            new_hp -= no_by_per(total_hp, 10)

        if is_afk(user.id):
            afkst = check_afk_status(user.id)
            # if user is afk and no reason then decrease 7%
            # else if reason exist decrease 5%
            if not afkst.reason:
                new_hp -= no_by_per(total_hp, 7)
            else:
                new_hp -= no_by_per(total_hp, 5)

        # fbanned users will have (2*number of fbans) less from max HP
        # Example: if HP is 100 but user has 5 diff fbans
        # Available HP is (2*5) = 10% less than Max HP
        # So.. 10% of 100HP = 90HP

        _, fbanlist = get_user_fbanlist(user.id)
        new_hp -= no_by_per(total_hp, 2 * len(fbanlist))

    # Bad status effects:
    # gbanned users will always have 5% HP from max HP
    # Example: If HP is 100 but gbanned
    # Available HP is 5% of 100 = 5HP

    else:
        new_hp = no_by_per(total_hp, 5)

    return {
        "earnedhp": int(new_hp),
        "totalhp": int(total_hp),
        "percentage": get_percentage(total_hp, new_hp),
    }
def __user_info__(user_id):
    is_gbanned = sql.is_user_gbanned(user_id)

    text = "<b>Baneado globalmente:</b> <code>{}</code>"
    if user_id in [777000, 1087968824]:
        return ""
    if user_id == dispatcher.bot.id:
        return ""
    if int(user_id) in SUDO_USERS + FROG_USERS + WHITELIST_USERS:
        return ""
    if is_gbanned:
        text = text.format("Si")
        user = sql.get_gbanned_user(user_id)
        if user.reason:
            text += f"\n<b>Razón:</b> <code>{html.escape(user.reason)}</code>"
        text += f"\n<b>Chat de apelación:</b> @{SUPPORT_CHAT}"
    else:
        text = text.format("No")
    return text
Example #4
0
def left_member(update: Update, context: CallbackContext):
    bot = context.bot
    chat = update.effective_chat
    user = update.effective_user
    should_goodbye, cust_goodbye, goodbye_type = sql.get_gdbye_pref(chat.id)

    if user.id == bot.id:
        return

    if should_goodbye:
        reply = update.message.message_id
        cleanserv = sql.clean_service(chat.id)
        # Clean service welcome
        if cleanserv:
            try:
                dispatcher.bot.delete_message(chat.id,
                                              update.message.message_id)
            except BadRequest:
                pass
            reply = False

        left_mem = update.effective_message.left_chat_member
        if left_mem:

            # Thingy for spamwatched users
            if sw != None:
                sw_ban = sw.get_ban(left_mem.id)
                if sw_ban:
                    return

            # Dont say goodbyes to gbanned users
            if is_user_gbanned(left_mem.id):
                return

            # Ignore bot being kicked
            if left_mem.id == bot.id:
                return

            # Give the owner a special goodbye
            if left_mem.id == OWNER_ID:
                update.effective_message.reply_text("Oh! Kazuma! Salió...",
                                                    reply_to_message_id=reply)
                return

            # Give the devs a special goodbye
            elif left_mem.id in DEV_USERS:
                update.effective_message.reply_text(
                    "Nos vemos luego ^^!",
                    reply_to_message_id=reply,
                )
                return

            # if media goodbye, use appropriate function for it
            if goodbye_type != sql.Types.TEXT and goodbye_type != sql.Types.BUTTON_TEXT:
                ENUM_FUNC_MAP[goodbye_type](chat.id, cust_goodbye)
                return

            first_name = (left_mem.first_name or "PersonaSinNombre"
                          )  # edge case of empty name - occurs for some bugs.
            if cust_goodbye:
                if cust_goodbye == sql.DEFAULT_GOODBYE:
                    cust_goodbye = random.choice(
                        sql.DEFAULT_GOODBYE_MESSAGES).format(
                            first=escape_markdown(first_name))
                if left_mem.last_name:
                    fullname = escape_markdown(
                        f"{first_name} {left_mem.last_name}")
                else:
                    fullname = escape_markdown(first_name)
                count = chat.get_members_count()
                mention = mention_markdown(left_mem.id, first_name)
                if left_mem.username:
                    username = "******" + escape_markdown(left_mem.username)
                else:
                    username = mention

                valid_format = escape_invalid_curly_brackets(
                    cust_goodbye, VALID_WELCOME_FORMATTERS)
                res = valid_format.format(
                    first=escape_markdown(first_name),
                    last=escape_markdown(left_mem.last_name or first_name),
                    fullname=escape_markdown(fullname),
                    username=username,
                    mention=mention,
                    count=count,
                    chatname=escape_markdown(chat.title),
                    id=left_mem.id,
                )
                buttons = sql.get_gdbye_buttons(chat.id)
                keyb = build_keyboard(buttons)

            else:
                res = random.choice(
                    sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name)
                keyb = []

            keyboard = InlineKeyboardMarkup(keyb)

            send(
                update,
                res,
                keyboard,
                random.choice(
                    sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name),
            )
def gban(update: Update, context: CallbackContext):
    bot, args = context.bot, context.args
    message = update.effective_message
    user = update.effective_user
    chat = update.effective_chat
    log_message = ""

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            "No parece que se refiera a un usuario o el ID especificado es incorrecto."
        )
        return

    if int(user_id) in DEV_USERS:
        message.reply_text(
            "Este usuario es un Demonio Carmesí\nNo puedo actuar en contra de ellos."
        )
        return

    if int(user_id) in SUDO_USERS:
        message.reply_text(
            "Espío, con mi ojito... un destroyer! Por qué se están volviendo el uno contra el otro?"
        )
        return

    if int(user_id) in SUPPORT_USERS:
        message.reply_text(
            "¡Oooh, alguien está intentando superar a un Demonio! *agarra palomitas de maíz*"
        )
        return

    if int(user_id) in FROG_USERS:
        message.reply_text("¡Es una rana! No puede ser baneado!")
        return

    if int(user_id) in WHITELIST_USERS:
        message.reply_text("¡Es un sapo! No puede ser baneado!")
        return

    if user_id == bot.id:
        message.reply_text("Tu uhh... quieres que me salga?")
        return
    if user_id in [777000, 1087968824]:
        message.reply_text(
            "Baka! No puedes hacer explotar la tecnología nativa de Telegram!")
        return

    try:
        user_chat = bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text("Parece que no puedo encontrar a este usuario.")
            return ""
        else:
            return

    if user_chat.type != "private":
        message.reply_text("Eso no es un usuario!")
        return

    if sql.is_user_gbanned(user_id):

        if not reason:
            message.reply_text(
                "Este usuario ya está baneado globalmente. \nCambiaría el motivo, pero no me has dado uno..."
            )
            return

        old_reason = sql.update_gban_reason(
            user_id, user_chat.username or user_chat.first_name, reason)
        if old_reason:
            message.reply_text(
                "Este usuario ya está baneado globalmente por la siguiente razón:\n"
                "<code>{}</code>\n"
                "Lo he actualizado con tu nueva razón!".format(
                    html.escape(old_reason)),
                parse_mode=ParseMode.HTML,
            )

        else:
            message.reply_text(
                "Este usuario ya está baneado globalmente, pero no se ha establecido ningún motivo; Lo he actualizado!"
            )

        return

    message.reply_text("En eso!")

    start_time = time.time()
    datetime_fmt = "%Y-%m-%dT%H:%M"
    current_time = datetime.utcnow().strftime(datetime_fmt)

    if chat.type != "private":
        chat_origin = "<b>{} ({})</b>\n".format(html.escape(chat.title),
                                                chat.id)
    else:
        chat_origin = "<b>{}</b>\n".format(chat.id)

    log_message = (
        f"#BaneoGlobal\n"
        f"<b>Originado desde:</b> <code>{chat_origin}</code>\n"
        f"<b>Administrador:</b> {mention_html(user.id, user.first_name)}\n"
        f"<b>Usuario baneado:</b> {mention_html(user_chat.id, user_chat.first_name)}\n"
        f"<b>ID del usuario baneado:</b> <code>{user_chat.id}</code>\n"
        f"<b>Evento Registrado:</b> <code>{current_time}</code>")

    if reason:
        if chat.type == chat.SUPERGROUP and chat.username:
            log_message += f'\n<b>Razón:</b> <a href="https://telegram.me/{chat.username}/{message.message_id}">{reason}</a>'
        else:
            log_message += f"\n<b>Razón:</b> <code>{reason}</code>"

    if GLOBAL_LOGS:
        try:
            log = bot.send_message(GLOBAL_LOGS,
                                   log_message,
                                   parse_mode=ParseMode.HTML)
        except BadRequest as excp:
            log = bot.send_message(
                GLOBAL_LOGS,
                log_message +
                "\n\nEl formateo se ha deshabilitado debido a un error inesperado.",
            )

    else:
        send_to_list(bot, SUDO_USERS + SUPPORT_USERS, log_message, html=True)

    sql.gban_user(user_id, user_chat.username or user_chat.first_name, reason)

    chats = get_user_com_chats(user_id)
    gbanned_chats = 0

    for chat in chats:
        chat_id = int(chat)

        # Check if this group has disabled gbans
        if not sql.does_chat_gban(chat_id):
            continue

        try:
            bot.kick_chat_member(chat_id, user_id)
            gbanned_chats += 1

        except BadRequest as excp:
            if excp.message in GBAN_ERRORS:
                pass
            else:
                message.reply_text(
                    f"No se pudo banear globalmente debido a: {excp.message}")
                if GLOBAL_LOGS:
                    bot.send_message(
                        GLOBAL_LOGS,
                        f"No se pudo banear globalmente debido a: {excp.message}",
                        parse_mode=ParseMode.HTML,
                    )
                else:
                    send_to_list(
                        bot,
                        SUDO_USERS + SUPPORT_USERS,
                        f"No se pudo banear globalmente debido a: {excp.message}",
                    )
                sql.ungban_user(user_id)
                return
        except TelegramError:
            pass

    if GLOBAL_LOGS:
        log.edit_text(
            log_message +
            f"\n<b>Chats afectados:</b> <code>{gbanned_chats}</code>",
            parse_mode=ParseMode.HTML,
        )
    else:
        send_to_list(
            bot,
            SUDO_USERS + SUPPORT_USERS,
            f"Gban completo! (Usuario baneado en <code>{gbanned_chats}</code> chats)",
            html=True,
        )

    end_time = time.time()
    gban_time = round((end_time - start_time), 2)

    if gban_time > 60:
        gban_time = round((gban_time / 60), 2)
        message.reply_text("Hecho! baneado globalmente.",
                           parse_mode=ParseMode.HTML)
    else:
        message.reply_text("Hecho! baneado globalmente.",
                           parse_mode=ParseMode.HTML)

    try:
        bot.send_message(
            user_id,
            "Ha sido expulsado globalmente de todos los grupos en los que tengo permisos administrativos."
            " Para ver el motivo haga clic en /info."
            f" Si cree que se trata de un error, puede apelar su prohibición aquí: @{SUPPORT_CHAT}",
            parse_mode=ParseMode.HTML,
        )
    except:
        pass  # bot probably blocked by user
def ungban(update: Update, context: CallbackContext):
    bot, args = context.bot, context.args
    message = update.effective_message
    user = update.effective_user
    chat = update.effective_chat
    log_message = ""

    user_id = extract_user(message, args)

    if not user_id:
        message.reply_text(
            "No parece que se refiera a un usuario o el ID especificado es incorrecto."
        )
        return

    user_chat = bot.get_chat(user_id)
    if user_chat.type != "private":
        message.reply_text("Eso no es un usuario!")
        return

    if not sql.is_user_gbanned(user_id):
        message.reply_text("Este usuario no está globalmente baneado!")
        return

    message.reply_text(
        f"Le daré a {user_chat.first_name} una segunda oportunidad, a nivel global."
    )

    start_time = time.time()
    datetime_fmt = "%Y-%m-%dT%H:%M"
    current_time = datetime.utcnow().strftime(datetime_fmt)

    if chat.type != "private":
        chat_origin = f"<b>{html.escape(chat.title)} ({chat.id})</b>\n"
    else:
        chat_origin = f"<b>{chat.id}</b>\n"

    log_message = (
        f"#DesbaneoGlobal\n"
        f"<b>Originado desde:</b> <code>{chat_origin}</code>\n"
        f"<b>Administrador:</b> {mention_html(user.id, user.first_name)}\n"
        f"<b>Usuario desbaneado:</b> {mention_html(user_chat.id, user_chat.first_name)}\n"
        f"<b>ID de Usuario desbaneado:</b> <code>{user_chat.id}</code>\n"
        f"<b>Evento Registrado:</b> <code>{current_time}</code>")

    if GLOBAL_LOGS:
        try:
            log = bot.send_message(GLOBAL_LOGS,
                                   log_message,
                                   parse_mode=ParseMode.HTML)
        except BadRequest as excp:
            log = bot.send_message(
                GLOBAL_LOGS,
                log_message +
                "\n\nEl formateo se ha deshabilitado debido a un error inesperado.",
            )
    else:
        send_to_list(bot, SUDO_USERS + SUPPORT_USERS, log_message, html=True)

    chats = get_all_chats()
    ungbanned_chats = 0

    for chat in chats:
        chat_id = chat.chat_id

        # Check if this group has disabled gbans
        if not sql.does_chat_gban(chat_id):
            continue

        try:
            member = bot.get_chat_member(chat_id, user_id)
            if member.status == "kicked":
                bot.unban_chat_member(chat_id, user_id)
                ungbanned_chats += 1

        except BadRequest as excp:
            if excp.message in UNGBAN_ERRORS:
                pass
            else:
                message.reply_text(
                    f"No se pudo cancelar el desbaneo global debido a: {excp.message}"
                )
                if GLOBAL_LOGS:
                    bot.send_message(
                        GLOBAL_LOGS,
                        f"No se pudo cancelar el desbaneo global debido a: {excp.message}",
                        parse_mode=ParseMode.HTML,
                    )
                else:
                    bot.send_message(
                        OWNER_ID,
                        f"No se pudo cancelar el desbaneo global debido a: {excp.message}",
                    )
                return
        except TelegramError:
            pass

    sql.ungban_user(user_id)

    if GLOBAL_LOGS:
        log.edit_text(
            log_message + f"\n<b>Chats afectados:</b> {ungbanned_chats}",
            parse_mode=ParseMode.HTML,
        )
    else:
        send_to_list(bot, SUDO_USERS + SUPPORT_USERS,
                     "Desbaneo global completado!")

    end_time = time.time()
    ungban_time = round((end_time - start_time), 2)

    if ungban_time > 60:
        ungban_time = round((ungban_time / 60), 2)
        message.reply_text(
            f"La persona ha sido desbaneada globalmente. Tomó {ungban_time} minuto's"
        )
    else:
        message.reply_text(
            f"La persona ha sido desbaneada globalmente. Tomó {ungban_time} minuto's"
        )