Пример #1
0
    def set_top_results(self, update: Update,
                        context: CallbackContext) -> None:
        assert update.effective_message is not None  # for mypy, real check is in decorator

        chat_id = update.effective_message.chat_id
        value = self.sanitize_digit(context.args, 3, 10)

        if value != -1:
            is_same = SearchConfigs.check_if_same_value(chat_id, value, "n")
            if is_same:
                update.effective_message.reply_text(
                    TextRepo.MSG_SAME_VALUE.format(value))
                return
            SearchConfigs.set_user_cfg(chat_id, value, "n")
            update.effective_message.reply_text(
                TextRepo.MSG_SET_FIRST_N.format(value))
Пример #2
0
def test_set_user_cfg():
    SearchConfigs.set_user_cfg(1, 999, 'n')
    SearchConfigs.set_user_cfg(1, 99, 'm')

    assert SearchConfigs.get_user_show_first_n(1) == 999
    assert SearchConfigs.get_user_cfg(1).m == 99

    with pytest.raises(ValueError):
        SearchConfigs.set_user_cfg(1, 999, 'w')
Пример #3
0
    def show_my_config(self, update: Update, context: CallbackContext) -> None:
        assert update.effective_message is not None  # for mypy, real check is in decorator

        chat_id = update.effective_message.chat_id

        cfg_user = SearchConfigs.get_user_cfg(chat_id)
        update.effective_message.reply_text(
            TextRepo.MSG_PRINT_CFG.format(cfg_user.n, cfg_user.m))
Пример #4
0
def test_get_user_cfg():
    assert isinstance(SearchConfigs.get_user_cfg(1), UserConfig)
    assert isinstance(SearchConfigs.get_user_cfg(2), UserConfig)
    assert isinstance(SearchConfigs.get_user_cfg(3), UserConfig)

    assert SearchConfigs.get_user_cfg(1).n == 5
    assert SearchConfigs.get_user_cfg(2).n == 10
    assert SearchConfigs.get_user_cfg(3).n == 3
Пример #5
0
def test_normalize_user_data():
    data = SearchConfigs.normalize_user_data()

    one_hashed = sha1(bytes(1)).hexdigest()
    two_hashed = sha1(bytes(2)).hexdigest()
    three_hashed = sha1(bytes(3)).hexdigest()

    assert data[one_hashed]['n'] == SearchConfigs.get_user_show_first_n(1)
    assert data[one_hashed]['m'] == SearchConfigs.get_user_show_min_threshold(1)

    assert data[two_hashed]['n'] == SearchConfigs.get_user_show_first_n(2)
    assert data[two_hashed]['m'] == SearchConfigs.get_user_show_min_threshold(2)

    assert data[three_hashed]['n'] == SearchConfigs.get_user_show_first_n(3)
    assert data[three_hashed]['m'] == SearchConfigs.get_user_show_min_threshold(3)
Пример #6
0
    def search(self, update: Update, context: CallbackContext) -> None:
        assert update.effective_message is not None  # for mypy, real check is in decorator
        chat_id: int = update.effective_message.chat_id

        is_admin = self.is_admin(chat_id)

        if not is_admin:
            self.call_counter.add_call()
        if not context.args:
            update.effective_message.reply_text(
                TextRepo.MSG_SEARCH_EMPTY_INPUT)
            return

        text: List[str] = context.args
        user_cfg: UserConfig = SearchConfigs.get_user_cfg(chat_id)

        message, text = self.episode_handler.search_text_in_episodes(
            " ".join(text), user_cfg.n, MINIMUM_SCORE, is_admin)

        update.effective_message.reply_text(message,
                                            parse_mode=ParseMode.HTML,
                                            disable_web_page_preview=True)
Пример #7
0
def run_before():
    SearchConfigs.DUMP_FOLDER = os.path.join(SRC_TEST_FOLDER, 'resources/usr_cfg_test')
    SearchConfigs.USERS_CFG_FILEPATH = os.path.join(SRC_TEST_FOLDER, 'resources/usr_cfg_test', 'users_cfg.json')
    SearchConfigs.set_user_cfg(1, 5, 'n')
    SearchConfigs.set_user_cfg(1, 1, 'm')
    SearchConfigs.set_user_cfg(2, 10, 'n')
    SearchConfigs.set_user_cfg(2, 30, 'm')
    SearchConfigs.set_user_cfg(3, 3, 'n')
    SearchConfigs.set_user_cfg(3, 90, 'm')

    yield
    SearchConfigs.reset_user_data()
    filelist = [f for f in os.listdir(SearchConfigs.DUMP_FOLDER)]
    for f in filelist:
        os.remove(os.path.join(SearchConfigs.DUMP_FOLDER, f))
Пример #8
0
def test_dump_data():
    one_hashed = sha1(bytes(1)).hexdigest()
    two_hashed = sha1(bytes(2)).hexdigest()

    SearchConfigs.dump_data()

    SearchConfigs.set_user_cfg(1, 10, 'n')
    SearchConfigs.set_user_cfg(1, 20, 'm')
    SearchConfigs.set_user_cfg(2, 30, 'n')
    SearchConfigs.set_user_cfg(2, 40, 'm')

    SearchConfigs.dump_data()

    SearchConfigs.set_user_cfg(1, 999, 'n')
    SearchConfigs.set_user_cfg(1, 998, 'm')
    SearchConfigs.set_user_cfg(2, 111, 'n')
    SearchConfigs.set_user_cfg(2, 112, 'm')

    assert SearchConfigs.get_user_show_first_n(1) == 999
    assert SearchConfigs.get_user_show_min_threshold(1) == 998

    assert SearchConfigs.get_user_show_first_n(2) == 111
    assert SearchConfigs.get_user_show_min_threshold(2) == 112

    SearchConfigs.init_data()

    assert SearchConfigs.get_user_show_first_n(1) == 10
    assert SearchConfigs.get_user_show_min_threshold(1) == 20

    assert SearchConfigs.get_user_show_first_n(2) == 30
    assert SearchConfigs.get_user_show_min_threshold(2) == 40
