コード例 #1
0
def enforce_gban(update: Update, context: CallbackContext):
    # Not using @restrict handler to avoid spamming - just ignore if cant gban.
    bot = context.bot
    try:
        restrict_permission = update.effective_chat.get_member(
            bot.id).can_restrict_members
    except Unauthorized:
        return
    if sql.does_chat_gban(update.effective_chat.id) and restrict_permission:
        user = update.effective_user
        chat = update.effective_chat
        msg = update.effective_message

        if user and not is_user_admin(chat, user.id):
            check_and_ban(update, user.id)
            return

        if msg.new_chat_members:
            new_members = update.effective_message.new_chat_members
            for mem in new_members:
                check_and_ban(update, mem.id)

        if msg.reply_to_message:
            user = msg.reply_to_message.from_user
            if user and not is_user_admin(chat, user.id):
                check_and_ban(update, user.id, should_message=False)
コード例 #2
0
ファイル: muting.py プロジェクト: kxrumi/MeguRobot
def check_user(user_id: int, bot: Bot, chat: Chat) -> Optional[str]:
    if not user_id:
        reply = (
            "No parece que se refiera a un usuario o el ID especificado es incorrecto.."
        )
        return reply

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "Usuario no encontrado":
            reply = "Parece que no puedo encontrar a este usuario"
            return reply
        else:
            raise

    if user_id == bot.id:
        reply = "No me voy a silenciar, que tan alto estas?"
        return reply

    if is_user_admin(chat, user_id, member) or user_id in FROG_USERS:
        reply = """Realmente desearía poder silenciar a los administradores... Quizás un "explosion"?"""
        return reply

    return None
コード例 #3
0
def get_settings(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]

    # ONLY send settings in PM
    if chat.type != chat.PRIVATE:
        if is_user_admin(chat, user.id):
            text = "Haga clic aquí para obtener la configuración de este chat."
            msg.reply_text(
                text,
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton(
                                text="Configuración",
                                url="t.me/{}?start=stngs_{}".format(
                                    context.bot.username, chat.id
                                ),
                            )
                        ]
                    ]
                ),
            )
        else:
            text = "Haga clic aquí para cambiar la configuración."

    else:
        send_settings(chat.id, user.id, True)
コード例 #4
0
def slap(update: Update, context: CallbackContext):
    bot, args = context.bot, context.args
    message = update.effective_message
    chat = update.effective_chat

    reply_text = (message.reply_to_message.reply_text
                  if message.reply_to_message else message.reply_text)

    curr_user = html.escape(message.from_user.first_name)
    user_id = extract_user(message, args)

    if user_id == bot.id:
        temp = random.choice(fun_strings.SLAP_MEGU_TEMPLATES)

        if isinstance(temp, list):
            if temp[2] == "tmute":
                if is_user_admin(chat, message.from_user.id):
                    reply_text(temp[1])
                    return

                mutetime = int(time.time() + 60)
                bot.restrict_chat_member(
                    chat.id,
                    message.from_user.id,
                    until_date=mutetime,
                    permissions=ChatPermissions(can_send_messages=False),
                )
            reply_text(temp[0])
        else:
            reply_text(temp)
        return

    if user_id:

        slapped_user = bot.get_chat(user_id)
        user1 = curr_user
        user2 = html.escape(slapped_user.first_name)

    else:
        user1 = bot.first_name
        user2 = curr_user

    temp = random.choice(fun_strings.SLAP_TEMPLATES)
    item = random.choice(fun_strings.ITEMS)
    hit = random.choice(fun_strings.HIT)
    throw = random.choice(fun_strings.THROW)

    reply = temp.format(user1=user1,
                        user2=user2,
                        item=item,
                        hits=hit,
                        throws=throw)

    reply_text(reply, parse_mode=ParseMode.HTML)
コード例 #5
0
ファイル: bans.py プロジェクト: kxrumi/MeguRobot
def exploitme(update: Update, context: CallbackContext):
    user_id = update.effective_message.from_user.id
    if is_user_admin(update.effective_chat, user_id):
        update.effective_message.reply_text(
            "Desearía poder hacerlo... pero eres un admin.")
        return

    res = update.effective_chat.unban_member(
        user_id)  # unban on current user = kick
    if res:
        update.effective_message.reply_text("*Lo hace volar del grupo*")
    else:
        update.effective_message.reply_text("¿Eh? No puedo :/")
コード例 #6
0
ファイル: disable.py プロジェクト: kxrumi/MeguRobot
        def check_update(self, update):
            if isinstance(update, Update) and update.effective_message:
                message = update.effective_message

                if message.text and len(message.text) > 1:
                    fst_word = message.text.split(None, 1)[0]
                    if len(fst_word) > 1 and any(
                            fst_word.startswith(start)
                            for start in CMD_STARTERS):
                        args = message.text.split()[1:]
                        command = fst_word[1:].split("@")
                        command.append(message.bot.username)

                        if not (command[0].lower() in self.command
                                and command[1].lower()
                                == message.bot.username.lower()):
                            return None

                        filter_result = self.filters(update)
                        if filter_result:
                            chat = update.effective_chat
                            user = update.effective_user
                            # disabled, admincmd, user admin
                            if sql.is_command_disabled(chat.id,
                                                       command[0].lower()):
                                # check if command was disabled
                                is_disabled = command[
                                    0] in ADMIN_CMDS and is_user_admin(
                                        chat, user.id)
                                if not is_disabled:
                                    return None
                                else:
                                    return args, filter_result

                            return args, filter_result
                        else:
                            return False
