Пример #1
0
def list_warn_filters(update, context):
    chat = update.effective_chat
    user = update.effective_user

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat_id = conn
    else:
        if chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id

    all_handlers = sql.get_chat_warn_triggers(chat_id)

    if not all_handlers:
        update.effective_message.reply_text(
            "Tidak ada filter peringatan yang aktif di sini!")
        return

    filter_list = CURRENT_WARNING_FILTER_STRING
    for keyword in all_handlers:
        entry = " - {}\n".format(html.escape(keyword))
        if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(filter_list,
                                                parse_mode=ParseMode.HTML)
            filter_list = entry
        else:
            filter_list += entry

    if not filter_list == CURRENT_WARNING_FILTER_STRING:
        update.effective_message.reply_text(filter_list,
                                            parse_mode=ParseMode.HTML)
Пример #2
0
def invite(update, context):
    user = update.effective_user
    msg = update.effective_message
    chat = update.effective_chat
    context.args

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
    else:
        if msg.chat.type == "private":
            msg.reply_text("Perintah ini dimaksudkan untuk digunakan dalam obrolan bukan di PM")
            return ""
        chat = update.effective_chat

    if chat.username:
        msg.reply_text(chat.username)
    elif chat.type == chat.SUPERGROUP or chat.type == chat.CHANNEL:
        bot_member = chat.get_member(context.bot.id)
        if bot_member.can_invite_users:
            invitelink = context.bot.exportChatInviteLink(chat.id)
            msg.reply_text(invitelink)
        else:
            msg.reply_text(
                "Saya tidak memiliki akses ke tautan undangan, coba ubah izin saya!"
            )
    else:
        msg.reply_text(
            "Saya hanya dapat memberi Anda tautan undangan untuk supergrup dan saluran, maaf!"
        )
Пример #3
0
def clear(update, context):
    args = context.args
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_message
    conn = connected(context.bot, update, chat, user.id)
    note_name, text, data_type, content, buttons = get_note_type(msg)

    if not conn == 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 notes"
        else:
            chat_name = chat.title

    if len(args) >= 1:
        notename = args[0].lower()

        if sql.rm_note(chat_id, notename):
            update.effective_message.reply_text(
                "Berhasil menghapus '`{note_name}`' dari {chat_name}!".format(
                    note_name=note_name, chat_name=chat_name),
                parse_mode=ParseMode.MARKDOWN,
            )
        else:
            update.effective_message.reply_text(
                "Tidak ada catatan yang disimpan di {chat_name}!".format(
                    chat_name=chat_name))
Пример #4
0
def set_warn_strength(update, context):
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_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 chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    if args:
        if args[0].lower() in ("on", "yes"):
            sql.set_warn_strength(chat_id, False)
            msg.reply_text(
                "Terlalu banyak peringatan sekarang akan mengakibatkan pelarangan!"
            )
            return (
                "<b>{}:</b>\n"
                "<b>Admin:</b> {}\n"
                "Telah mengaktifkan peringatan yang kuat. Pengguna akan diblokir."
                .format(chat_name, mention_html(user.id, user.first_name)))

        elif args[0].lower() in ("off", "no"):
            sql.set_warn_strength(chat_id, True)
            msg.reply_text(
                "Terlalu banyak peringatan sekarang akan menghasilkan tendangan! Pengguna akan dapat bergabung lagi setelah itu."
            )
            return (
                "<b>{}:</b>\n"
                "<b>Admin:</b> {}\n"
                "Telah menonaktifkan peringatan yang kuat. Pengguna hanya akan ditendang."
                .format(chat_name, mention_html(user.id, user.first_name)))

        else:
            msg.reply_text("Saya hanya mengerti on/yes/no/off!")
    else:
        _, soft_warn = sql.get_warn_setting(chat_id)
        if soft_warn:
            msg.reply_text(
                "Peringatan saat ini disetel untuk *menendang* pengguna ketika mereka melebihi batas.",
                parse_mode=ParseMode.MARKDOWN,
            )
        else:
            msg.reply_text(
                "Peringatan saat ini disetel untuk *melarang* pengguna ketika mereka melebihi batas.",
                parse_mode=ParseMode.MARKDOWN,
            )
    return ""
Пример #5
0
def set_warn_strength(update, context):
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_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 chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    if args:
        if args[0].lower() in ("on", "yes"):
            sql.set_warn_strength(chat_id, False)
            msg.reply_text("Too many warns will now result in a ban!")
            return ("<b>{}:</b>\n"
                    "<b>Admin:</b> {}\n"
                    "Has enabled strong warns. Users will be banned.".format(
                        chat_name, mention_html(user.id, user.first_name)))

        elif args[0].lower() in ("off", "no"):
            sql.set_warn_strength(chat_id, True)
            msg.reply_text(
                "Too many warns will now result in a kick! Users will be able to join again after."
            )
            return (
                "<b>{}:</b>\n"
                "<b>Admin:</b> {}\n"
                "Has disabled strong warns. Users will only be kicked.".format(
                    chat_name, mention_html(user.id, user.first_name)))

        else:
            msg.reply_text("I only understand on/yes/no/off!")
    else:
        _, soft_warn = sql.get_warn_setting(chat_id)
        if soft_warn:
            msg.reply_text(
                "Warns are currently set to *kick* users when they exceed the limits.",
                parse_mode=ParseMode.MARKDOWN,
            )
        else:
            msg.reply_text(
                "Warns are currently set to *ban* users when they exceed the limits.",
                parse_mode=ParseMode.MARKDOWN,
            )
    return ""
