Example #1
0
def get_user_id(username):
    # ensure valid userid
    if len(username) <= 5:
        return None

    if username.startswith("@"):
        username = username[1:]

    users = users_db.get_userid_by_name(username)

    if not users:
        return None

    elif len(users) == 1:
        return users[0]["_id"]

    else:
        for user_obj in users:
            try:
                userdat = dispatcher.bot.get_chat(user_obj["_id"])
                if userdat.username == username:
                    return userdat.id

            except BadRequest as excp:
                if excp.message == "brolan tidak ditemukan":
                    pass
                else:
                    LOGGER.exception(
                        "Terjadi kesalahan saat mengekstrak ID pengguna")

    return None
Example #2
0
def __list_all_modules():
    import glob
    from os.path import basename, dirname, isfile

    # This generates a list of modules in this folder for the * in __main__ to
    # work.
    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [
        basename(f)[:-3] for f in mod_paths
        if isfile(f) and f.endswith(".py") and not f.endswith("__init__.py")
    ]

    if LOAD or NO_LOAD:
        to_load = LOAD
        if to_load:
            if not all(
                    any(mod == module_name for module_name in all_modules)
                    for mod in to_load):
                LOGGER.error("Invalid loadorder names. Quitting.")
                sys.exit(1)

        else:
            to_load = all_modules

        if NO_LOAD:
            LOGGER.info("Not loading: {}".format(NO_LOAD))
            return [item for item in to_load if item not in NO_LOAD]

        return to_load

    return all_modules
Example #3
0
        def log_action(update, context, *args, **kwargs):
            result = func(update, context, *args, **kwargs)
            chat = update.effective_chat
            message = update.effective_message
            if result:
                if chat.type == chat.SUPERGROUP and chat.username:
                    result += (
                        "\n<b>Link:</b> "
                        '<a href="http://telegram.me/{}/{}">click here</a>'.format(
                            chat.username, message.message_id
                        )
                    )
                log_chat = db.get_chat_log_channel(chat.id)
                if log_chat:
                    try:
                        send_log(context.bot, log_chat, chat.id, result)
                    except Unauthorized:
                        db.stop_chat_logging(chat.id)

            elif result == "":
                pass
            else:
                LOGGER.warning(
                    "%s was set as loggable, but had no return statement.",
                    func,
                )

            return result
Example #4
0
def purge(update, context):
    args = context.args
    msg = update.effective_message  # type: Optional[Message]
    if msg.reply_to_message:
        user = update.effective_user  # type: Optional[User]
        chat = update.effective_chat  # type: Optional[Chat]
        if user_can_delete(chat, user, context.bot.id) == False:
           msg.reply_text("Anda tidak memiliki cukup hak untuk menghapus pesan!")
           return ""
        if can_delete(chat, context.bot.id):
            message_id = msg.reply_to_message.message_id
            delete_to = msg.message_id - 1
            if args and args[0].isdigit():
                new_del = message_id + int(args[0])
                # No point deleting messages which haven't been written yet.
                if new_del < delete_to:
                    delete_to = new_del

            for m_id in range(delete_to, message_id - 1, -1):  # Reverse iteration over message ids
                try:
                    context.bot.deleteMessage(chat.id, m_id)
                except BadRequest as err:
                    if err.message == "Message can't be deleted":
                        context.bot.send_message(chat.id, "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin "
                                                  "tidak memiliki hak hapus, atau ini mungkin bukan grup super.")

                    elif err.message != "Message to delete not found":
                        LOGGER.exception("Kesalahan saat membersihkan pesan obrolan.")

            try:
                msg.delete()
            except BadRequest as err:
                if err.message == "Message can't be deleted":
                    context.bot.send_message(chat.id, "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin "
                                              "tidak memiliki hak hapus, atau ini mungkin bukan grup super.")

                elif err.message != "Message to delete not found":
                    LOGGER.exception("Kesalahan saat membersihkan pesan obrolan.")

            del_msg = context.bot.send_message(chat.id, "Pembersihan selesai.")
            time.sleep(2)

            try:
                del_msg.delete()

            except BadRequest:
                pass

            return "<b>{}:</b>" \
                   "\n#PURGE" \
                   "\n<b>Admin:</b> {}" \
                   "\nPurged <code>{}</code> messages.".format(html.escape(chat.title),
                                                               mention_html(user.id, user.first_name),
                                                               delete_to - message_id)

    else:
        msg.reply_text("Balas pesan untuk memilih dari mana mulai membersihkan.")

    return ""
