Exemplo n.º 1
0
 def update_competitor_table_record(competitor: Competitor, all_data=None):
     try:
         cfg = get_config()
         if not all_data:
             data = UsersSheet.get_all_users()
         else:
             data = all_data
         updated = False
         row_number = 1
         for row_number, row in enumerate(data, 2):
             if row[0] == competitor.legacy_number and row[1] == competitor.name:
                 update_data(
                     cfg.spreadsheet_id,
                     f'{cfg.spreadsheet_users_sheet}!C{row_number}:G',
                     values=[
                         [
                             Competitor.status_code_to_str_dict[competitor.status],
                             competitor.level or '',
                             competitor.matches or 0,
                             competitor.wins or 0,
                             competitor.losses or 0
                         ]
                     ]
                 )
                 # UsersSheet.update_competitor_performance_from_table(
                 #     competitor,
                 #     row_number
                 # )
                 updated = True
                 break
         if not updated:
             logger.error(f"Cannot update record for competitor {competitor.name} ({competitor.legacy_number}) - table record not found")
     except:
         logger.exception('Exception occurred while updating competitor in gsheet')
Exemplo n.º 2
0
 def update_competitor_status(competitor: Competitor, upsert=False, all_data=None):
     try:
         cfg = get_config()
         if not all_data:
             data = UsersSheet.get_all_users()
         else:
             data = all_data
         updated = False
         row_number = 1
         for row_number, row in enumerate(data, 2):
             if row[0] == competitor.legacy_number and row[1] == competitor.name:
                 update_data(
                     cfg.spreadsheet_id,
                     f'{cfg.spreadsheet_users_sheet}!C{row_number}',
                     values=[
                         [
                             Competitor.status_code_to_str_dict[competitor.status],
                         ]
                     ]
                 )
                 updated = True
                 break
         if not updated:
             if not upsert:
                 logger.error(f"Cannot update record for competitor {competitor.name} ({competitor.legacy_number}) - table record not found")
             else:
                 logger.warning(f"Cannot update record for competitor {competitor.name} ({competitor.legacy_number}) - table record not found. Performing upsert")
                 UsersSheet.insert_competitor_in_table(competitor, at_row=row_number+1)
     except:
         logger.exception('Exception occurred while updating competitor status in gsheet')
Exemplo n.º 3
0
 def update_competitor_performance_from_table(competitor: Competitor, row=None):
     try:
         if row is None:
             data = UsersSheet.get_all_users()
             for row_number, row_data in enumerate(data, 2):
                 if row_data[0] == competitor.legacy_number and row_data[1] == competitor.name:
                     row = row_number
                     competitor.performance = to_int(row_data[7])
                     competitor.save()
                     break
             if row is None:
                 logger.error(f'Cannot get new performance for competitor: {competitor} - cannot found record in gsheet')
             return
         cfg = get_config()
         new_perf = retrieve_data(
             cfg.spreadsheet_id,
             f'{cfg.spreadsheet_users_sheet}!H{row}'
         )
         new_perf = to_int(new_perf, None)
         if new_perf is None:
             logger.error(f'Cannot get new performance for competitor: {competitor}')
             return
         competitor.performance = new_perf
         competitor.save()
     except:
         logger.exception(f'Error occurred while updating performance for competitor: {competitor}')
Exemplo n.º 4
0
    def glog(text: str, severity=logging.INFO, at_row=None):
        try:
            cfg = get_config()
            if not cfg.spreadsheet_logs_sheet:
                hr_logger.error(
                    'Не вдалося надіслати лог в гуглтаблицю - у налаштуваннях відсутня назва листа'
                )
                logger.error(
                    'Cannot insert log into a google sheet - sheet name is missing'
                )
                return

            if at_row is None:
                stored_logs = LogsSheet.get_all_logs()
                if stored_logs is None:
                    stored_logs = []
                at_row = len(stored_logs) + 2

            update_data(
                cfg.spreadsheet_id,
                f'{cfg.spreadsheet_logs_sheet}!A{at_row}:C',
                values=[[
                    datetime.now(tz=_k_tz).strftime('%d/%m/%Y %H:%M:%S (%Z)'),
                    _logging_severity_to_str_dict[severity], text
                ]])
        except:
            logger.exception(
                'Exception occurred while uploading log to gsheet')
Exemplo n.º 5
0
 def __get_state(self, name):
     if callable(name):
         name = name.__name__
     ret = self.__states.get(name)
     if ret is None:
         logger.error('No state with name "{}"'.format(name))
         return False, self.__states[self.__start_state], self.__start_state
     return True, ret, name
Exemplo n.º 6
0
 def register_my_win(self, message: Message, user: User, bot: TeleBot,
                     competitor: Competitor):
     res = user.check_result()
     if res.player_a == competitor:
         res.result = RESULT.A_WINS
     elif res.player_b == competitor:
         res.result = RESULT.B_WINS
     else:
         logger.error(
             f'Competitor {competitor.name} record vanished from results record {str(res.id)}'
         )
         return RET.GO_TO_STATE, 'MenuState', message, user
     res.save()
     return self.process_result(message, user, bot, competitor, True)