Пример #6
0
def warns(update, context):
    message = update.effective_message
    chat = update.effective_chat
    args = context.args
    user = update.effective_user
    user_id = extract_user(message, args) or update.effective_user.id

    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 chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    result = sql.get_warns(user_id, chat_id)

    num = 1
    if result and result[0] != 0:
        num_warns, reasons = result
        limit, _ = sql.get_warn_setting(chat_id)

        if reasons:
            if conn:
                text = "Pengguna ini memiliki {}/{} peringatan, dalam * {} * karena alasan berikut:".format(
                    num_warns, limit, chat_name)
            else:
                text = "Pengguna ini memiliki {}/{} peringatan, karena alasan berikut:".format(
                    num_warns,
                    limit,
                )
            for reason in reasons:
                text += "\n {}. {}".format(num, reason)
                num += 1

            msgs = split_message(text)
            for msg in msgs:
                update.effective_message.reply_text(msg, parse_mode="markdown")
        else:
            update.effective_message.reply_text(
                "Pengguna memiliki peringatan {}/{}, tapi tidak ada alasan untuk itu."
                .format(num_warns, limit),
                parse_mode="markdown",
            )
    else:
        update.effective_message.reply_text(
            "Pengguna ini tidak mendapat peringatan apa pun!")
Пример #7
0
def warns(update, context):
    message = update.effective_message
    chat = update.effective_chat
    args = context.args
    user = update.effective_user
    user_id = extract_user(message, args) or update.effective_user.id

    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 chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    result = sql.get_warns(user_id, chat_id)

    num = 1
    if result and result[0] != 0:
        num_warns, reasons = result
        limit, _ = sql.get_warn_setting(chat_id)

        if reasons:
            if conn:
                text = "This user has {}/{} warnings, in *{}* for the following reasons:".format(
                    num_warns, limit, chat_name)
            else:
                text = "This user has {}/{} warnings, for the following reasons:".format(
                    num_warns,
                    limit,
                )
            for reason in reasons:
                text += "\n {}. {}".format(num, reason)
                num += 1

            msgs = split_message(text)
            for msg in msgs:
                update.effective_message.reply_text(msg, parse_mode="markdown")
        else:
            update.effective_message.reply_text(
                "User has {}/{} warnings, but no reasons for any of them.".
                format(num_warns, limit),
                parse_mode="markdown",
            )
    else:
        update.effective_message.reply_text(
            "This user hasn't got any warnings!")
Пример #8
0
def add_warn_filter(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, need_admin=True)
    if conn:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    if len(args) < 2:
        return

    extracted = split_quotes(args[1])

    if len(extracted) >= 2:
        # set trigger -> lower, so as to avoid adding duplicate filters with
        # different cases
        keyword = extracted[0].lower()
        content = extracted[1]

    else:
        return

    # Note: perhaps handlers can be removed somehow using sql.get_chat_filters
    for handler in dispatcher.handlers.get(WARN_HANDLER_GROUP, []):
        if handler.filters == (keyword, chat_id):
            dispatcher.remove_handler(handler, WARN_HANDLER_GROUP)

    sql.add_warn_filter(chat_id, keyword, content)

    update.effective_message.reply_text(
        "Filter peringatan ditambahkan untuk `{}` di *{}*!".format(
            keyword, chat_name),
        parse_mode="markdown",
    )
    raise DispatcherHandlerStop
Пример #9
0
def add_blacklist(update, context):
    msg = update.effective_message
    chat = update.effective_chat
    user = update.effective_user
    words = msg.text.split(None, 1)

    conn = connected(context.bot, update, chat, user.id)
    if conn:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            return
        else:
            chat_name = chat.title

    if len(words) > 1:
        text = words[1]
        to_blacklist = list(
            set(trigger.strip() for trigger in text.split("\n")
                if trigger.strip()))
        for trigger in to_blacklist:
            blacklist_db.add_to_blacklist(chat_id, trigger.lower())

        if len(to_blacklist) == 1:
            send_message(
                update.effective_message,
                "Menambahkan daftar hitam <code>{}</code> dalam obrolan: <b>{}</b>!"
                .format(html.escape(to_blacklist[0]), chat_name),
                parse_mode=ParseMode.HTML,
            )

        else:
            send_message(
                update.effective_message,
                "Menambahkan pemicu daftar hitam: <code>{}</code> di <b>{}</b>!"
                .format(len(to_blacklist), chat_name),
                parse_mode=ParseMode.HTML,
            )

    else:
        send_message(
            update.effective_message,
            "Beri tahu saya kata mana yang ingin Anda tambahkan ke daftar hitam.",
        )
Пример #10
0
    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,
                    "Perintah ini dimaksudkan untuk digunakan di grup bukan di PM",
                )
                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):
                disable_db.disable_command(chat.id, disable_cmd)
                if conn:
                    text = "Menonaktifkan penggunaan perintah `{}` di *{}*!".format(
                        disable_cmd, chat_name
                    )
                else:
                    text = "Menonaktifkan penggunaan perintah `{}`!".format(
                        disable_cmd
                    )
                send_message(
                    update.effective_message,
                    text,
                    parse_mode=ParseMode.MARKDOWN,
                )
            else:
                send_message(
                    update.effective_message, "Perintah ini tidak dapat dinonaktifkan"
                )

        else:
            send_message(update.effective_message, "Apa yang harus saya nonaktifkan?")