Example #5
0
def main():
    # test_handler = CommandHandler("test", test)
    start_handler = CommandHandler(
        "start", start, pass_args=True, run_async=True
    )

    help_handler = CommandHandler("help", get_help)
    help_callback_handler = CallbackQueryHandler(
        help_button, pattern=r"help_", run_async=True
    )
    help_staff_handler = CommandHandler(
        "staffhelp",
        staff_help,
        filters=CustomFilters.support_filter,
        run_async=True,
    )

    settings_handler = CommandHandler("settings", get_settings, run_async=True)
    settings_callback_handler = CallbackQueryHandler(
        settings_button, pattern=r"stngs_", run_async=True
    )

    migrate_handler = MessageHandler(
        Filters.status_update.migrate, migrate_chats
    )
    is_chat_allowed_handler = MessageHandler(Filters.chat_type.groups, is_chat_allowed)

    # dispatcher.add_handler(test_handler)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(settings_handler)
    dispatcher.add_handler(help_callback_handler)
    dispatcher.add_handler(help_staff_handler)
    dispatcher.add_handler(settings_callback_handler)
    dispatcher.add_handler(migrate_handler)
    dispatcher.add_handler(is_chat_allowed_handler)
    dispatcher.add_error_handler(error_handler)

    if WEBHOOK:
        LOGGER.info("Using webhooks.")
        updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)

        if CERT_PATH:
            updater.bot.set_webhook(
                url=URL + TOKEN, certificate=open(CERT_PATH, "rb")
            )
        else:
            updater.bot.set_webhook(url=URL + TOKEN)

    else:
        LOGGER.info("Using long polling.")
        updater.start_polling(timeout=15, read_latency=5, clean=True)
        if MESSAGE_DUMP:
            updater.bot.send_message(
                chat_id=MESSAGE_DUMP, text="Sistem telah aktif..."
            )

    updater.idle()
Example #6
0
def help_button(update, context):
    query = update.callback_query
    user = update.effective_user
    mod_match = re.match(r"help_module\((.+?)\)", query.data)
    staff_match = re.match(r"help_staff", query.data)
    back_match = re.match(r"help_back", query.data)
    try:
        if mod_match:
            module = mod_match.group(1)
            text = ("Berikut adalah bantuan untuk modul *{}*e:\n".format(
                HELPABLE[module].__mod_name__) + HELPABLE[module].__help__)
            query.message.edit_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(text="⬅️ Kembali",
                                         callback_data="help_back")
                ]]),
            )

        elif staff_match:
            query.message.edit_text(
                text=STAFF_HELP_STRINGS,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(text="⬅️ Kembali",
                                         callback_data="help_back")
                ]]),
            )

        elif back_match:
            keyb = paginate_modules(0, HELPABLE, "help")
            # Add aditional button if staff user detected
            if (user.id in DEV_USERS or user.id in SUDO_USERS
                    or user.id in SUPPORT_USERS):
                keyb += [[
                    InlineKeyboardButton(text="Staff",
                                         callback_data="help_staff")
                ]]

            query.message.edit_text(
                text=HELP_STRINGS,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(keyb),
            )

        # ensure no spinny white circle
        context.bot.answer_callback_query(query.id)
    except Exception as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            query.message.edit_text(excp.message)
            LOGGER.exception("Exception in help buttons. %s", str(query.data))
Example #7
0
def error_handler(update, context):
    """Log the error and send a telegram message to notify the developer."""
    # Log the error before we do anything else, so we can see it even if something breaks.
    LOGGER.error(
        msg="Exception while handling an update:", exc_info=context.error
    )
    if isinstance(context.error, SQLAlchemyError) or isinstance(
        context.error, DBAPIError
    ):
        return
    # traceback.format_exception returns the usual python message about an exception, but as a
    # list of strings rather than a single string, so we have to join them together.
    else:
        tb_list = traceback.format_exception(
            None, context.error, context.error.__traceback__
        )
        tb_string = "".join(tb_list)

        # Build the message with some markup and additional information about what happened.
        # You might need to add some logic to deal with messages longer than the 4096 character limit.
        message = (
            f"An exception was raised while handling an update\n"
            f"update = {(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}"
            "\n\n"
            f"context.chat_data = {(str(context.chat_data))}\n\n"
            f"context.user_data = {(str(context.user_data))}\n\n"
            f"{(tb_string)}"
        )

        key = (
            requests.post(
                "https://nekobin.com/api/documents", json={"content": message}
            )
            .json()
            .get("result")
            .get("key")
        )
        markup = InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        "Nekobin Url", url=f"https://nekobin.com/{key}"
                    ),
                    InlineKeyboardButton(
                        "Nekobin Raw", url=f"https://nekobin.com/raw/{key}"
                    ),
                ]
            ]
        )

    # Finally, send the message
    context.bot.send_message(
        chat_id=MESSAGE_DUMP,
        text="kesalahan telah ditemukan di sini !!!",
        reply_markup=markup,
    )