Exemplo n.º 7
0
def get_menu_keyboard(**kwargs):
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)

    status = kwargs.get('status', COMPETITOR_STATUS.UNAUTHORIZED)
    if status == COMPETITOR_STATUS.UNAUTHORIZED:
        logger.error('Not provided status for keyboard in menu state. Asserting')
        assert False

    if status == COMPETITOR_STATUS.INACTIVE:
        keyboard.row(get_translation_for('menu_moved_to_inactive_pseudo1_btn'))
        keyboard.row(get_translation_for('menu_moved_to_inactive_pseudo2_btn'))

    if status in (COMPETITOR_STATUS.ACTIVE, COMPETITOR_STATUS.PASSIVE):
        keyboard.row(get_translation_for('menu_info_btn'),
                     get_translation_for('menu_create_challenge_btn'))
        keyboard.row(get_translation_for('menu_go_on_vacation_btn'),
                     get_translation_for('menu_go_on_sick_leave_btn'))
    elif status == COMPETITOR_STATUS.CHALLENGE_INITIATED:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('menu_cancel_challenge_request_btn'))
    elif status == COMPETITOR_STATUS.CHALLENGE_NEED_RESPONSE:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('menu_reply_to_challenge_request_btn'))
    elif status == COMPETITOR_STATUS.CHALLENGE_STARTER:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('menu_submit_challenge_results_btn'))
        keyboard.row(get_translation_for('menu_cancel_challenge_btn'))
    elif status == COMPETITOR_STATUS.CHALLENGE_RECEIVER:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('menu_submit_challenge_results_btn'))
    elif status == COMPETITOR_STATUS.CHALLENGE_NEED_CANCELLATION_CONFIRMATION:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('challenge_cancel_request_opponent_confirm_btn'))
        keyboard.row(get_translation_for('challenge_cancel_request_opponent_dismiss_btn'))
    elif status == COMPETITOR_STATUS.CHALLENGE_NEED_RESULTS_CONFIRMATION:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('menu_accept_challenge_results_btn'))
    elif status == COMPETITOR_STATUS.VACATION:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('menu_end_vacation_btn'))
    elif status == COMPETITOR_STATUS.INJUIRY:
        keyboard.row(get_translation_for('menu_info_btn'))
        keyboard.row(get_translation_for('menu_end_sick_leave_btn'))
    return keyboard
Exemplo n.º 8
0
 def register_opponent_wins(self, message: Message, user: User,
                            bot: TeleBot, competitor: Competitor):
     res = user.check_result()
     opponent, opponent_user = get_opponent_and_opponent_user(competitor)
     if not opponent or not opponent_user:
         return teardown_challenge(
             competitor, message, user, bot,
             'challenge_confirm_cannot_find_opponent_msg' if not opponent
             else 'challenge_confirm_cannot_fin_opponents_user_msg')
     if res.player_a == opponent:
         res.result = RESULT.A_WINS
     elif res.player_b == opponent:
         res.result = RESULT.B_WINS
     else:
         logger.error(
             f'Opponent {opponent.name} record vanished from results record {str(res.id)}'
         )
         return RET.GO_TO_STATE, 'MenuState', message, user
     res.save()
     return self.process_result(message, user, bot, competitor, True)
Exemplo n.º 9
0
 def entry(self,
           message: Message,
           user: User,
           bot: TeleBot,
           competitor: Competitor = None):
     if competitor is None:
         competitor = user.check_association()
     if competitor.status not in (COMPETITOR_STATUS.CHALLENGE_STARTER,
                                  COMPETITOR_STATUS.CHALLENGE_RECEIVER):
         logger.error(
             f"User ({user.user_id}) - {competitor.name} entered ChallengeSendResultsState with incorrect competitor status {competitor.status}"
         )
         return RET.GO_TO_STATE, 'MenuState', message, user
     opponent, opponent_user = get_opponent_and_opponent_user(competitor)
     if not opponent or not opponent_user:
         return teardown_challenge(
             competitor, message, user, bot,
             'challenge_confirm_cannot_find_opponent_msg' if not opponent
             else 'challenge_confirm_cannot_fin_opponents_user_msg')
     if not user.check_result():
         res = Result(player_a=competitor,
                      player_b=opponent,
                      confirmed=False)
         res.save()
         user.current_result = res
         user.save()
     elif not user.check_result().sent:
         bot.send_message(user.user_id,
                          get_translation_for('results_enter_results_msg'))
     else:
         bot.send_message(message.chat.id,
                          get_translation_for('results_already_sent_msg'))
         return RET.GO_TO_STATE, 'MenuState', message, user
     return self.process_result(message,
                                user,
                                bot,
                                competitor,
                                final=user.check_result().result
                                is not None)
Exemplo n.º 10
0
 def daily_task():
     now = datetime.now(tz=tz)
     tbot = None
     bconfig = get_config()
     for competitor in Competitor.objects(
             status=COMPETITOR_STATUS.VACATION):
         if competitor.vacation_started_at:
             delta = now - mongo_time_to_local(
                 competitor.vacation_started_at, tz)
             delta = delta.total_seconds()
             if competitor.used_vacation_time is not None:
                 delta += competitor.used_vacation_time
             if timedelta(seconds=delta).days > bconfig.vacation_time:
                 competitor.change_status(competitor.previous_status
                                          or COMPETITOR_STATUS.ACTIVE)
                 competitor.save()
                 relevant_user: User = User.objects(
                     associated_with=competitor).first()
                 if relevant_user is not None:
                     if not tbot:
                         tbot = TeleBot(BOT_TOKEN, threaded=False)
                     smwae_check(
                         relevant_user.user_id,
                         get_translation_for('menu_on_vacation_end_msg'),
                         relevant_user,
                         reply_markup=get_menu_keyboard(
                             status=competitor.status))
             else:
                 competitor.vacation_started_at = now
                 competitor.used_vacation_time = delta
                 competitor.save()
         else:
             logger.error(
                 f"Cannot find vacation_started_at for competitor {competitor.name} (on vacation). Saved current time"
             )
             competitor.vacation_started_at = now
             competitor.save()
Exemplo n.º 11
0
    def upload_result(result: Result, at_row=None):
        try:
            cfg = get_config()
            if not cfg.spreadsheet_results_sheet:
                hr_logger.error(
                    'Не вдалося надіслати результат матчу в гуглтаблицю - у налаштуваннях відсутня назва листа')
                logger.error('Cannot insert result into a google sheet - sheet name is missing')
                return

            if at_row is None:
                results = ResultsSheet.get_all_successful_results()
                if results is None:
                    results = []
                at_row = len(results) + 2

            if result.result in (RESULT.A_WINS, RESULT.B_WINS):
                winner = result.player_a.fetch() if result.result == RESULT.A_WINS else result.player_b.fetch()
                looser = result.player_b.fetch() if result.result == RESULT.A_WINS else result.player_a.fetch()
                score = result.repr_score()

                update_data(
                    cfg.spreadsheet_id,
                    f'{cfg.spreadsheet_results_sheet}!A{at_row}:E',
                    values=[
                        [
                            mongo_time_to_local(result.date, tz=_k_tz).strftime('%d/%m/%Y'),
                            winner.name,
                            score,
                            looser.name,
                            result.level_change or '-'
                        ]
                    ]
                )
            else:
                logger.error(f"Wrong method called for result {result.id}. Call upload_canceled_result instead")
        except:
            logger.exception('Exception occurred while uploading match result')