Пример #11
0
def remove_warn_filter(update, context):
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_message

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat_id = conn
    else:
        if chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id

    args = msg.text.split(
        None,
        1)  # use python's maxsplit to separate Cmd, keyword, and reply_text

    if len(args) < 2:
        return

    extracted = split_quotes(args[1])

    if len(extracted) < 1:
        return

    to_remove = extracted[0]

    chat_filters = sql.get_chat_warn_triggers(chat_id)

    if not chat_filters:
        msg.reply_text("Tidak ada filter peringatan yang aktif di sini!")
        return

    for filt in chat_filters:
        if filt == to_remove:
            sql.remove_warn_filter(chat_id, to_remove)
            msg.reply_text(
                "YYa, saya akan berhenti memperingatkan orang untuk ituep, I'll stop warning people for that."
            )
            raise DispatcherHandlerStop

    msg.reply_text(
        "Itu bukan filter peringatan saat ini - klik: /warnlist untuk semua filter peringatan aktif."
    )
Пример #12
0
def set_warn_limit(update, context) -> str:
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_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 chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    if args:
        if args[0].isdigit():
            if int(args[0]) < 3:
                msg.reply_text("Batas peringatan minimum adalah 3!")
            else:
                sql.set_warn_limit(chat_id, int(args[0]))
                msg.reply_text(
                    "Memperbarui batas peringatan menjadi `{}` di *{}*".format(
                        escape_markdown(args[0]), chat_name),
                    parse_mode="markdown",
                )
                return ("<b>{}:</b>"
                        "\n#SET_WARN_LIMIT"
                        "\n<b>Admin:</b> {}"
                        "\nSet the warn limit to <code>{}</code>".format(
                            html.escape(chat_name),
                            mention_html(user.id, user.first_name),
                            args[0],
                        ))
        else:
            msg.reply_text("Beri saya nomor sebagai argumen!")
    else:
        limit, _ = sql.get_warn_setting(chat_id)

        msg.reply_text("Peringatan saat ini dalam batas {} adalah {}".format(
            chat_name, limit))
    return ""
Пример #13
0
def save(update, context):
    chat = update.effective_chat
    user = update.effective_user
    conn = connected(context.bot, update, chat, user.id)
    if not conn == 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 notes"
        else:
            chat_name = chat.title

    msg = update.effective_message

    try:
        note_name, text, data_type, content, buttons = get_note_type(msg)
    except IndexError:
        msg.reply_text(
            "Ini bukanlah hal yang benar T_T\nGunakan: /save <notename> <pesan/balas ke pesan>"
        )
        return
    note_name = note_name.lower()

    if data_type is None:
        msg.reply_text("Bruh! tidak ada catatan")
        return

    if len(text.strip()) == 0:
        text = note_name

    sql.add_note_to_db(chat_id,
                       note_name,
                       text,
                       data_type,
                       buttons=buttons,
                       file=content)

    msg.reply_text(
        "Menyimpan '`{note_name}`' di *{chat_name}*.\nDapatkan dengan `/get {note_name}`, atau`#{note_name}`!"
        .format(note_name=note_name, chat_name=chat_name),
        parse_mode=ParseMode.MARKDOWN,
    )
Пример #14
0
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 == False:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
        filter_list = "*Filter in {}:*\n"
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            chat_name = "Local filters"
            filter_list = "*local filters:*\n"
        else:
            chat_name = chat.title
            filter_list = "*Filters in {}*:\n"

    all_handlers = sql.get_chat_triggers(chat_id)

    if not all_handlers:
        send_message(
            update.effective_message,
            "Tidak ada filter yang disimpan di {}!".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,
    )
Пример #15
0
def set_warn_limit(update, context) -> str:
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_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 chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    if args:
        if args[0].isdigit():
            if int(args[0]) < 3:
                msg.reply_text("The minimum warn limit is 3!")
            else:
                sql.set_warn_limit(chat_id, int(args[0]))
                msg.reply_text(
                    "Updated the warn limit to `{}` in *{}*".format(
                        escape_markdown(args[0]), chat_name),
                    parse_mode="markdown",
                )
                return ("<b>{}:</b>"
                        "\n#SET_WARN_LIMIT"
                        "\n<b>Admin:</b> {}"
                        "\nSet the warn limit to <code>{}</code>".format(
                            html.escape(chat_name),
                            mention_html(user.id, user.first_name),
                            args[0],
                        ))
        else:
            msg.reply_text("Give me a number as an arg!")
    else:
        limit, _ = sql.get_warn_setting(chat_id)

        msg.reply_text("The current warn in {} limit is {}".format(
            chat_name, limit))
    return ""
Пример #16
0
def blacklist(update, context):
    chat = update.effective_chat
    user = update.effective_user
    args = context.args

    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 chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id
            chat_name = chat.title

    filter_list = "Kata-kata dalam daftar hitam saat ini dalam <b>{}</b>:\n".format(
        chat_name)

    all_blacklisted = blacklist_db.get_chat_blacklist(chat_id)

    if len(args) > 0 and args[0].lower() == "copy":
        for trigger in all_blacklisted:
            filter_list += "<code>{}</code>\n".format(html.escape(trigger))
    else:
        for trigger in all_blacklisted:
            filter_list += " - <code>{}</code>\n".format(html.escape(trigger))

    # for trigger in all_blacklisted:
    #     filter_list += " - <code>{}</code>\n".format(html.escape(trigger))

    split_text = split_message(filter_list)
    for text in split_text:
        if filter_list == "Kata-kata dalam daftar hitam saat ini dalam <b>{}</b>:\n".format(
                chat_name):
            send_message(
                update.effective_message,
                "Tidak ada kata dalam daftar hitam <b>{}</b>!".format(
                    chat_name),
                parse_mode=ParseMode.HTML,
            )
            return
        send_message(update.effective_message, text, parse_mode=ParseMode.HTML)