Example #8
0
 def command_func(update, context, *args, **kwargs):
     try:
         context.bot.send_chat_action(
             chat_id=update.effective_chat.id, action=ChatAction.TYPING
         )
         return func(update, context, *args, **kwargs)
     except error.BadRequest as err:
         if str(err) == "Have no rights to send a message":
             LOGGER.warning("Bot dibisukan {} {}".format(
                     update.effective_message.chat.title,
                     update.effective_message.chat.id
                 )
             )
Example #9
0
def get_exception(excp, filt, chat):
    if excp.message == "Unsupported url protocol":
        return "Anda tampaknya mencoba menggunakan protokol URL yang tidak didukung. Telegram tidak mendukung kunci untuk beberapa protokol, seperti tg://. Silakan coba lagi!"
    elif excp.message == "Reply message not found":
        return "noreply"
    else:
        LOGGER.warning("Message %s could not be parsed", str(filt.reply))
        LOGGER.exception(
            "Could not parse filter %s in chat %s",
            str(filt.keyword),
            str(chat.id),
        )
        return ("Data ini tidak dapat dikirim karena formatnya salah.")
Example #10
0
def sed(update, context):
    sed_result = separate_sed(update.effective_message.text)
    if sed_result and update.effective_message.reply_to_message:
        if update.effective_message.reply_to_message.text:
            to_fix = update.effective_message.reply_to_message.text
        elif update.effective_message.reply_to_message.caption:
            to_fix = update.effective_message.reply_to_message.caption
        else:
            return

        repl, repl_with, flags = sed_result

        if not repl:
            update.effective_message.reply_to_message.reply_text(
                "Anda mencoba mengganti ... "
                " tidak ada apa-apa dengan sesuatu?")
            return

        try:

            # Protects bot from retarded geys -_-
            if infinite_checker(repl):
                return update.effective_message.reply_text(
                    "Usaha yang bagus -_-")

            if "i" in flags and "g" in flags:
                text = re.sub(repl, repl_with, to_fix, flags=re.I).strip()
            elif "i" in flags:
                text = re.sub(repl, repl_with, to_fix, count=1,
                              flags=re.I).strip()
            elif "g" in flags:
                text = re.sub(repl, repl_with, to_fix).strip()
            else:
                text = re.sub(repl, repl_with, to_fix, count=1).strip()
        except sre_constants.error:
            LOGGER.warning(update.effective_message.text)
            LOGGER.exception("SRE constant error")
            update.effective_message.reply_text(
                "Apakah kamu bahkan sed? Sepertinya tidak.")
            return

        # empty string errors -_-
        if len(text) >= telegram.MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(
                "Hasil dari perintah sed terlalu lama untuk \
                                                 telegram!")
        elif text:
            update.effective_message.reply_to_message.reply_text(text)
Example #11
0
    def setlog(update, context):
        message = update.effective_message
        chat = update.effective_chat
        if chat.type == chat.CHANNEL:
            message.reply_text(
                "Sekarang, teruskan /setlog ke grup yang ingin Anda kaitkan dengan saluran ini!"
            )

        elif message.forward_from_chat:
            db.set_chat_log_channel(chat.id, message.forward_from_chat.id)
            try:
                message.delete()
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception(
                        "Error deleting message in log channel. Should work anyway though."
                    )

            try:
                context.bot.send_message(
                    message.forward_from_chat.id,
                    "Saluran ini telah ditetapkan sebagai saluran log untuk {}.".format(
                        chat.title or chat.first_name
                    ),
                )
            except Unauthorized as excp:
                if (
                    excp.message
                    == "Forbidden: bot is not a member of the channel chat"
                ):
                    context.bot.send_message(
                        chat.id, "Berhasil menyetel saluran log!"
                    )
                else:
                    LOGGER.exception("ERROR in setting the log channel.")

            context.bot.send_message(chat.id, "Berhasil menyetel saluran log!")

        else:
            message.reply_text(
                "Langkah-langkah untuk mengatur saluran log adalah:\n"
                " - tambahkan bot ke saluran yang diinginkan\n"
                " - kirim /setlog ke saluran\n"
                " - meneruskan /setlog ke grup\n"
            )
Example #12
0
def migrate_chats(update, context):
    msg = update.effective_message  # type: Optional[Message]
    if msg.migrate_to_chat_id:
        old_chat = update.effective_chat.id
        new_chat = msg.migrate_to_chat_id
    elif msg.migrate_from_chat_id:
        old_chat = msg.migrate_from_chat_id
        new_chat = update.effective_chat.id
    else:
        return

    LOGGER.info("Migrating from %s, to %s", str(old_chat), str(new_chat))
    for mod in MIGRATEABLE:
        mod.__migrate__(old_chat, new_chat)

    LOGGER.info("Successfully migrated!")
    raise DispatcherHandlerStop