Exemplo n.º 12
0
 def end_vacation(self, message: Message, user: User, bot: TeleBot, competitor: Competitor):
     if competitor.status != COMPETITOR_STATUS.VACATION:
         return RET.OK, None, None, None
     if not competitor.vacation_started_at:
         logger.error(f"Cannot calculate user's ({user.user_id}) time on vacation - cannot find vacation_started_at")
         delta = 0
     else:
         tz = timezone('Europe/Kiev')
         now = datetime.now(tz=tz)
         delta = now - mongo_time_to_local(competitor.vacation_started_at, tz)
         delta = delta.total_seconds()
     if competitor.used_vacation_time is None:
         competitor.used_vacation_time = delta
     else:
         competitor.used_vacation_time += delta
     competitor.change_status(competitor.previous_status)
     competitor.save()
     bot.send_message(
         message.chat.id,
         get_translation_for('menu_on_vacation_end_manual_msg'),
         reply_markup=self.__base_keyboard(status=competitor.status)
     )
     LogsSheet.glog(get_translation_for('gsheet_log_player_finished_vacation').format(competitor.name))
     return RET.OK, None, None, None
Exemplo n.º 13
0
    def upload_canceled_result(winner: Competitor, looser: Competitor, level_change=None, was_dismissed=False,
                               was_ignored=False, at_row=None):
        try:
            if not was_dismissed and not was_ignored:
                logger.error(
                    'upload_canceled_result called without both was_dismissed and was_ignored - one must be set')
                return
            if was_dismissed and was_ignored:
                logger.error(
                    'upload_canceled_result called with both was_dismissed and was_ignored - only one must be set')
                return

            cfg = get_config()
            if not cfg.spreadsheet_results_sheet:
                hr_logger.error(
                    'Не вдалося надіслати результат матчу в гуглтаблицю - у налаштуваннях відсутня назва листа')
                logger.error('Cannot insert result into a google sheet - sheet name is missing')
                return

            if not at_row:
                results = ResultsSheet.get_all_canceled_results()
                if results is None:
                    results = []
                at_row = len(results) + 2

            t = ''
            if was_ignored:
                t = get_translation_for('gsheet_technical_win_ignored_str')
            if was_dismissed:
                t = get_translation_for('gsheet_technical_win_dismissed_str')

            update_data(
                cfg.spreadsheet_id,
                f'{cfg.spreadsheet_results_sheet}!H{at_row}:L',
                values=[
                    [
                        datetime.now(tz=_k_tz).strftime('%d/%m/%Y'),
                        looser.name,
                        t,
                        winner.name,
                        level_change or '-'
                    ]
                ]
            )
        except:
            logger.exception('Exception occurred while uploading canceled match results')