Пример #17
0
    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)
        else:
            if update.effective_message.chat.type == "private":
                send_message(
                    update.effective_message,
                    "Perintah ini dimaksudkan untuk digunakan dalam grup bukan di PM",
                )
                return ""
            chat = update.effective_chat

        text = build_curr_disabled(chat.id)
        send_message(update.effective_message,
                     text,
                     parse_mode=ParseMode.MARKDOWN)
Пример #18
0
def remove_warn_filter(update, context):
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_message

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat_id = conn
    else:
        if chat.type == "private":
            return
        else:
            chat_id = update.effective_chat.id

    args = msg.text.split(
        None,
        1)  # use python's maxsplit to separate Cmd, keyword, and reply_text

    if len(args) < 2:
        return

    extracted = split_quotes(args[1])

    if len(extracted) < 1:
        return

    to_remove = extracted[0]

    chat_filters = sql.get_chat_warn_triggers(chat_id)

    if not chat_filters:
        msg.reply_text("No warning filters are active here!")
        return

    for filt in chat_filters:
        if filt == to_remove:
            sql.remove_warn_filter(chat_id, to_remove)
            msg.reply_text("Yep, I'll stop warning people for that.")
            raise DispatcherHandlerStop

    msg.reply_text(
        "That's not a current warning filter - click: /warnlist for all active warning filters."
    )
Пример #19
0
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 == 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, "Apa yang harus saya hentikan?")
        return

    chat_filters = sql.get_chat_triggers(chat_id)

    if not chat_filters:
        send_message(update.effective_message,
                     "Tidak ada filter yang aktif di sini!")
        return

    for keyword in chat_filters:
        if keyword == args[1]:
            sql.remove_filter(chat_id, args[1])
            send_message(
                update.effective_message,
                "Oke, saya akan berhenti membalas filter itu *{}*.".format(
                    chat_name),
                parse_mode=telegram.ParseMode.MARKDOWN,
            )
            raise DispatcherHandlerStop

    send_message(
        update.effective_message,
        "Itu bukan filter - Klik: /filters untuk mendapatkan filter yang sedang aktif.",
    )
Пример #20
0
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,
                "Perintah ini dimaksudkan untuk digunakan dalam grup bukan di PM",
            )
            return
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    limit = sql.get_flood_limit(chat_id)
    if limit == 0:
        if conn:
            text = (
                "Saya tidak memaksakan pengendalian flood apa pun{}!".format(chat_name)
            )
        else:
            text = ("Saya tidak memaksakan pengendalian flood di sini!")
    else:
        if conn:
            text = (
                "Saya saat ini membatasi anggota setelah {} pesan berurutan di {}.".format(
                    limit, chat_name
                )
            )
        else:
            text = (
                "Saya saat ini membatasi anggota setelah {} pesan berturut-turut.".format(
                    limit
                )
            )
    send_message(msg, text, parse_mode="markdown")
Пример #21
0
def list_notes(update, context):
    chat_id = update.effective_chat.id
    chat = update.effective_chat
    user = update.effective_user
    conn = connected(context.bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
        msg = "*Catatan dalam {}:*\n"
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            chat_name = ""
            msg = "*Catatan Lokal:*\n"
        else:
            chat_name = chat.title
            msg = "*Catatan disimpan di {}:*\n"

    note_list = sql.get_all_chat_notes(chat_id)
    des = "Anda bisa mendapatkan catatan dengan menggunakan `/get notename`, atau `#notename`.\n"
    for note in note_list:
        note_name = " × `{}`\n".format(note.name.lower())
        if len(msg) + len(note_name) > MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(msg,
                                                parse_mode=ParseMode.MARKDOWN)
            msg = ""
        msg += note_name

    if not note_list:
        update.effective_message.reply_text(
            "Tidak ada catatan yang disimpan di sini!")

    elif len(msg) != 0:
        try:
            update.effective_message.reply_text(msg.format(chat_name) + des,
                                                parse_mode=ParseMode.MARKDOWN)
        except ValueError:
            update.effective_message.reply_text(
                "Terjadi masalah saat menampilkan daftar catatan, mungkin karena beberapa karakter tidak valid dalam nama catatan. Tanyakan di @ZeroBotSupport jika Anda tidak dapat menemukannya!"
            )
Пример #22
0
def list_locks(update, context):
    chat = update.effective_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,
                "Perintah ini dimaksudkan untuk digunakan dalam grup bukan di PM",
            )
            return ""
        chat = update.effective_chat
        chat_name = update.effective_message.chat.title

    res = build_lock_message(chat.id)
    if conn:
        res = res.replace("Terkunci di", "*{}*".format(chat_name))

    send_message(update.effective_message, res, parse_mode=ParseMode.MARKDOWN)