Example #13
0
def broadcast(update, context):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = users_db.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                context.bot.sendMessage(int(chat["chat_id"]), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning(
                    "Couldn't send broadcast to %s, group name %s",
                    str(chat["chat_id"]),
                    str(chat["chat_name"]),
                )

        update.effective_message.reply_text(
            "Siaran selesai. {} grup mungkin gagal menerima pesan "
            "karena ditendang.".format(failed))
Example #14
0
def snipe(update, context):
    args = context.args
    try:
        chat_id = str(args[0])
        del args[0]
    except (TypeError, IndexError):
        update.effective_message.reply_text(
            "Tolong beri saya obrolan untuk digemakan!")
    to_send = " ".join(args)
    if len(to_send) >= 2:
        try:
            context.bot.sendMessage(int(chat_id), str(to_send))
        except TelegramError:
            LOGGER.warning("Couldn't send to group %s", str(chat_id))
            update.effective_message.reply_text(
                "Tidak dapat mengirim pesan. Mungkin saya bukan bagian dari grup itu?"
            )
    else:
        update.effective_message.reply_text(
            "Kemana saya harus mengirim??\nBeri aku id obrolan!")
Example #15
0
    def setlog(update: Update, context: CallbackContext):
        bot = context.bot
        message = update.effective_message
        chat = update.effective_chat
        if chat.type == chat.CHANNEL:
            message.reply_text(
                "Now, forward the /setlog to the group you want to tie this channel to!"
            )

        elif message.forward_from_chat:
            sql.set_chat_log_channel(chat.id, message.forward_from_chat.id)
            try:
                message.delete()
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception(
                        "Error deleting message in log channel. Should work anyway though."
                    )

            try:
                bot.send_message(
                    message.forward_from_chat.id,
                    f"This channel has been set as the log channel for {chat.title or chat.first_name}."
                )
            except Unauthorized as excp:
                if excp.message == "Forbidden: bot is not a member of the channel chat":
                    bot.send_message(chat.id, "Successfully set log channel!")
                else:
                    LOGGER.exception("ERROR in setting the log channel.")

            bot.send_message(chat.id, "Successfully set log channel!")

        else:
            message.reply_text("The steps to set a log channel are:\n"
                               " - add bot to the desired channel\n"
                               " - send /setlog to the channel\n"
                               " - forward the /setlog to the group\n")
Example #16
0
    def setlog(update: Update, context: CallbackContext):
        bot = context.bot
        message = update.effective_message
        chat = update.effective_chat
        if chat.type == chat.CHANNEL:
            message.reply_text(
                "Sekarang, teruskan /setlog ke grup yang ingin Anda kaitkan dengan saluran ini!"
            )

        elif message.forward_from_chat:
            sql.set_chat_log_channel(chat.id, message.forward_from_chat.id)
            try:
                message.delete()
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception(
                        "Terjadi kesalahan saat menghapus pesan di saluran log. Bagaimanapun juga harus bekerja."
                    )

            try:
                bot.send_message(
                    message.forward_from_chat.id,
                    f"Saluran ini telah ditetapkan sebagai saluran log untuk {chat.title or chat.first_name}."
                )
            except Unauthorized as excp:
                if excp.message == "Forbidden: bot is not a member of the channel chat":
                    bot.send_message(chat.id, "Berhasil menyetel saluran log!")
                else:
                    LOGGER.exception("GAGAL dalam mengatur saluran log.")

            bot.send_message(chat.id, "Berhasil menyetel saluran log!")

        else:
            message.reply_text("Langkah-langkah untuk mengatur saluran log adalah:\n"
                               " - tambahkan bot ke saluran yang diinginkan\n"
                               " - kirim /setlog ke saluran\n"
                               " - meneruskan /setlog ke grup\n")
Example #17
0
    def send_log(bot: Bot, log_chat_id: str, orig_chat_id: str, result: str):
        try:
            bot.send_message(log_chat_id, result, parse_mode=ParseMode.HTML)
        except BadRequest as excp:
            if excp.message == "Chat not found":
                bot.send_message(
                    orig_chat_id,
                    "Saluran log ini telah dihapus - tidak disetel.",
                )
                db.stop_chat_logging(orig_chat_id)
            else:
                LOGGER.warning(excp.message)
                LOGGER.warning(result)
                LOGGER.exception("Could not parse")

                bot.send_message(
                    log_chat_id,
                    result
                    + "\n\nPemformatan telah dinonaktifkan karena kesalahan yang tidak terduga.",
                )
Example #18
0
    def send_log(context: CallbackContext, log_chat_id: str, orig_chat_id: str,
                 result: str):
        bot = context.bot
        try:
            bot.send_message(
                log_chat_id,
                result,
                parse_mode=ParseMode.HTML,
                disable_web_page_preview=True)
        except BadRequest as excp:
            if excp.message == "Chat not found":
                bot.send_message(
                    orig_chat_id,
                    "Saluran log ini telah dihapus - tidak disetel.")
                sql.stop_chat_logging(orig_chat_id)
            else:
                LOGGER.warning(excp.message)
                LOGGER.warning(result)
                LOGGER.exception("Could not parse")

                bot.send_message(
                    log_chat_id, result +
                    "\n\nPemformatan telah dinonaktifkan karena kesalahan yang tidak terduga."
                )
Example #19
0
    def send_log(context: CallbackContext, log_chat_id: str, orig_chat_id: str,
                 result: str):
        bot = context.bot
        try:
            bot.send_message(
                log_chat_id,
                result,
                parse_mode=ParseMode.HTML,
                disable_web_page_preview=True)
        except BadRequest as excp:
            if excp.message == "Chat not found":
                bot.send_message(
                    orig_chat_id,
                    "This log channel has been deleted - unsetting.")
                sql.stop_chat_logging(orig_chat_id)
            else:
                LOGGER.warning(excp.message)
                LOGGER.warning(result)
                LOGGER.exception("Could not parse")

                bot.send_message(
                    log_chat_id, result +
                    "\n\nFormatting has been disabled due to an unexpected error."
                )
Example #20
0
def send(update, message, keyboard, backup_message):
    chat = update.effective_chat
    cleanserv = sql.clean_service(chat.id)
    reply = update.message.message_id
    # Clean service welcome
    if cleanserv:
        try:
            dispatcher.bot.delete_message(chat.id, update.message.message_id)
        except BadRequest:
            pass
        reply = False
    try:
        msg = update.effective_message.reply_text(
            message,
            parse_mode=ParseMode.MARKDOWN,
            reply_markup=keyboard,
            reply_to_message_id=reply,
        )
    except BadRequest as excp:
        if excp.message == "Button_url_invalid":
            msg = update.effective_message.reply_text(
                markdown_parser(
                    backup_message +
                    "\nCatatan: pesan saat ini memiliki url yang tidak valid "
                    "di salah satu tombolnya. Harap perbarui."),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )
        elif excp.message == "Unsupported url protocol":
            msg = update.effective_message.reply_text(
                markdown_parser(
                    backup_message +
                    "\nCatatan: pesan saat ini memiliki tombol yang "
                    "gunakan protokol url yang tidak didukung oleh "
                    "telegram. Harap perbarui."),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )
        elif excp.message == "Wrong url host":
            msg = update.effective_message.reply_text(
                markdown_parser(
                    backup_message +
                    "\nCatatan: pesan saat ini memiliki beberapa url yang buruk. "
                    "Harap perbarui."),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )
            LOGGER.warning(message)
            LOGGER.warning(keyboard)
            LOGGER.exception(
                "Tidak bisa mengurai! mendapat kesalahan host url yang tidak valid"
            )
        elif excp.message == "Tidak punya hak untuk mengirim pesan":
            return
        else:
            msg = update.effective_message.reply_text(
                markdown_parser(backup_message +
                                "\nCatatan: Terjadi kesalahan saat mengirim "
                                "pesan khusus. Harap perbarui."),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )
            LOGGER.exception()
    return msg
Example #21
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")
Example #22
0
def extract_user_and_text(message: Message,
                          args: List[str]) -> (Optional[int], Optional[str]):
    prev_message = message.reply_to_message
    split_text = message.text.split(None, 1)

    if len(split_text) < 2:
        return id_from_reply(message)  # only option possible

    text_to_parse = split_text[1]

    text = ""

    entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
    if len(entities) > 0:
        ent = entities[0]
    else:
        ent = None

    # if entity offset matches (command end/text start) then all good
    if (entities and ent
            and ent.offset == len(message.text) - len(text_to_parse)):
        ent = entities[0]
        user_id = ent.user.id
        text = message.text[ent.offset + ent.length:]

    elif len(args) >= 1 and args[0][0] == "@":
        user = args[0]
        user_id = get_user_id(user)
        if not user_id:
            message.reply_text(
                "Saya tidak memiliki pengguna itu di db saya. Anda akan dapat berinteraksi dengan mereka jika "
                "Anda membalas pesan orang itu, atau meneruskan salah satu pesan pengguna itu."
            )
            return None, None

        else:
            user_id = user_id
            res = message.text.split(None, 2)
            if len(res) >= 3:
                text = res[2]

    elif len(args) >= 1 and args[0].isdigit():
        user_id = int(args[0])
        res = message.text.split(None, 2)
        if len(res) >= 3:
            text = res[2]

    elif prev_message:
        user_id, text = id_from_reply(message)

    else:
        return None, None

    try:
        message.bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message in ("User_id_invalid", "Chat not found"):
            message.reply_text(
                "Sepertinya saya belum pernah berinteraksi dengan pengguna ini sebelumnya - teruskan pesan dari "
                "mereka untuk memberi saya kendali! (seperti boneka voodoo, saya perlu sepotong agar bisa "
                "untuk menjalankan perintah tertentu...)")
        else:
            LOGGER.exception("Exception %s on user %s", excp.message, user_id)

        return None, None

    return user_id, text
Example #23
0
def ban(update, context):
    chat = update.effective_chat
    user = update.effective_user
    message = update.effective_message
    args = context.args

    if user_can_ban(chat, user, context.bot.id) is False:
        message.reply_text(
            "Anda tidak memiliki cukup hak untuk melarang pengguna!")
        return ""

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            "Setidaknya merujuk beberapa pengguna untuk melarang!")
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(
                "Saya tampaknya tidak dapat menemukan pengguna ini")
            return ""
        else:
            raise

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text(
            "Saya tidak akan melarang admin, jangan mengejek diri sendiri!")
        return ""

    if user_id == context.bot.id:
        message.reply_text(
            "Saya tidak akan melarang diri saya sendiri, apakah Anda gila atau tidak?"
        )
        return ""

    log = ("<b>{}:</b>"
           "\n#BANNED"
           "\n<b>Admin:</b> {}"
           "\n<b>User:</b> {} (<code>{}</code>)".format(
               html.escape(chat.title),
               mention_html(user.id, user.first_name),
               mention_html(member.user.id, member.user.first_name),
               member.user.id,
           ))
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        chat.kick_member(user_id)
        # context.bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie
        # sticker
        context.bot.sendMessage(
            chat.id,
            "biarkan {} berjalan di papan.".format(
                mention_html(member.user.id, member.user.first_name)),
            parse_mode=ParseMode.HTML,
        )
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text("Banned!", quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception(
                "ERROR banning user %s in chat %s (%s) due to %s",
                user_id,
                chat.title,
                chat.id,
                excp.message,
            )
            message.reply_text("Sial, saya tidak bisa mencekal pengguna itu.")

    return ""
Example #24
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")
Example #25
0
"""MongoDB database."""

from pymongo import MongoClient, collection

from kaga import MONGO_URI, LOGGER

LOGGER.info("Connecting to MongoDB")

DB_CLIENT = MongoClient(MONGO_URI)

_DB = DB_CLIENT["KagaRobot"]


def get_collection(name: str) -> collection:
    """Get the collection from database."""
    return _DB[name]
Example #26
0
def reply_filter(update, context):
    chat = update.effective_chat
    message = update.effective_message

    to_match = extract_text(message)
    if not to_match:
        return

    chat_filters = sql.get_chat_triggers(chat.id)
    for keyword in chat_filters:
        pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
        if re.search(pattern, to_match, flags=re.IGNORECASE):
            filt = sql.get_filter(chat.id, keyword)
            if filt.reply == "harus ada balasan baru":
                buttons = sql.get_buttons(chat.id, filt.keyword)
                keyb = build_keyboard_parser(context.bot, chat.id, buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                VALID_WELCOME_FORMATTERS = [
                    "first",
                    "last",
                    "fullname",
                    "username",
                    "id",
                    "chatname",
                    "mention",
                ]
                if filt.reply_text:
                    valid_format = escape_invalid_curly_brackets(
                        filt.reply_text, VALID_WELCOME_FORMATTERS)
                    if valid_format:
                        filtext = valid_format.format(
                            first=escape(message.from_user.first_name),
                            last=escape(message.from_user.last_name
                                        or message.from_user.first_name),
                            fullname=" ".join(
                                [
                                    escape(message.from_user.first_name),
                                    escape(message.from_user.last_name),
                                ] if message.from_user.last_name else
                                [escape(message.from_user.first_name)]),
                            username="******" + escape(message.from_user.username)
                            if message.from_user.username else mention_html(
                                message.from_user.id,
                                message.from_user.first_name,
                            ),
                            mention=mention_html(
                                message.from_user.id,
                                message.from_user.first_name,
                            ),
                            chatname=escape(message.chat.title)
                            if message.chat.type != "private" else escape(
                                message.from_user.first_name),
                            id=message.from_user.id,
                        )
                    else:
                        filtext = ""
                else:
                    filtext = ""

                if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        context.bot.send_message(
                            chat.id,
                            markdown_to_html(filtext),
                            reply_to_message_id=message.message_id,
                            parse_mode=ParseMode.HTML,
                            reply_markup=keyboard,
                        )
                    except BadRequest as excp:
                        error_catch = get_exception(excp, filt, chat)
                        if error_catch == "noreply":
                            try:
                                context.bot.send_message(
                                    chat.id,
                                    markdown_to_html(filtext),
                                    parse_mode=ParseMode.HTML,
                                    reply_markup=keyboard,
                                )
                            except BadRequest as excp:
                                LOGGER.exception("Error in filters: " +
                                                 excp.message)
                                send_message(
                                    update.effective_message,
                                    get_exception(excp, filt, chat),
                                )
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    get_exception(excp, filt, chat),
                                )
                            except BadRequest as excp:
                                LOGGER.exception("Failed to send message: " +
                                                 excp.message)
                else:
                    if (ENUM_FUNC_MAP[filt.file_type] ==
                            dispatcher.bot.send_sticker):
                        ENUM_FUNC_MAP[filt.file_type](
                            chat.id,
                            filt.file_id,
                            reply_to_message_id=message.message_id,
                            reply_markup=keyboard,
                        )
                    else:
                        ENUM_FUNC_MAP[filt.file_type](
                            chat.id,
                            filt.file_id,
                            caption=markdown_to_html(filtext),
                            reply_to_message_id=message.message_id,
                            parse_mode=ParseMode.HTML,
                            reply_markup=keyboard,
                        )
                break
            else:
                if filt.is_sticker:
                    message.reply_sticker(filt.reply)
                elif filt.is_document:
                    message.reply_document(filt.reply)
                elif filt.is_image:
                    message.reply_photo(filt.reply)
                elif filt.is_audio:
                    message.reply_audio(filt.reply)
                elif filt.is_voice:
                    message.reply_voice(filt.reply)
                elif filt.is_video:
                    message.reply_video(filt.reply)
                elif filt.has_markdown:
                    buttons = sql.get_buttons(chat.id, filt.keyword)
                    keyb = build_keyboard_parser(context.bot, chat.id, buttons)
                    keyboard = InlineKeyboardMarkup(keyb)

                    try:
                        send_message(
                            update.effective_message,
                            filt.reply,
                            parse_mode=ParseMode.MARKDOWN,
                            reply_markup=keyboard,
                        )
                    except BadRequest as excp:
                        if excp.message == "Unsupported url protocol":
                            try:
                                send_message(
                                    update.effective_message,
                                    "Anda tampaknya mencoba menggunakan protokol url yang tidak didukung. "
                                    "Telegram tidak mendukung tombol untuk beberapa protokol, seperti tg://. Silakan coba "
                                    "lagi...",
                                )
                            except BadRequest as excp:
                                LOGGER.exception("Error in filters: " +
                                                 excp.message)
                        elif excp.message == "Pesan balasan tidak ditemukan":
                            try:
                                context.bot.send_message(
                                    chat.id,
                                    filt.reply,
                                    parse_mode=ParseMode.MARKDOWN,
                                    reply_markup=keyboard,
                                )
                            except BadRequest as excp:
                                LOGGER.exception("Error in filters: " +
                                                 excp.message)
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    "Pesan ini tidak dapat dikirim karena formatnya salah.",
                                )
                            except BadRequest as excp:
                                LOGGER.exception("Error in filters: " +
                                                 excp.message)
                            LOGGER.warning(
                                "Message %s could not be parsed",
                                str(filt.reply),
                            )
                            LOGGER.exception(
                                "Could not parse filter %s in chat %s",
                                str(filt.keyword),
                                str(chat.id),
                            )

                else:
                    # LEGACY - all new filters will have has_markdown set to
                    # True.
                    try:
                        send_message(update.effective_message, filt.reply)
                    except BadRequest as excp:
                        LOGGER.exception("Error in filters: " + excp.message)
                break