Exemplo n.º 14
0
    def check_challenges():
        bconfig = get_config()
        n = datetime.now(tz=tz)
        tbot = None
        for competitor in Competitor.objects(
                status=COMPETITOR_STATUS.CHALLENGE_NEED_RESPONSE):
            try:
                if not competitor.latest_challenge_received_at:
                    logger.error(
                        f'Competitor {competitor.name} {competitor.legacy_number} has no latest_challenge_received_at'
                    )
                    competitor.latest_challenge_received_at = datetime.now(
                        tz=tz)
                    competitor.save()
                    continue
                cs = mongo_time_to_local(
                    competitor.latest_challenge_received_at, tz)
                if (n - cs) > timedelta(days=max(
                        0, bconfig.time_to_accept_challenge -
                        bconfig.accept_challenge_reminder
                )) and not competitor.challenge_remainder_sent:
                    if tbot is None:
                        tbot = TeleBot(PROJECT_NAME, threaded=False)
                    cuser = User.objects(associated_with=competitor).first()
                    if cuser is None:
                        continue
                    if not smwae_check(
                            cuser.user_id,
                            get_translation_for(
                                'remainder_challenge_accept_msg').format(
                                    bconfig.accept_challenge_reminder), cuser):
                        opponent, opponent_user = get_opponent_and_opponent_user(
                            competitor)
                        if opponent and opponent_user:
                            teardown_challenge(
                                opponent, None, opponent_user, tbot,
                                'error_bot_blocked_by_opponent_challenge_canceled_msg'
                            )
                            continue
                    competitor.reload()
                    competitor.challenge_remainder_sent = True
                    competitor.save()
                elif (n -
                      cs) > timedelta(days=bconfig.time_to_accept_challenge):
                    if tbot is None:
                        tbot = TeleBot(PROJECT_NAME, threaded=False)
                    cuser = User.objects(associated_with=competitor).first()
                    skip_comp = False
                    if cuser is None:
                        skip_comp = True

                    opponent_user: User
                    opponent, opponent_user = get_opponent_and_opponent_user(
                        competitor)

                    prev_level, new_level = None, None
                    level_change = None
                    if opponent and opponent.level > competitor.level:
                        new_level = competitor.level
                        prev_level = opponent.level
                        level_change = f'{prev_level}->{new_level}'
                        ResultsSheet.upload_canceled_result(opponent,
                                                            competitor,
                                                            level_change,
                                                            was_ignored=True)

                    if opponent:
                        config = get_config()
                        if config.group_chat_id:
                            gmsg = get_translation_for(
                                'group_chat_technical_win_report_msg').format(
                                    opponent.name, competitor.name)
                            if level_change:
                                gmsg += '.\n'
                                gmsg += get_translation_for(
                                    'group_chat_players_level_changed').format(
                                        level_change)

                                LogsSheet.glog(
                                    get_translation_for(
                                        'gsheet_log_player_ignored_challenge_from_player'
                                    ).format(competitor.name, opponent.name) +
                                    '. ' + get_translation_for(
                                        'group_chat_players_level_changed').
                                    format(level_change))
                            else:
                                LogsSheet.glog(
                                    get_translation_for(
                                        'gsheet_log_player_ignored_challenge_from_player'
                                    ).format(competitor.name, opponent.name))

                            try:
                                tbot.send_message(config.group_chat_id,
                                                  gmsg,
                                                  parse_mode='html')
                            except:
                                logger.exception(
                                    'Exception occurred while sending message to group chat'
                                )

                            res = Result(player_a=opponent,
                                         player_a_s=opponent.name,
                                         player_b=competitor,
                                         player_b_s=competitor.name,
                                         result=RESULT.IGNORED,
                                         canceled=True,
                                         date=datetime.now(tz=tz),
                                         level_change=level_change)
                            res.save()

                    competitor.in_challenge_with = None
                    competitor.change_status(competitor.previous_status)
                    competitor.previous_status = None
                    competitor.latest_challenge_received_at = None
                    if prev_level:
                        competitor.level = prev_level

                    competitor.challenges_ignored = (
                        competitor.challenges_ignored +
                        1) if competitor.challenges_ignored is not None else 1
                    competitor.challenges_ignored_total = (
                        competitor.challenges_ignored_total + 1
                    ) if competitor.challenges_ignored_total is not None else 1
                    competitor.losses = competitor.losses + 1 if competitor.losses is not None else 1
                    competitor.matches = competitor.matches + 1 if competitor.matches is not None else 1
                    if competitor.challenges_ignored >= bconfig.maximum_challenges_ignored:
                        competitor.change_status(COMPETITOR_STATUS.INACTIVE)
                        LogsSheet.glog(
                            get_translation_for(
                                'gsheet_log_player_moved_to_inactive').format(
                                    competitor.name))
                    competitor.save()
                    UsersSheet.update_competitor_table_record(competitor)

                    t = get_translation_for(
                        'challenge_was_ignored_msg').format(
                            competitor.challenges_ignored,
                            bconfig.maximum_challenges_ignored)

                    if not skip_comp:
                        if competitor.status == COMPETITOR_STATUS.INACTIVE:
                            t += '.\n<b>'
                            t += get_translation_for(
                                'user_was_moved_to_inactive')
                            t += '</b>'
                        elif prev_level:
                            t += '.\n'
                            t += get_translation_for(
                                'your_level_changed_str').format(
                                    new_level, prev_level)

                        smwae_check(cuser.user_id,
                                    t,
                                    cuser,
                                    reply_markup=get_menu_keyboard(
                                        status=competitor.status),
                                    parse_mode='html')

                    if opponent:
                        opponent.reload()
                        opponent.in_challenge_with = None
                        if opponent.status != COMPETITOR_STATUS.INACTIVE:
                            opponent.change_status(opponent.previous_status)
                        opponent.previous_status = None
                        opponent.latest_challenge_received_at = None
                        opponent.wins = opponent.wins + 1 if opponent.wins is not None else 1
                        opponent.matches = opponent.matches + 1 if opponent.matches is not None else 1
                        opponent.level = new_level
                        opponent.save()
                        UsersSheet.update_competitor_table_record(opponent)

                        t = get_translation_for(
                            'challenge_was_ignored_opponent_msg')
                        if prev_level:
                            t += '\n'
                            t += get_translation_for(
                                'your_level_changed_str').format(
                                    prev_level, new_level)
                        if opponent_user:
                            smwae_check(opponent_user.user_id,
                                        t,
                                        opponent_user,
                                        reply_markup=get_menu_keyboard(
                                            status=opponent.status),
                                        parse_mode='html')
            except:
                logger.exception(
                    f'Exception occurred while checking challenge requests for competitor {competitor.name} {competitor.legacy_number}'
                )

        for competitor in Competitor.objects(status__in=(
                COMPETITOR_STATUS.CHALLENGE_STARTER,
                COMPETITOR_STATUS.CHALLENGE_RECEIVER,
                COMPETITOR_STATUS.CHALLENGE_NEED_RESULTS_CONFIRMATION,
                COMPETITOR_STATUS.CHALLENGE_NEED_CANCELLATION_CONFIRMATION)):
            try:
                if not competitor.challenge_started_at:
                    logger.error(
                        f'Competitor {competitor.name} {competitor.legacy_number} has no challenge_started_at'
                    )
                    competitor.challenge_started_at = datetime.now(tz=tz)
                    competitor.save()
                    continue
                cs = mongo_time_to_local(competitor.challenge_started_at, tz)
                if (n - cs) > timedelta(days=max(
                        0, bconfig.time_to_play_challenge -
                        bconfig.challenge_play_reminder
                )) and not competitor.challenge_remainder_sent:
                    if tbot is None:
                        tbot = TeleBot(PROJECT_NAME, threaded=False)
                    cuser = User.objects(associated_with=competitor).first()
                    if cuser is None:
                        continue
                    if not smwae_check(
                            cuser.user_id,
                            get_translation_for('remainder_challenge_play_msg')
                            .format(bconfig.challenge_play_reminder), cuser):
                        opponent, opponent_user = get_opponent_and_opponent_user(
                            competitor)
                        if opponent and opponent_user:
                            teardown_challenge(
                                opponent, None, opponent_user, tbot,
                                'error_bot_blocked_by_opponent_challenge_canceled_msg'
                            )
                            continue
                    competitor.reload()
                    competitor.challenge_remainder_sent = True
                    competitor.save()
                elif (n - cs) > timedelta(days=bconfig.time_to_play_challenge):
                    # TODO
                    pass
            except:
                logger.exception(
                    f'Exception occurred while checking challenges in progress (for competitor {competitor.name} {competitor.legacy_number})'
                )