Пример #23
0
def import_data(update, context):
    msg = update.effective_message
    chat = update.effective_chat
    user = update.effective_user
    # TODO: allow uploading doc with command, not just as reply
    # only work with a doc

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            update.effective_message.reply_text(
                "Perintah ini hanya dapat dijalankan pada grup, bukan PM."
            )
            return ""

        chat = update.effective_chat
        chat_name = update.effective_message.chat.title

    if msg.reply_to_message and msg.reply_to_message.document:
        try:
            file_info = context.bot.get_file(
                msg.reply_to_message.document.file_id
            )
        except BadRequest:
            msg.reply_text(
                "Coba unduh dan unggah sendiri berkasnya, Yang ini sepertinya rusak!"
            )
            return

        with BytesIO() as file:
            file_info.download(out=file)
            file.seek(0)
            data = json.load(file)

        # only import one group
        if len(data) > 1 and str(chat.id) not in data:
            msg.reply_text(
                "Ada lebih dari satu grup dalam berkas ini dan chat.id tidak sama! Bagaimana saya bisa mengimpornya?"
            )
            return

        # Check if backup is this chat
        try:
            if data.get(str(chat.id)) is None:
                if conn:
                    text = "Cadangan berasal dari obrolan lain, saya tidak bisa mengembalikan obrolan lain untuk mengobrol *{}*".format(
                        chat_name
                    )
                else:
                    text = "Cadangan berasal dari obrolan lain, saya tidak dapat mengembalikan obrolan lain ke obrolan ini "
                return msg.reply_text(text, parse_mode="markdown")
        except Exception:
            return msg.reply_text("Ada masalah saat mengimpor data!")
        # Check if backup is from self
        try:
            if str(context.bot.id) != str(data[str(chat.id)]["bot"]):
                return msg.reply_text(
                    "Cadangan dari bot lain yang tidak disarankan dapat menyebabkan masalah, dokumen, foto, video, audio, rekaman mungkin tidak berfungsi sebagaimana mestinya."
                )
        except Exception:
            pass
        # Select data source
        if str(chat.id) in data:
            data = data[str(chat.id)]["hashes"]
        else:
            data = data[list(data.keys())[0]]["hashes"]

        try:
            for mod in DATA_IMPORT:
                mod.__import_data__(str(chat.id), data)
        except Exception:
            msg.reply_text(
                "Timbul galat saat memulihkan data Anda. Proses gagal. Jika Anda mengalami masalah dengan ini, silakan tanyakan @HayakaRyu"
            )

            LOGGER.exception(
                "Imprt for the chat %s with the name %s failed.",
                str(chat.id),
                str(chat.title),
            )
            return

        # TODO: some of that link logic
        # NOTE: consider default permissions stuff?
        if conn:

            text = "Pencadangan sepenuhnya dipulihkan pada *{}*.".format(chat_name)
        else:
            text = "Pencadangan sepenuhnya dipulihkan"
        msg.reply_text(text, parse_mode="markdown")
Пример #24
0
def export_data(update, context):
    chat_data = context.chat_data
    msg = update.effective_message
    user = update.effective_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(
                "Perintah ini hanya dapat digunakan pada grup, bukan PM"
            )
            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(
                "Anda hanya dapat mencadangkan sekali sehari!nAnda dapat mencadangkan lagi dalam tentang `{}`".format(
                    timeformatt
                ),
                parse_mode=ParseMode.MARKDOWN,
            )
            return
        else:
            if user.id != OWNER_ID or user.id not in DEV_USERS:
                put_chat(chat_id, new_jam, chat_data)
    else:
        if user.id != OWNER_ID or user.id not in DEV_USERS:
            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 = chat_rules(chat_id)
    # Blacklist
    bl = list(blacklist_db.get_chat_blacklist(chat_id))
    # Disabled command
    disabledcmd = list(disable_db.get_all_disabled(chat_id))
    # Filters (TODO)
    """
	all_filters = list(filtersql.get_chat_triggers(chat_id))
	export_filters = {}
	for filters in all_filters:
		filt = filtersql.get_filter(chat_id, filters)
		# print(vars(filt))
		if filt.is_sticker:
			tipefilt = "sticker"
		elif filt.is_document:
			tipefilt = "doc"
		elif filt.is_image:
			tipefilt = "img"
		elif filt.is_audio:
			tipefilt = "audio"
		elif filt.is_voice:
			tipefilt = "voice"
		elif filt.is_video:
			tipefilt = "video"
		elif filt.has_buttons:
			tipefilt = "button"
			buttons = filtersql.get_buttons(chat.id, filt.keyword)
			print(vars(buttons))
		elif filt.has_markdown:
			tipefilt = "text"
		if tipefilt == "button":
			content = "{}#=#{}|btn|{}".format(tipefilt, filt.reply, buttons)
		else:
			content = "{}#=#{}".format(tipefilt, filt.reply)
		print(content)
		export_filters[filters] = content
	print(export_filters)
	"""
    # Welcome (TODO)
    # welc = welcsql.get_welc_pref(chat_id)
    # Locked
    curr_locks = locksql.get_locks(chat_id)
    curr_restr = locksql.get_restr(chat_id)

    if curr_locks:
        locked_lock = {
            "sticker": curr_locks.sticker,
            "audio": curr_locks.audio,
            "voice": curr_locks.voice,
            "document": curr_locks.document,
            "video": curr_locks.video,
            "contact": curr_locks.contact,
            "photo": curr_locks.photo,
            "gif": curr_locks.gif,
            "url": curr_locks.url,
            "bots": curr_locks.bots,
            "forward": curr_locks.forward,
            "game": curr_locks.game,
            "location": curr_locks.location,
            "rtl": curr_locks.rtl,
        }
    else:
        locked_lock = {}

    if curr_restr:
        locked_restr = {
            "messages": curr_restr.messages,
            "media": curr_restr.media,
            "other": curr_restr.other,
            "previews": curr_restr.preview,
            "all": all(
                [
                    curr_restr.messages,
                    curr_restr.media,
                    curr_restr.other,
                    curr_restr.preview,
                ]
            ),
        }
    else:
        locked_restr = {}

    locks = {"locks": locked_lock, "restrict": locked_restr}
    # Warns (TODO)
    # warns = warnssql.get_warns(chat_id)
    # Backing up
    backup[chat_id] = {
        "bot": context.bot.id,
        "hashes": {
            "info": {"rules": rules},
            "extra": notes,
            "blacklist": bl,
            "disabled": disabledcmd,
            "locks": locks,
        },
    }
    baccinfo = json.dumps(backup, indent=4)
    with open("KagaRobot{}.backup".format(chat_id), "w") as f:
        f.write(str(baccinfo))
    context.bot.sendChatAction(current_chat_id, "upload_document")
    tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time()))
    try:
        context.bot.sendMessage(
            MESSAGE_DUMP,
            "*Pencadangan berhasil diimpor:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`".format(
                chat.title, chat_id, tgl
            ),
            parse_mode=ParseMode.MARKDOWN,
        )
    except BadRequest:
        pass
    context.bot.sendDocument(
        current_chat_id,
        document=open("KagaRobot{}.backup".format(chat_id), "rb"),
        caption="*Berhasil mencadangkan:*\nChat: `{}`\nChat ID: `{}`\nDi: `{}`\n\nCatatan: Ini `KagaRobot-Backup` dibuat khusus untuk catatan.".format(
            chat.title, chat_id, tgl
        ),
        timeout=360,
        reply_to_message_id=msg.message_id,
        parse_mode=ParseMode.MARKDOWN,
    )
    os.remove("KagaRobot{}.backup".format(chat_id))  # Cleaning file