Example #27
0
    dispatcher.add_handler(help_callback_handler)
    dispatcher.add_handler(help_staff_handler)
    dispatcher.add_handler(settings_callback_handler)
    dispatcher.add_handler(migrate_handler)
    dispatcher.add_handler(is_chat_allowed_handler)
    dispatcher.add_error_handler(error_handler)

    if WEBHOOK:
        LOGGER.info("Using webhooks.")
        updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)

        if CERT_PATH:
            updater.bot.set_webhook(url=URL + TOKEN,
                                    certificate=open(CERT_PATH, "rb"))
        else:
            updater.bot.set_webhook(url=URL + TOKEN)

    else:
        LOGGER.info("Using long polling.")
        updater.start_polling(timeout=15, read_latency=5, clean=True)
        if MESSAGE_DUMP:
            updater.bot.send_message(chat_id=MESSAGE_DUMP,
                                     text="Sistem telah aktif...")

    updater.idle()


if __name__ == "__main__":
    LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES))
    main()
Example #28
0
def temp_ban(update, context):
    chat = update.effective_chat
    user = update.effective_user
    message = update.effective_message
    args = context.args

    if user_can_ban(chat, user, context.bot.id) is False:
        message.reply_text(
            "Anda tidak memiliki cukup hak untuk memblokir seseorang untuk sementara!"
        )
        return ""

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            "Hai kawan! setidaknya rujuk beberapa pengguna untuk dicekal...")
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(
                "Sepertinya saya tidak dapat menemukan pengguna ini")
            return ""
        else:
            raise

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text("Wow! mari kita mulai memblokir Admin sendiri?...")
        return ""

    if user_id == context.bot.id:
        message.reply_text(
            "Saya tidak akan melarang diri saya sendiri, apakah Anda gila atau tidak?"
        )
        return ""

    if not reason:
        message.reply_text(
            "Anda belum menentukan waktu untuk mencekal pengguna ini!")
        return ""

    split_reason = reason.split(None, 1)

    time_val = split_reason[0].lower()
    if len(split_reason) > 1:
        reason = split_reason[1]
    else:
        reason = ""

    bantime = extract_time(message, time_val)

    if not bantime:
        return ""

    log = ("<b>{}:</b>"
           "\n#TEMP BANNED"
           "\n<b>Admin:</b> {}"
           "\n<b>User:</b> {} (<code>{}</code>)"
           "\n<b>Time:</b> {}".format(
               html.escape(chat.title),
               mention_html(user.id, user.first_name),
               mention_html(member.user.id, member.user.first_name),
               member.user.id,
               time_val,
           ))
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        chat.kick_member(user_id, until_date=bantime)
        # context.bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie
        # sticker
        message.reply_text(
            "Dilarang! Pengguna akan diblokir {}.".format(time_val))
        return log

    except BadRequest as excp:
        if excp.message == "Pesan balasan tidak ditemukan":
            # Do not reply
            message.reply_text(
                "Selamat tinggal .. kita akan bertemu setelah {}.".format(
                    time_val),
                quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception(
                "ERROR banning user %s in chat %s (%s) due to %s",
                user_id,
                chat.title,
                chat.id,
                excp.message,
            )
            message.reply_text("Sial, saya tidak bisa mencekal pengguna itu.")

    return ""
Example #29
0
    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [
        basename(f)[:-3] for f in mod_paths
        if isfile(f) and f.endswith(".py") and not f.endswith("__init__.py")
    ]

    if LOAD or NO_LOAD:
        to_load = LOAD
        if to_load:
            if not all(
                    any(mod == module_name for module_name in all_modules)
                    for mod in to_load):
                LOGGER.error("Invalid loadorder names. Quitting.")
                sys.exit(1)

        else:
            to_load = all_modules

        if NO_LOAD:
            LOGGER.info("Not loading: {}".format(NO_LOAD))
            return [item for item in to_load if item not in NO_LOAD]

        return to_load

    return all_modules


ALL_MODULES = sorted(__list_all_modules())
LOGGER.info("Modules to load: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]
Example #30
0
def settings_button(update, context):
    query = update.callback_query
    user = update.effective_user
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = context.bot.get_chat(chat_id)
            text = "*{}* memiliki pengaturan berikut untuk modul *{}*:\n\n".format(
                escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__
            ) + CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id)
            query.message.reply_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(
                        text="Kembali",
                        callback_data="stngs_back({})".format(chat_id),
                    )
                ]]),
            )

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = context.bot.get_chat(chat_id)
            query.message.reply_text(
                "Halo yang disana! Ada beberapa setelan untuk {} - lanjutkan dan pilih apa "
                "bikin Anda tertarik.".format(chat.title),
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(curr_page - 1,
                                     CHAT_SETTINGS,
                                     "stngs",
                                     chat=chat_id)),
            )

        elif next_match:
            chat_id = next_match.group(1)
            next_page = int(next_match.group(2))
            chat = context.bot.get_chat(chat_id)
            query.message.reply_text(
                "Halo yang disana! Ada beberapa setelan untuk {} - lanjutkan dan pilih apa "
                "bikin Anda tertarik.".format(chat.title),
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(next_page + 1,
                                     CHAT_SETTINGS,
                                     "stngs",
                                     chat=chat_id)),
            )

        elif back_match:
            chat_id = back_match.group(1)
            chat = context.bot.get_chat(chat_id)
            query.message.reply_text(
                text=
                "Halo yang disana! Ada beberapa setelan untuk {} - lanjutkan dan pilih apa "
                "bikin Anda tertarik.".format(escape_markdown(chat.title)),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id)),
            )

        # ensure no spinny white circle
        query.message.delete()
        context.bot.answer_callback_query(query.id)
    except Exception as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            query.message.edit_text(excp.message)
            LOGGER.exception("Exception in settings buttons. %s",
                             str(query.data))