Пример #9
0
def test_chek_if_same_value():
    assert SearchConfigs.check_if_same_value(1, 5, 'n')
    assert SearchConfigs.check_if_same_value(1, 1, 'm')
    assert not SearchConfigs.check_if_same_value(1, 999, 'n')
    assert not SearchConfigs.check_if_same_value(1, 999, 'm')

    assert SearchConfigs.check_if_same_value(2, 10, 'n')
    assert SearchConfigs.check_if_same_value(2, 30, 'm')
    assert not SearchConfigs.check_if_same_value(2, 999, 'n')
    assert not SearchConfigs.check_if_same_value(2, 999, 'm')

    assert SearchConfigs.check_if_same_value(3, 3, 'n')
    assert SearchConfigs.check_if_same_value(3, 90, 'm')
    assert not SearchConfigs.check_if_same_value(3, 999, 'n')
    assert not SearchConfigs.check_if_same_value(3, 999, 'm')

    with pytest.raises(ValueError):
        SearchConfigs.check_if_same_value(1, 5, 'w')
Пример #10
0
def test_get_user_show_min_threshold():
    assert SearchConfigs.get_user_show_min_threshold(1) == 1
    assert SearchConfigs.get_user_show_min_threshold(2) == 30
    assert SearchConfigs.get_user_show_min_threshold(3) == 90
Пример #11
0
def test_get_user_show_first_n():
    assert SearchConfigs.get_user_show_first_n(1) == 5
    assert SearchConfigs.get_user_show_first_n(2) == 10
    assert SearchConfigs.get_user_show_first_n(3) == 3
Пример #12
0
 def dump_data(self, update: Update, context: CallbackContext):
     res_dump_cfg = SearchConfigs.dump_data()
     res_dump_search = self.episode_handler.save_searches()
     res_dump_call = self.call_counter.dump_data()
     return zip([res_dump_cfg, res_dump_search, res_dump_call],
                ['dump_cfg', 'dump_search', 'dump_call'])
Пример #13
0
def main():

    init_message_config = f"Booting up using {os.environ.get('PPB_ENV')} version"
    logger.info(init_message_config)

    SearchConfigs.init_data()

    client = SpreakerAPIClient(config["SECRET"].get("api_token"))
    power_pizza = Show(config["POWER_PIZZA"].get("SHOW_ID"))

    TOKEN_BOT = config["SECRET"].get("bot_token")
    q = mq.MessageQueue(all_burst_limit=29, all_time_limit_ms=1017)
    request = Request(con_pool_size=8)
    testbot = MQBot(TOKEN_BOT, request=request, mqueue=q)
    updater = extUpdater(bot=testbot, use_context=True)

    for admin in LIST_OF_ADMINS:
        updater.bot.send_message(chat_id=admin, text=init_message_config)

    episode_handler = EpisodeHandler(client, power_pizza, WordCounter())
    episode_handler.add_episodes_to_show()

    facade_bot = FacadeBot(episode_handler)

    dp = updater.dispatcher
    dp.add_handler(CommandHandler("s", facade_bot.search))
    dp.add_handler(CommandHandler("top", facade_bot.set_top_results))
    dp.add_handler(CommandHandler("last", facade_bot.get_last_ep))
    dp.add_handler(CommandHandler("get", facade_bot.get_ep))
    dp.add_handler(CommandHandler("random", facade_bot.get_ep_random))
    dp.add_handler(CommandHandler("host", facade_bot.get_eps_host))
    dp.add_handler(CommandHandler("hostf", facade_bot.get_eps_host))
    dp.add_handler(CommandHandler("hosta", facade_bot.get_eps_host))
    dp.add_handler(
        CommandHandler("dump",
                       facade_bot.dump_data,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    # analytics commands
    dp.add_handler(
        CommandHandler("nu",
                       facade_bot.get_users_total_n,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("ncw",
                       facade_bot.get_most_common_words,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("neps",
                       facade_bot.get_episodes_total_n,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("qry",
                       facade_bot.get_daily_logs,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    dp.add_handler(
        CommandHandler("memo",
                       facade_bot.memo,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    dp.add_handler(CommandHandler("start", facade_bot.start))
    dp.add_handler(CommandHandler("help", facade_bot.help))

    dp.add_error_handler(error_callback)

    facade_bot.schedule_jobs(dp.job_queue)

    def stop_and_restart():
        logger.info("Stop and restarting bot...")
        updater.stop()
        os.execl(sys.executable, sys.executable, *sys.argv)

    def kill_bot():
        logger.info("Shutting down bot...")
        updater.stop()

    @restricted
    def restart(update, context):
        result_dump = facade_bot.dump_data(update, context)

        for res_dump, name_dump in result_dump:
            update.message.reply_text(f"{name_dump} save " +
                                      "success." if res_dump else "fail.")

        update.message.reply_text("Bot is restarting...")
        Thread(target=stop_and_restart).start()

    @restricted
    def kill(update, context):
        result_dump = facade_bot.dump_data(update, context)

        for res_dump, name_dump in result_dump:
            update.message.reply_text(f"{name_dump} save " +
                                      "success." if res_dump else "fail.")

        update.message.reply_text("See you, space cowboy...")
        Thread(target=kill_bot).start()

    # handler restarter
    dp.add_handler(
        CommandHandler("restart",
                       restart,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("killme",
                       kill,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    updater.start_polling()

    updater.idle()