Пример #25
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    chat = update.effective_chat
    user = update.effective_user
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if conn:
        chat_id = conn
        user.id
    else:
        chat_id = update.effective_chat.id

    note = sql.get_note(chat_id, notename)
    message = update.effective_message

    if note:
        # If we're replying to a message, reply to that message (unless it's an
        # error)
        if message.reply_to_message:
            reply_id = message.reply_to_message.message_id
        else:
            reply_id = message.message_id

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(
                        chat_id=update.effective_chat.id,
                        from_chat_id=MESSAGE_DUMP,
                        message_id=note.value,
                    )
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Pesan ini sepertinya telah hilang - Saya akan menghapusnya "
                            "dari daftar catatan Anda.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(
                        chat_id=update.effective_chat.id,
                        from_chat_id=chat_id,
                        message_id=note.value,
                    )
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Sepertinya pengirim asli catatan ini telah dihapus "
                            "pesan mereka - maaf! Minta admin bot Anda untuk mulai menggunakan file "
                            "pesan dump untuk menghindari ini. Saya akan menghapus catatan ini dari "
                            "catatan Anda yang disimpan.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            VALID_NOTE_FORMATTERS = [
                "first",
                "last",
                "fullname",
                "username",
                "id",
                "chatname",
                "mention",
            ]
            valid_format = escape_invalid_curly_brackets(
                note.value, VALID_NOTE_FORMATTERS)
            if valid_format:
                text = 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:
                text = ""

            keyb = []
            parseMode = ParseMode.HTML
            buttons = sql.get_buttons(chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                text = markdown_to_html(text)
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(
                        update.effective_chat.id,
                        text,
                        reply_to_message_id=reply_id,
                        parse_mode=parseMode,
                        disable_web_page_preview=True,
                        reply_markup=keyboard,
                    )
                else:
                    if (ENUM_FUNC_MAP[note.msgtype] ==
                            dispatcher.bot.send_sticker):
                        ENUM_FUNC_MAP[note.msgtype](
                            chat_id,
                            note.file,
                            reply_to_message_id=reply_id,
                            reply_markup=keyboard,
                        )
                    else:
                        ENUM_FUNC_MAP[note.msgtype](
                            update.effective_chat.id,
                            note.file,
                            caption=text,
                            reply_to_message_id=reply_id,
                            parse_mode=parseMode,
                            reply_markup=keyboard,
                        )

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Sepertinya Anda mencoba menyebut seseorang yang belum pernah saya lihat sebelumnya. Jika Anda benar-benar "
                        "ingin menyebutkan mereka, meneruskan salah satu pesan mereka kepada saya, dan saya akan bisa "
                        "untuk menandai mereka!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "Catatan ini adalah file yang diimpor dengan tidak benar dari bot lain - Saya tidak dapat menggunakan "
                        "Itu. Jika Anda benar-benar membutuhkannya, Anda harus menyimpannya lagi. Di "
                        "sementara itu, saya akan menghapusnya dari daftar catatan Anda."
                    )
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "Catatan ini tidak dapat dikirim, karena formatnya salah."
                    )

                    LOGGER.exception(
                        "Could not parse message #%s in chat %s",
                        notename,
                        str(chat_id),
                    )
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("Catatan ini tidak ada")
Пример #26
0
def unblacklist(update, context):
    msg = update.effective_message
    chat = update.effective_chat
    user = update.effective_user
    words = msg.text.split(None, 1)

    conn = connected(context.bot, update, chat, user.id)
    if conn:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            return
        else:
            chat_name = chat.title

    if len(words) > 1:
        text = words[1]
        to_unblacklist = list(
            set(trigger.strip() for trigger in text.split("\n")
                if trigger.strip()))
        successful = 0
        for trigger in to_unblacklist:
            success = blacklist_db.rm_from_blacklist(chat_id, trigger.lower())
            if success:
                successful += 1

        if len(to_unblacklist) == 1:
            if successful:
                send_message(
                    update.effective_message,
                    "Dihapus <code>{}</code> dari daftar hitam di <b>{}</b>!".
                    format(html.escape(to_unblacklist[0]), chat_name),
                    parse_mode=ParseMode.HTML,
                )
            else:
                send_message(
                    update.effective_message,
                    "Ini bukan pemicu daftar hitam!",
                )

        elif successful == len(to_unblacklist):
            send_message(
                update.effective_message,
                "Dihapus <code>{}</code> dari daftar hitam di <b>{}</b>!".
                format(successful, chat_name),
                parse_mode=ParseMode.HTML,
            )

        elif not successful:
            send_message(
                update.effective_message,
                "Tidak satu pun pemicu ini ada sehingga tidak dapat dihapus.".
                format(successful,
                       len(to_unblacklist) - successful),
                parse_mode=ParseMode.HTML,
            )

        else:
            send_message(
                update.effective_message,
                "Dihapus <code>{}</code> dari daftar hitam. {} Tidak ada, "
                "jadi tidak dihapus.".format(successful,
                                             len(to_unblacklist) - successful),
                parse_mode=ParseMode.HTML,
            )
    else:
        send_message(
            update.effective_message,
            "Beri tahu saya kata mana yang ingin Anda hapus dari daftar hitam!",
        )