コード例 #7
0
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 ""
コード例 #8
0
def warn(user: User,
         chat: Chat,
         reason: str,
         message: Message,
         warner: User = None) -> str:
    if is_user_admin(chat, user.id):
        # message.reply_text("Damn admins, They are too far to be One Punched!")
        return

    if user.id in FROG_USERS:
        if warner:
            message.reply_text("Las 'Ranas' no pueden ser advertidos.")
        else:
            message.reply_text(
                "El usuario es una 'Rana'\nNo puedo advertir a estos usuarios, pero deben evitar abusar de esto."
            )
        return

    if user.id in WHITELIST_USERS:
        if warner:
            message.reply_text("Los 'Sapos' no pueden ser advertidos.")
        else:
            message.reply_text(
                "El usuario es una 'Rana'\nNo puedo advertir a estos usuarios, pero deben evitar abusar de esto."
            )
        return

    if warner:
        warner_tag = mention_html(warner.id, warner.first_name)
    else:
        warner_tag = "Filtro de advertencia automatizado."

    limit, soft_warn = sql.get_warn_setting(chat.id)
    num_warns, reasons = sql.warn_user(user.id, chat.id, reason)
    if num_warns >= limit:
        sql.reset_warns(user.id, chat.id)
        if soft_warn:  # punch
            chat.unban_member(user.id)
            reply = (
                f"<code>💥</code> <b>Kickeo</b>\n"
                f" <b>• Usuario:</b> {mention_html(user.id, user.first_name)}\n"
                f" <b>• Advertencias:</b> {limit}")

        else:  # ban
            chat.kick_member(user.id)
            reply = (
                f"<code>💥</code><b>Baneo</b>\n"
                f" <b>• Usuario:</b> {mention_html(user.id, user.first_name)}\n"
                f" <b>• Advertencias:</b> {limit}")

        for warn_reason in reasons:
            reply += f"\n - {html.escape(warn_reason)}"

        # message.bot.send_sticker(chat.id, BAN_STICKER)  # Saitama's sticker
        keyboard = None
        log_reason = (
            f"<b>{html.escape(chat.title)}:</b>\n"
            f"#AdvertenciaBan\n"
            f"<b>Administrador:</b> {warner_tag}\n"
            f"<b>Usuario:</b> {mention_html(user.id, user.first_name)}\n"
            f"<b>Razón:</b> {reason}\n"
            f"<b>Advertencias:</b> <code>{num_warns}/{limit}</code>")

    else:
        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton(
                "✖ Quitar Advertencia",
                callback_data="rm_warn({})".format(user.id),
            )
        ]])

        reply = (
            f"<code>💥</code><b>Advertencia</b>\n"
            f"<code> </code><b>• Usuario:</b> {mention_html(user.id, user.first_name)}\n"
            f"<code> </code><b>• Advertencias:</b> {num_warns}/{limit}")
        if reason:
            reply += f"\n<code> </code><b>•  Razón:</b> {html.escape(reason)}"

        log_reason = (
            f"<b>{html.escape(chat.title)}:</b>\n"
            f"#Advertencia\n"
            f"<b>Administrador:</b> {warner_tag}\n"
            f"<b>Usuario:</b> {mention_html(user.id, user.first_name)}\n"
            f"<b>Razón:</b> {reason}\n"
            f"<b>Advertencias:</b> <code>{num_warns}/{limit}</code>")

    try:
        message.reply_text(reply,
                           reply_markup=keyboard,
                           parse_mode=ParseMode.HTML)
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(reply,
                               reply_markup=keyboard,
                               parse_mode=ParseMode.HTML,
                               quote=False)
        else:
            raise
    return log_reason
コード例 #9
0
ファイル: antiflood.py プロジェクト: kxrumi/MeguRobot
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))
コード例 #10
0
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split("_", 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id,
                    HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(text="Atrás",
                                             callback_data="help_back")
                    ]]),
                )
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "adventurers":
                IMPORTED["extras"].send_adventurers(update)
            elif args[0].lower() == "welcomehelp":
                IMPORTED["saludos"].welcome_help_sender(update)
            elif args[0].lower() == "welcomemutehelp":
                IMPORTED["saludos"].welcome_mute_help_sender(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "reglas" in IMPORTED:
                IMPORTED["reglas"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_text(
                PM_START_TEXT.format(
                    escape_markdown(first_name),
                    escape_markdown(context.bot.first_name),
                    MEGU_IMG,
                ),
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=False,
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(
                            text="Añadir a Megu",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username),
                        )
                    ],
                    [
                        InlineKeyboardButton(
                            text="Grupo de Soporte",
                            url=f"https://t.me/{SUPPORT_CHAT}",
                        ),
                        InlineKeyboardButton(text="❔ Ayuda",
                                             callback_data="help_back"),
                    ],
                    [
                        InlineKeyboardButton(
                            text="🗄 Código Fuente",
                            url="https://github.com/NachABR/MeguRobot",
                        )
                    ],
                ]),
            )
    else:
        update.effective_message.reply_text(
            "<b>Estoy Online!</b>\n<b>Desde:</b> <code>{}</code>".format(
                uptime),
            parse_mode=ParseMode.HTML,
        )