Exemplo n.º 1
0
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'!")
Exemplo n.º 2
0
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!\nPodrás 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(user.id, 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("MeguRobot{}.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(
            JOIN_LOGGER,
            "*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("MeguRobot{}.backup".format(chat_id), "rb"),
        caption=
        "*Copia de seguridad exportada con éxito:*\nChat: `{}`\nChat ID: `{}`\nEn: `{}`\n\nNota: Este `MeguRobot-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("MeguRobot{}.backup".format(chat_id))  # Cleaning file
Exemplo n.º 3
0
def new_member(update: Update, context: CallbackContext):
    bot, job_queue = context.bot, context.job_queue
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_message

    should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref(
        chat.id)
    welc_mutes = sql.welcome_mutes(chat.id)
    human_checks = sql.get_human_checks(user.id, chat.id)

    new_members = update.effective_message.new_chat_members

    for new_mem in new_members:

        welcome_log = None
        res = None
        sent = None
        should_mute = True
        welcome_bool = True
        media_wel = False

        if sw != None:
            sw_ban = sw.get_ban(new_mem.id)
            if sw_ban:
                return

        if should_welc:

            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

            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text(
                    "Oh, ¿que haces aquí Kazuma?.", reply_to_message_id=reply)
                welcome_log = (
                    f"{html.escape(chat.title)}\n"
                    f"#EntradaUsuario\n"
                    f"El propietario del bot acaba de unirse al chat!")
                continue

            # Welcome Devs
            elif new_mem.id in DEV_USERS:
                update.effective_message.reply_text(
                    "Un *Demonio Carmesí* acaba de unirse!",
                    reply_to_message_id=reply,
                    parse_mode=ParseMode.MARKDOWN,
                )
                continue

            # Welcome Sudos
            elif new_mem.id in SUDO_USERS:
                update.effective_message.reply_text(
                    "Eh! ¡Un *Destroyer* acaba de unirse!",
                    reply_to_message_id=reply,
                    parse_mode=ParseMode.MARKDOWN,
                )
                continue

            # Welcome Support
            elif new_mem.id in SUPPORT_USERS:
                update.effective_message.reply_text(
                    "Eh! Un *Demonio* acaba de unirse!",
                    reply_to_message_id=reply,
                    parse_mode=ParseMode.MARKDOWN,
                )
                continue

            # Welcome Whitelisted
            elif new_mem.id in FROG_USERS:
                update.effective_message.reply_text(
                    "Uf! Una *Rana* acaba de unirse!",
                    reply_to_message_id=reply,
                    parse_mode=ParseMode.MARKDOWN,
                )
                continue

            # Welcome Frogs
            elif new_mem.id in WHITELIST_USERS:
                update.effective_message.reply_text(
                    "Uf! Un *Sapo* acaba de unirse!",
                    reply_to_message_id=reply,
                    parse_mode=ParseMode.MARKDOWN,
                )
                continue

            # Welcome yourself
            elif new_mem.id == bot.id:
                if sql.group_is_bl(chat.id):
                    msg.reply_text("Este grupo está en la lista negra.",
                                   reply_to_message_id=reply)
                    chat.leave()
                    continue

                else:
                    update.effective_message.reply_text(
                        "Hola! gracias por añadirme al grupo! :3",
                        reply_to_message_id=reply)
                    bot.send_message(
                        JOIN_LOGGER,
                        "#NuevoGrupo\n<b>Nombre del grupo:</b> {}\n<b>ID:</b> <pre>{}</pre>"
                        .format(chat.title, chat.id),
                        parse_mode=ParseMode.HTML,
                    )
                    continue

            else:
                buttons = sql.get_welc_buttons(chat.id)
                keyb = build_keyboard(buttons)

                if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT):
                    media_wel = True

                first_name = (
                    new_mem.first_name or "PersonaSinNombre"
                )  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if cust_welcome == sql.DEFAULT_WELCOME:
                        cust_welcome = random.choice(
                            sql.DEFAULT_WELCOME_MESSAGES).format(
                                first=escape_markdown(first_name))

                    if new_mem.last_name:
                        fullname = escape_markdown(
                            f"{first_name} {new_mem.last_name}")
                    else:
                        fullname = escape_markdown(first_name)
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id,
                                               escape_markdown(first_name))
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(
                        cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(
                        first=escape_markdown(first_name),
                        last=escape_markdown(new_mem.last_name or first_name),
                        fullname=escape_markdown(fullname),
                        username=username,
                        mention=mention,
                        count=count,
                        chatname=escape_markdown(chat.title),
                        id=new_mem.id,
                    )

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

                backup_message = random.choice(
                    sql.DEFAULT_WELCOME_MESSAGES).format(
                        first=escape_markdown(first_name))
                keyboard = InlineKeyboardMarkup(keyb)

        else:
            welcome_bool = False
            res = None
            keyboard = None
            backup_message = None
            reply = None

        # User exceptions from welcomemutes
        if (is_user_ban_protected(chat, new_mem.id, chat.get_member(
                new_mem.id)) or human_checks):
            should_mute = False
        # Join welcome: soft mute
        if new_mem.is_bot:
            should_mute = False

        if user.id == new_mem.id:
            if should_mute:
                if welc_mutes == "soft":
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=True,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_add_web_page_previews=False,
                        ),
                        until_date=(int(time.time() + 24 * 60 * 60)),
                    )
                if welc_mutes == "strong":
                    welcome_bool = False
                    if not media_wel:
                        VERIFIED_USER_WAITLIST.update({
                            new_mem.id: {
                                "should_welc": should_welc,
                                "media_wel": False,
                                "status": False,
                                "update": update,
                                "res": res,
                                "keyboard": keyboard,
                                "backup_message": backup_message,
                            }
                        })
                    else:
                        VERIFIED_USER_WAITLIST.update({
                            new_mem.id: {
                                "should_welc": should_welc,
                                "chat_id": chat.id,
                                "status": False,
                                "media_wel": True,
                                "cust_content": cust_content,
                                "welc_type": welc_type,
                                "res": res,
                                "keyboard": keyboard,
                            }
                        })
                    new_join_mem = f"[{escape_markdown(new_mem.first_name)}](tg://user?id={user.id})"
                    message = msg.reply_text(
                        f"{new_join_mem}, Haz clic en el botón de abajo para demostrar que no eres un robot.\nTienes 2 minutos.",
                        reply_markup=InlineKeyboardMarkup([{
                            InlineKeyboardButton(
                                text="Soy un humano",
                                callback_data=f"user_join_({new_mem.id})",
                            )
                        }]),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_to_message_id=reply,
                    )
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_add_web_page_previews=False,
                        ),
                    )
                    job_queue.run_once(
                        partial(check_not_bot, new_mem, chat.id,
                                message.message_id),
                        120,
                        name="welcomemute",
                    )

        if welcome_bool:
            if media_wel:
                if ENUM_FUNC_MAP[welc_type] == dispatcher.bot.send_sticker:
                    sent = ENUM_FUNC_MAP[welc_type](
                        chat.id,
                        cust_content,
                        reply_markup=keyboard,
                        reply_to_message_id=reply,
                    )
                else:
                    sent = ENUM_FUNC_MAP[welc_type](
                        chat.id,
                        cust_content,
                        caption=res,
                        reply_markup=keyboard,
                        reply_to_message_id=reply,
                        parse_mode="markdown",
                    )
            else:
                sent = send(update, res, keyboard, backup_message)
            prev_welc = sql.get_clean_pref(chat.id)
            if prev_welc:
                try:
                    bot.delete_message(chat.id, prev_welc)
                except BadRequest:
                    pass

                if sent:
                    sql.set_clean_welcome(chat.id, sent.message_id)

        if welcome_log:
            return welcome_log

        if user.id == new_mem.id:
            welcome_log = (
                f"{html.escape(chat.title)}\n"
                f"#EntradaUsuario\n"
                f"<b>Usuario</b>: {mention_html(user.id, user.first_name)}\n"
                f"<b>ID</b>: <code>{user.id}</code>")
        elif new_mem.is_bot and user.id != new_mem.id:
            welcome_log = (
                f"{html.escape(chat.title)}\n"
                f"#BotAñadido\n"
                f"<b>Bot</b>: {mention_html(new_mem.id, new_mem.first_name)}\n"
                f"<b>ID</b>: <code>{new_mem.id}</code>")
        else:
            welcome_log = (
                f"{html.escape(chat.title)}\n"
                f"#UsuarioAñadido\n"
                f"<b>User</b>: {mention_html(new_mem.id, new_mem.first_name)}\n"
                f"<b>ID</b>: <code>{new_mem.id}</code>")
        return welcome_log

    return ""
Exemplo n.º 4
0
def __chat_settings__(chat_id, user_id):
    welcome_pref = sql.get_welc_pref(chat_id)[0]
    goodbye_pref = sql.get_gdbye_pref(chat_id)[0]
    return ("Configuración de bienvenida establecida en `{}`.\n"
            "Configuración de despedida establecida en `{}`.".format(
                welcome_pref, goodbye_pref))