Exemplo n.º 15
0
    def process_callback(self, callback: CallbackQuery, user: User,
                         bot: TeleBot):
        data = callback.data
        if data.find('challenge_to_') != 0:
            return RET.ANSWER_CALLBACK, None, callback, user
        data = data.replace('challenge_to_', '')

        competitor: Competitor = user.check_association()
        if not competitor:
            bot.send_message(
                callback.message.chat.id,
                get_translation_for('competitor_record_vanished_msg'))
            return RET.ANSWER_AND_GO_TO_STATE, 'AuthenticationState', callback, user

        if data.find('user='******'=')
            if len(ds) == 2:
                opponent_id = ds[1]
                try:
                    opponent = Competitor.objects(id=opponent_id).first()
                    if opponent is not None:
                        text = get_translation_for(
                            'challenge_send_confirm_msg').format(opponent.name)
                        text = f'<b>{text}</b>\n' \
                               f'{get_translation_for("info_status_str")}: {Competitor.status_code_to_str_dict[opponent.status]}\n' \
                               f'{get_translation_for("info_level_str")}: {opponent.level or get_translation_for("not_found_str")}\n' \
                               f'{get_translation_for("info_matches_str")}: {opponent.matches}\n' \
                               f'{get_translation_for("info_wins_str")}: {opponent.wins}\n' \
                               f'{get_translation_for("info_losses_str")}: {opponent.losses}\n' \
                               f'{get_translation_for("info_performance_str")}: {opponent.performance}'
                        update_failed = False
                        try:
                            bot.edit_message_text(
                                text,
                                callback.message.chat.id,
                                callback.message.message_id,
                                reply_markup=self.__confirmation_keyboard(
                                    id=opponent_id),
                                parse_mode='html')
                        except:
                            update_failed = True
                            logger.exception(
                                f'Exception occurred while updating keyboard for challenge sending. Chat: {callback.message.chat.id}'
                            )
                        if update_failed:
                            bot.send_message(
                                callback.message.chat.id,
                                text,
                                reply_markup=self.__confirmation_keyboard(
                                    id=opponent_id),
                                parse_mode='html')
                        return RET.ANSWER_CALLBACK, None, callback, user
                    else:
                        return RET.ANSWER_CALLBACK, get_translation_for(
                            'authentication_specified_competitor_not_found_clb'
                        ), callback, user
                except ValidationError:
                    logger.exception(
                        f'Incorrect opponent_id: {opponent_id} from user with user_id: {user.user_id}'
                    )
        elif data.find('paginate=') == 0:
            ds = data.split('=')
            if len(ds) == 2:
                page = ds[1]
                page = to_int(page, 1)
                try:
                    available_competitors = Competitor.objects(
                        status__in=(COMPETITOR_STATUS.ACTIVE,
                                    COMPETITOR_STATUS.PASSIVE),
                        level__in=self.get_possible_levels(competitor.level),
                        id__ne=competitor.latest_challenge_sent_to.id
                        if competitor.latest_challenge_sent_to is not None else
                        ObjectId(),
                        associated_user_vanished__ne=True).paginate(
                            page=page, per_page=10)
                except NotFound:
                    logger.exception(
                        f'User {user.user_id} tried to switch to nonexistent page {page}'
                    )
                    available_competitors = Competitor.objects(
                        status__in=(COMPETITOR_STATUS.ACTIVE,
                                    COMPETITOR_STATUS.PASSIVE),
                        level__in=self.get_possible_levels(competitor.level),
                        id__ne=competitor.latest_challenge_sent_to.id
                        if competitor.latest_challenge_sent_to is not None else
                        ObjectId(),
                        associated_user_vanished__ne=True).paginate(
                            page=1, per_page=10)
                if not render_pagination(
                        available_competitors,
                        callback.message,
                        bot,
                        get_translation_for('challenge_send_msg'),
                        self.__base_keyboard,
                        update=True):
                    bot.send_message(
                        callback.message.chat.id,
                        get_translation_for(
                            'challenge_no_applicable_competitors_msg'))
        elif data.find('none') == 0:
            return RET.ANSWER_CALLBACK, None, callback, user
        elif data.find('refresh') == 0:
            if guard.get_allowed()[0] and guard.update_allowed()[0]:
                UsersSheet.update_model()
            available_competitors = Competitor.objects(
                status__in=(COMPETITOR_STATUS.ACTIVE,
                            COMPETITOR_STATUS.PASSIVE),
                level__in=self.get_possible_levels(competitor.level),
                id__ne=competitor.latest_challenge_sent_to.id
                if competitor.latest_challenge_sent_to is not None else
                ObjectId(),
                associated_user_vanished__ne=True).paginate(page=1,
                                                            per_page=10)
            if not render_pagination(
                    available_competitors,
                    callback.message,
                    bot,
                    get_translation_for('challenge_send_msg'),
                    self.__base_keyboard,
                    update=True,
            ):
                bot.send_message(
                    callback.message.chat.id,
                    get_translation_for(
                        'challenge_no_applicable_competitors_msg'))
        elif data.find('confirm_send=') == 0:
            ds = data.split('=')
            if len(ds) == 2:
                opponent_id = ds[1]
                if competitor.latest_challenge_sent_to and opponent_id == str(
                        competitor.latest_challenge_sent_to):
                    bot.send_message(
                        callback.message.chat.id,
                        get_translation_for(
                            'challenge_opponent_no_longer_available_msg'))
                    return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user
                try:
                    opponent: Competitor = Competitor.objects(
                        status__in=(COMPETITOR_STATUS.ACTIVE,
                                    COMPETITOR_STATUS.PASSIVE),
                        level__in=self.get_possible_levels(competitor.level),
                        id=opponent_id,
                        associated_user_vanished__ne=True).first()
                    if opponent is None:
                        bot.send_message(
                            callback.message.chat.id,
                            get_translation_for(
                                'challenge_opponent_no_longer_available_msg'))
                        return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user
                    opponent_user: User = User.objects(
                        associated_with=opponent).first()
                    if opponent_user is None:
                        bot.send_message(
                            callback.message.chat.id,
                            get_translation_for(
                                'challenge_cannot_send_message_to_opponent_msg'
                            ))
                        send_msg_to_admin(
                            get_translation_for(
                                'admin_notification_tg_user_vanished').format(
                                    opponent.name))
                        opponent.associated_user_vanished = True
                        opponent.save()

                        return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user

                    config = get_config()
                    if opponent.status == COMPETITOR_STATUS.ACTIVE:
                        if not smwae_check(
                                opponent_user.user_id,
                                get_translation_for(
                                    'challenge_you_are_challenged_msg').format(
                                        user.user_id, competitor.name,
                                        competitor.level,
                                        config.time_to_accept_challenge),
                                opponent_user,
                                reply_markup=
                                get_challenge_confirmation_keyboard(),
                                parse_mode='html'):
                            bot.send_message(
                                callback.message.chat.id,
                                get_translation_for(
                                    'error_bot_blocked_by_opponent_challenge_canceled_msg'
                                ) + '\n' + get_translation_for(
                                    'error_bot_blocked_by_opponent_challenge_canceled_contact_admin_str'
                                ),
                                parse_mode='html')
                            return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user
                        opponent_user.reload()
                        opponent_user.states.append('ChallengeReceivedState')
                        if len(opponent_user.states) > STATES_HISTORY_LEN:
                            del opponent_user.states[0]
                        opponent_user.save()
                    elif opponent.status == COMPETITOR_STATUS.PASSIVE:
                        if not smwae_check(
                                opponent_user.user_id,
                                get_translation_for(
                                    'challenge_you_are_challenged_passive_msg'
                                ).format(user.user_id, competitor.name,
                                         competitor.level,
                                         config.time_to_accept_challenge),
                                opponent_user,
                                reply_markup=
                                get_challenge_confirmation_keyboard(),
                                parse_mode='html'):
                            bot.send_message(
                                callback.message.chat.id,
                                get_translation_for(
                                    'error_bot_blocked_by_opponent_challenge_canceled_msg'
                                ) + '\n' + get_translation_for(
                                    'error_bot_blocked_by_opponent_challenge_canceled_contact_admin_str'
                                ),
                                parse_mode='html')
                            return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user
                        opponent_user.reload()
                        opponent_user.states.append('ChallengeReceivedState')
                        if len(opponent_user.states) > STATES_HISTORY_LEN:
                            del opponent_user.states[0]
                        opponent_user.save()
                    else:
                        logger.error(
                            f'Trying to send message to opponent with incorrect state: {opponent.name} {opponent.legacy_number}'
                        )
                        bot.send_message(
                            callback.message.chat.id,
                            get_translation_for(
                                'error_occurred_contact_administrator_msg'),
                            parse_mode='html')
                        return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user

                    opponent.previous_status = opponent.status
                    opponent.change_status(
                        COMPETITOR_STATUS.CHALLENGE_NEED_RESPONSE)
                    opponent.in_challenge_with = competitor
                    opponent.latest_challenge_received_at = datetime.now(
                        tz=timezone('Europe/Kiev'))
                    opponent.challenge_remainder_sent = False
                    opponent.save()

                    competitor.previous_status = competitor.status
                    competitor.change_status(
                        COMPETITOR_STATUS.CHALLENGE_INITIATED)
                    competitor.in_challenge_with = opponent
                    competitor.latest_challenge_sent_to = opponent
                    competitor.challenge_remainder_sent = False
                    competitor.save()

                    user.dismiss_confirmed = False
                    user.save()

                    bot.send_message(
                        callback.message.chat.id,
                        get_translation_for('challenge_sent_msg').format(
                            opponent_user.user_id, opponent.name),
                        parse_mode='html')

                    LogsSheet.glog(
                        get_translation_for(
                            'gsheet_log_player_created_challenge_for_player').
                        format(competitor.name, opponent.name))

                    return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user

                except ValidationError:
                    logger.exception(
                        f'Incorrect opponent_id: {opponent_id} from user with user_id: {user.user_id}'
                    )

        elif data.find('cancel_send') == 0:
            if not self.update_and_paginate(callback.message,
                                            user,
                                            bot,
                                            competitor,
                                            update=True,
                                            updateText=True):
                bot.send_message(
                    callback.message.chat.id,
                    get_translation_for(
                        'challenge_no_applicable_competitors_msg'))
        elif data.find('back') == 0:
            return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user
        return RET.ANSWER_CALLBACK, None, callback, user