Пример #27
0
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 == 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,
            "Berikan kata kunci keyboard untuk membalas dengan filter ini!",
        )
        return

    if msg.reply_to_message:
        if len(args) < 2:
            send_message(
                update.effective_message,
                "Berikan kata kunci untuk membalas dengan filter ini!",
            )
            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,
                "Tidak ada pesan catatan - Anda tidak bisa HANYA memiliki tombol, Anda perlu pesan untuk menyertainya!",
            )
            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,
            "Harap berikan kata kunci untuk balasan filter ini dengan!",
        )
        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,
                "Tidak ada pesan catatan - Anda tidak bisa HANYA memiliki tombol, Anda perlu pesan untuk menyertainya!",
            )
            return

    else:
        send_message(update.effective_message, "Filter tidak valid!")
        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:
        send_message(
            update.effective_message,
            "Filter tersimpan '{}' di *{}*!".format(keyword, chat_name),
            parse_mode=telegram.ParseMode.MARKDOWN,
        )
    raise DispatcherHandlerStop
Пример #28
0
def blacklist_mode(update, context):
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_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,
                "Perintah ini hanya dapat digunakan di grup bukan di PM",
            )
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    if args:
        if (args[0].lower() == "off" or args[0].lower() == "nothing"
                or args[0].lower() == "no"):
            settypeblacklist = "do nothing"
            blacklist_db.set_blacklist_strength(chat_id, 0, "0")
        elif args[0].lower() == "del" or args[0].lower() == "delete":
            settypeblacklist = "will delete blacklisted message"
            blacklist_db.set_blacklist_strength(chat_id, 1, "0")
        elif args[0].lower() == "warn":
            settypeblacklist = "warn the sender"
            blacklist_db.set_blacklist_strength(chat_id, 2, "0")
        elif args[0].lower() == "mute":
            settypeblacklist = "mute the sender"
            blacklist_db.set_blacklist_strength(chat_id, 3, "0")
        elif args[0].lower() == "kick":
            settypeblacklist = "kick the sender"
            blacklist_db.set_blacklist_strength(chat_id, 4, "0")
        elif args[0].lower() == "ban":
            settypeblacklist = "ban the sender"
            blacklist_db.set_blacklist_strength(chat_id, 5, "0")
        elif args[0].lower() == "tban":
            if len(args) == 1:
                teks = """Sepertinya Anda mencoba menyetel nilai waktu untuk daftar hitam tetapi Anda tidak menentukan waktu; Coba, `/blacklistmode tban <timevalue>`.
Contoh nilai waktu: 4m = 4 menit, 3h = 3 jam, 6d = 6 hari, 5w = 5 minggu."""
                send_message(update.effective_message,
                             teks,
                             parse_mode="markdown")
                return ""
            restime = extract_time(msg, args[1])
            if not restime:
                teks = """Nilai waktu tidak valid!
Contoh nilai waktu: 4m = 4 menit, 3h = 3 jam, 6d = 6 hari, 5w = 5 minggu."""
                send_message(update.effective_message,
                             teks,
                             parse_mode="markdown")
                return ""
            settypeblacklist = "larangan sementara untuk {}".format(args[1])
            blacklist_db.set_blacklist_strength(chat_id, 6, str(args[1]))
        elif args[0].lower() == "tmute":
            if len(args) == 1:
                teks = """Sepertinya Anda mencoba menyetel nilai waktu untuk daftar hitam tetapi Anda tidak menentukan waktu; Coba, `/blacklistmode tmute <timevalue>`.

Contoh nilai waktu: 4m = 4 menit, 3h = 3 jam, 6d = 6 hari, 5w = 5 minggu."""
                send_message(update.effective_message,
                             teks,
                             parse_mode="markdown")
                return ""
            restime = extract_time(msg, args[1])
            if not restime:
                teks = """Nilai waktu tidak valid!
Contoh nilai waktu: 4m = 4 menit, 3h = 3 jam, 6d = 6 hari, 5w = 5 minggu."""
                send_message(update.effective_message,
                             teks,
                             parse_mode="markdown")
                return ""
            settypeblacklist = "bisukan sementara untuk {}".format(args[1])
            blacklist_db.set_blacklist_strength(chat_id, 7, str(args[1]))
        else:
            send_message(
                update.effective_message,
                "Saya hanya mengerti: off/del/warn/ban/kick/mute/tban/tmute!",
            )
            return ""
        if conn:
            text = "Modus daftar hitam diubah `{}` di *{}*!".format(
                settypeblacklist, chat_name)
        else:
            text = "Modus daftar hitam diubah: `{}`!".format(settypeblacklist)
        send_message(update.effective_message, text, parse_mode="markdown")
        return ("<b>{}:</b>\n"
                "<b>Admin:</b> {}\n"
                "Changed the blacklist mode. will {}.".format(
                    html.escape(chat.title),
                    mention_html(user.id, user.first_name),
                    settypeblacklist,
                ))
    else:
        getmode, getvalue = blacklist_db.get_blacklist_setting(chat.id)
        if getmode == 0:
            settypeblacklist = "do nothing"
        elif getmode == 1:
            settypeblacklist = "delete"
        elif getmode == 2:
            settypeblacklist = "warn"
        elif getmode == 3:
            settypeblacklist = "mute"
        elif getmode == 4:
            settypeblacklist = "kick"
        elif getmode == 5:
            settypeblacklist = "ban"
        elif getmode == 6:
            settypeblacklist = "temporarily ban for {}".format(getvalue)
        elif getmode == 7:
            settypeblacklist = "temporarily mute for {}".format(getvalue)
        if conn:
            text = "Mode daftar hitam saat ini: *{}* di *{}*.".format(
                settypeblacklist, chat_name)
        else:
            text = "Mode daftar hitam saat ini: *{}*.".format(settypeblacklist)
        send_message(update.effective_message,
                     text,
                     parse_mode=ParseMode.MARKDOWN)
    return ""