Exemplo n.º 16
0
    def synchronize_results(max_delta=None):
        all_finished_matches = ResultsSheet.get_all_successful_results()
        all_canceled_matches = ResultsSheet.get_all_canceled_results()

        stored_results = []
        for result in Result.objects(confirmed=True):
            stored_results.append(result)

        for sr in stored_results:
            sr: Result
            score = sr.repr_score()
            date = mongo_time_to_local(sr.date, _k_tz).strftime('%d/%m/%Y')

            if sr.result == RESULT.A_WINS:
                winner = sr.player_a_s
                loser = sr.player_b_s
            elif sr.result == RESULT.B_WINS:
                winner = sr.player_b_s
                loser = sr.player_a_s
            else:
                logger.error(f'INCONSISTENT RESULT OF A MATCH RESULT: {sr.id} {sr.result} {sr.player_a_s} {sr.player_b_s}')
                continue

            found = False
            for fm in all_finished_matches:
                if fm[0] == date and \
                        fm[1] == winner and \
                        fm[2] == score and \
                        fm[3] == loser:
                    found = True
                    all_finished_matches.remove(fm)
                    break
            if not found:
                if sr.deletion_marker:
                    logger.error(f'Again cannot find result info in gsheet: {sr.id}. Deleting')
                    sr.delete()
                else:
                    logger.error(f'Cannot find result info in gsheet: {sr.id}. {sr.result} - {sr.date}; {sr.player_a_s} - {sr.player_b_s}; {score} - {date}')
                    sr.deletion_marker = True
                    sr.save()

            else:
                sr.deletion_marker = False
                sr.save()

        now = datetime.now(tz=_k_tz)
        tbot = None
        for new_record in all_finished_matches:
            try:
                nr_date = new_record[0]
                try:
                    nr_date = datetime.strptime(nr_date, '%d/%m/%Y')
                except ValueError:
                    nr_date = datetime.strptime(nr_date, '%m/%d/%Y')
                nr_date = _k_tz.localize(nr_date)
                score = Result.try_to_parse_score(new_record[2])
                score_s = None
                if score is None:
                    score_s = new_record[2]
                    score = []
                new_res = Result(
                    player_a_s = new_record[1],
                    player_b_s = new_record[3],
                    scores=score,
                    scores_s=score_s,
                    confirmed=True,
                    level_change=new_record[4] if new_record[4] != '-' else None,
                    date=nr_date,
                    result=RESULT.A_WINS
                )
                new_res.save()

                cfg = get_config()
                if cfg.group_chat_id and (nr_date > now or (max_delta and (now - nr_date) < max_delta)):
                    if tbot is None:
                        tbot = TeleBot(BOT_TOKEN, threaded=False)

                    score = new_res.repr_score()
                    gmsg = get_translation_for('group_chat_match_result_msg').format(new_res.player_a_s,
                                                                                     new_res.player_b_s,
                                                                                     score)
                    if new_res.level_change:
                        gmsg += '.\n'
                        gmsg += get_translation_for('group_chat_players_level_changed').format(new_res.level_change)

                    try:
                        tbot.send_message(
                            cfg.group_chat_id,
                            gmsg,
                            parse_mode='html'
                        )
                    except:
                        logger.exception('Exception occurred while sending message to group chat')
            except:
                logger.exception(f'Exception occurred while checking new_record: {new_record}')

        # CANCELED CHECKS

        stored_results = []
        for result in Result.objects(canceled=True):
            stored_results.append(result)

        for sr in stored_results:
            sr: Result
            date = mongo_time_to_local(sr.date, _k_tz).strftime('%d/%m/%Y')
            alternative_date = mongo_time_to_local(sr.date, _k_tz).strftime('%m/%d/%Y')

            found = False
            # logger.warning('----------------------------')
            # logger.warning(f'{date}, {alternative_date}, {sr.player_a_s}, {sr.player_b_s}')
            for fm in all_canceled_matches:
                is_ignored = fm[2].find('игнор') != -1 or fm[2].find('проігнор') != -1 \
                             or fm[2].find(get_translation_for('gsheet_technical_win_ignored_str')) != -1
                is_dismissed = fm[2].find('повторн') != -1 or fm[2].find('відмов') != -1 \
                               or fm[2].find(get_translation_for('gsheet_technical_win_dismissed_str')) != -1
                # logger.warning(f'Is_ignore: {is_ignored} - {sr.result==RESULT.IGNORED}, is_dismissed: {is_dismissed} - {sr.result==RESULT.DISMISSED}')
                # logger.warning(fm)
                # logger.warning(f'{fm[0] == date} | {fm[0] == alternative_date} | {fm[3] == sr.player_a_s} | {fm[1] == sr.player_b_s}')
                # logger.warning(f'{(is_dismissed and sr.result == RESULT.DISMISSED) or (is_ignored and sr.result == RESULT.IGNORED)}')

                winner = sr.player_a_s
                loser = sr.player_b_s

                if fm[0] in (date, alternative_date) and \
                        fm[3] == winner and \
                        fm[1] == loser and \
                        ((is_dismissed and sr.result == RESULT.DISMISSED) or (is_ignored and sr.result == RESULT.IGNORED)):
                    found = True
                    all_canceled_matches.remove(fm)
                    break
            if not found:
                if sr.deletion_marker:
                    logger.error(f'Again cannot find result (canceled) info in gsheet: {sr.id}. Deleting')
                    sr.delete()
                else:
                    logger.error(
                        f'Cannot find result (canceled) info in gsheet: {sr.id}. {sr.result} - {sr.date}; {sr.player_a_s} - {sr.player_b_s}; {date}')
                    sr.deletion_marker = True
                    sr.save()
            else:
                sr.deletion_marker = False
                sr.save()

        for new_record in all_canceled_matches:
            try:
                nr_date = new_record[0]
                try:
                    nr_date = datetime.strptime(nr_date, '%d/%m/%Y')
                except ValueError:
                    nr_date = datetime.strptime(nr_date, '%m/%d/%Y')
                nr_date = _k_tz.localize(nr_date)
                is_ignored = new_record[2].find('игнор') != -1 or new_record[2].find('проігнор') != -1
                #is_dismissed = new_record[2].find('повторн') != -1 or new_record[2].find('відмов') != -1
                new_res = Result(
                    player_a_s = new_record[3],
                    player_b_s = new_record[1],
                    canceled=True,
                    level_change=new_record[4],
                    date=nr_date,
                    result=RESULT.IGNORED if is_ignored else RESULT.DISMISSED
                )
                new_res.save()

                cfg = get_config()
                if cfg.group_chat_id and (nr_date > now or (max_delta and (now - nr_date) < max_delta)):
                    if tbot is None:
                        tbot = TeleBot(BOT_TOKEN, threaded=False)

                    if is_ignored:
                        gmsg = get_translation_for('gsheet_log_player_ignored_challenge_from_player').format(
                            new_res.player_b_s,
                            new_res.player_a_s
                        )
                    else:
                        gmsg = get_translation_for('gsheet_log_player_dismissed_challenge_from_player').format(
                            new_res.player_b_s,
                            new_res.player_a_s
                        )

                    if new_res.level_change:
                        gmsg += '.\n'
                        gmsg += get_translation_for('group_chat_players_level_changed').format(new_res.level_change)

                    try:
                        tbot.send_message(
                            cfg.group_chat_id,
                            gmsg,
                            parse_mode='html'
                        )
                    except:
                        logger.exception('Exception occurred while sending message to group chat')
            except:
                logger.exception(f'Exception occurred while checking new_record: {new_record}')
Exemplo n.º 17
0
 def send_welcome(message):
     try:
         self.__bot_state_handler.handle_state_with_message(message,
                                                            start=True)
     except Exception as e:
         logger.error(f'[ERROR] {e}')
Exemplo n.º 18
0
    def confirm_results(self, message: Message, user: User, bot: TeleBot,
                        competitor: Competitor):
        res = user.check_result()
        if not res:
            pass
            # TODO
        opponent, opponent_user = get_opponent_and_opponent_user(competitor)
        if not opponent or not opponent_user:
            res.delete()
            return teardown_challenge(
                competitor, message, user, bot,
                'challenge_confirm_cannot_find_opponent_msg' if not opponent
                else 'challenge_confirm_cannot_fin_opponents_user_msg')

        if not user.dismiss_confirmed:
            bot.send_message(
                message.chat.id,
                get_translation_for('result_confirmation_confirm_msg'))
            user.dismiss_confirmed = True
            user.save()
            return RET.OK, None, None, None
        else:
            user.dismiss_confirmed = False
            user.save()

        pa = res.player_a.fetch()
        pb = res.player_b.fetch()
        winner: Competitor
        loser: Competitor
        if res.result == RESULT.A_WINS:
            winner = pa
            loser = pb
        elif res.result == RESULT.B_WINS:
            winner = pb
            loser = pa
        else:
            logger.error('INCONSISTENT RESULT OF A RESULT')
            return RET.GO_TO_STATE, 'MenuState', None, None

        res.confirmed = True
        res.date = datetime.now(timezone('Europe/Kiev'))
        res.player_a_s = pa.name
        res.player_b_s = pb.name

        winner.wins = winner.wins + 1 if winner.wins is not None else 1
        winner.matches = winner.matches + 1 if winner.matches is not None else 1
        winner.change_status(COMPETITOR_STATUS.ACTIVE)
        winner.previous_status = None
        winner.previous_challenge_status = None
        winner.challenge_started_at = None
        winner.in_challenge_with = None
        winner.save()
        UsersSheet.update_competitor_table_record(winner)

        loser.losses = loser.losses + 1 if loser.losses is not None else 1
        loser.matches = loser.matches + 1 if loser.matches is not None else 1
        loser.change_status(loser.previous_status)
        loser.previous_status = None
        loser.previous_challenge_status = None
        loser.challenge_started_at = None
        loser.in_challenge_with = None
        loser.save()
        UsersSheet.update_competitor_table_record(loser)

        prev_level, new_level = None, None
        if winner.level > loser.level:
            prev_level = winner.level
            new_level = loser.level
            res.level_change = f'{prev_level}->{new_level}'
        res.save()

        opponent.reload()
        competitor.reload()
        if prev_level:
            if opponent == winner:
                sw = smwae_check(
                    opponent_user.user_id,
                    get_translation_for(
                        'result_confirmation_confirmed_opponent_msg') + '\n' +
                    get_translation_for('your_level_changed_str').format(
                        prev_level, new_level),
                    opponent_user,
                    reply_markup=get_menu_keyboard(status=opponent.status))
                bot.send_message(
                    message.chat.id,
                    get_translation_for('result_confirmation_confirmed_msg') +
                    '\n' +
                    get_translation_for('your_level_changed_str').format(
                        new_level, prev_level),
                )
                opponent.reload()
                opponent.level = new_level
                opponent.save()
                UsersSheet.update_competitor_table_record(opponent)
                competitor.reload()
                competitor.level = prev_level
                competitor.save()
                UsersSheet.update_competitor_table_record(competitor)
            else:
                sw = smwae_check(
                    opponent_user.user_id,
                    get_translation_for(
                        'result_confirmation_confirmed_opponent_msg') + '\n' +
                    get_translation_for('your_level_changed_str').format(
                        new_level, new_level),
                    opponent_user,
                    reply_markup=get_menu_keyboard(status=opponent.status))
                bot.send_message(
                    message.chat.id,
                    get_translation_for('result_confirmation_confirmed_msg') +
                    '\n' +
                    get_translation_for('your_level_changed_str').format(
                        prev_level, new_level),
                )
                competitor.reload()
                competitor.level = new_level
                competitor.save()
                UsersSheet.update_competitor_table_record(competitor)
                opponent.reload()
                opponent.level = prev_level
                opponent.save()
                UsersSheet.update_competitor_table_record(opponent)
        else:
            sw = smwae_check(
                opponent_user.user_id,
                get_translation_for(
                    'result_confirmation_confirmed_opponent_msg'),
                opponent_user,
                reply_markup=get_menu_keyboard(status=opponent.status))

        opponent_user.reload()
        opponent_user.current_result = None
        opponent_user.states.append('MenuState')
        if len(opponent_user.states) > STATES_HISTORY_LEN:
            del opponent_user.states[0]
        opponent_user.save()

        user.reload()
        user.current_result = None
        user.save()

        res.reload()
        ResultsSheet.upload_result(res)
        if not res.level_change:
            LogsSheet.glog(
                get_translation_for('gsheet_log_game_finished').format(
                    competitor.name, opponent.name, winner.name,
                    res.repr_score()))
        else:
            LogsSheet.glog(
                get_translation_for('gsheet_log_game_finished').format(
                    competitor.name, opponent.name, winner.name,
                    res.repr_score()) + '. ' +
                get_translation_for('group_chat_players_level_changed').format(
                    res.level_change))

        config = get_config()
        if config.group_chat_id:
            score = res.repr_score()
            gmsg = get_translation_for('group_chat_match_result_msg').format(
                winner.name, loser.name, score)
            if res.level_change:
                gmsg += '.\n'
                gmsg += get_translation_for(
                    'group_chat_players_level_changed').format(
                        res.level_change)

            try:
                bot.send_message(config.group_chat_id, gmsg, parse_mode='html')
            except:
                logger.exception(
                    'Exception occurred while sending message to group chat')

        return RET.GO_TO_STATE, 'MenuState', message, user