Пример #29
0
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,
                "Perintah ini dimaksudkan untuk digunakan dalam grup tidak dalam PM",
            )
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    if args:
        if args[0].lower() == "ban":
            settypeflood = "ban"
            sql.set_flood_strength(chat_id, 1, "0")
        elif args[0].lower() == "kick":
            settypeflood = "kick"
            sql.set_flood_strength(chat_id, 2, "0")
        elif args[0].lower() == "mute":
            settypeflood = "mute"
            sql.set_flood_strength(chat_id, 3, "0")
        elif args[0].lower() == "tban":
            if len(args) == 1:
                teks = """Sepertinya Anda mencoba menetapkan nilai waktu untuk antiflood tetapi Anda tidak menentukan waktu; Coba `/setfloodmode tban <timevalue>`.
Contoh nilai waktu: 4m = 4 menit, 3h = 3 jam, 6d = 6 hari, 5w = 5 minggu."""
                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,
                    """Sepertinya Anda mencoba menetapkan nilai waktu untuk antiflood tetapi Anda tidak menentukan waktu; Coba, `/setfloodmode tmute <timevalue>`.
Contoh nilai waktu: 4m = 4 menit, 3h = 3 jam, 6d = 6 hari, 5w = 5 minggu.""",
                )
                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,
                "Saya hanya mengerti ban/kick/mute/tban/tmute!",
            )
            return
        if conn:
            text = msg.reply_text(
                "Melebihi batas flood berturut-turut akan mengakibatkan {} dalam {}!"
                .format(settypeflood, chat_name))
        else:
            text = msg.reply_text(
                "Melebihi batas flood berturut-turut akan {}!".format(
                    settypeflood))
        return ("<b>{}:</b>\n"
                "<b>Admin:</b> {}\n"
                "Has changed antiflood mode. User will {}.".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(
                "Mengirim lebih banyak pesan daripada batas flood akan mengakibatkan {} masuk {}."
                .format(settypeflood, chat_name))
        else:
            text = msg.reply_text(
                "Mengirim lebih banyak pesan daripada batas flood akan mengakibatkan {}."
                .format(settypeflood))
    return ""
Пример #30
0
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,
                "Perintah ini dimaksudkan untuk digunakan dalam grupPerintah ini dimaksudkan untuk digunakan dalam grup tidak dalam PM tidak dalam PM",
            )
            return ""
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    if len(args) >= 1:
        val = args[0].lower()
        if val == "off" or val == "no" or val == "0":
            sql.set_flood(chat_id, 0)
            if conn:
                text = message.reply_text(
                    "Antiflood telah dinon-fungsikan di {}.".format(chat_name))
            else:
                text = message.reply_text("Antiflood telah dinon-fungsikan.")
            send_message(update.effective_message, text, parse_mode="markdown")

        elif val.isdigit():
            amount = int(val)
            if amount <= 0:
                sql.set_flood(chat_id, 0)
                if conn:
                    text = message.reply_text(
                        "Antiflood telah dinon-fungsikan di{}.".format(
                            chat_name))
                else:
                    text = message.reply_text(
                        "Antiflood telah dinon-fungsikan.")
                return ("<b>{}:</b>"
                        "\n#SETFLOOD"
                        "\n<b>Admin:</b> {}"
                        "\nDisable antiflood.".format(
                            html.escape(chat_name),
                            mention_html(user.id, user.first_name),
                        ))

            elif amount < 3:
                send_message(
                    update.effective_message,
                    "Antiflood must be either 0 (disabled) or number greater than 3!",
                )
                return ""

            else:
                sql.set_flood(chat_id, amount)
                if conn:
                    text = ("Anti-flood telah diatur ke {} dalam obrolan: {}".
                            format(amount, chat_name))
                else:
                    text = ("Berhasil memperbarui batas anti-flood ke {}!".
                            format(amount))
                send_message(update.effective_message,
                             text,
                             parse_mode="markdown")
                return ("<b>{}:</b>"
                        "\n#SETFLOOD"
                        "\n<b>Admin:</b> {}"
                        "\nSet antiflood to <code>{}</code>.".format(
                            html.escape(chat_name),
                            mention_html(user.id, user.first_name),
                            amount,
                        ))

        else:
            message.reply_text(
                "Invalid argument please use a number, 'off' or 'no'")
    else:
        message.reply_text(
            ("Gunakan `/setflood number` untuk mengaktifkan anti-flood.\nAtau gunakan `/setflood off` untuk menonaktifkan antiflood!."
             ),
            parse_mode="markdown",
        )
    return ""