def do_try_connect(self):
        time_before_conn = self.get_time_before_connect_allowed()
        if time_before_conn is not None:
            log(f'Going to sleep for '
                f'{time_before_conn.total_seconds() / 60:.2f} minutes')
            sleep(time_before_conn.total_seconds())  # Use blocking sleep
        try:
            log('Going to attempt to connect')
            self.func(self.db)
        except Exception as e:
            log_exception(e)

            # Get last fail info
            last_info = self.get_last_conn_fail_info(self.db)

            # Register Failed attempt
            err_count = last_info.fail_count + 1
            err_msg = f'{last_info.err_msg}\n' \
                      f'{err_count}: {str(e)[:conf.MAX_ERR_MSG_LEN]}'
            new_fail_info = ConnFailInfo(datetime.now(), err_count, err_msg)
            self.set_last_conn_fail_info(new_fail_info, self.db)
            self.inc_next_attempt_time(new_fail_info)

            # Restart script to prevent "Event loop is closed" exception
            self.db.purge()  # Save error info before restart
            restart_script()
def main():
    setup_log(None, only_std_out=True)
    db = DBCache(get_db(), purge_loglevel=logging.INFO)
    log(ConnectManager.status(db))
    ConnectManager.init_last_conn_fail_info(db)
    db.purge()
    log(f"Connections Allowed Again")
Beispiel #3
0
def main():
    global bot, connect_manager
    setup_log(None, only_std_out=True)
    set_log_level(Conf.LOG_LEVEL)
    log('Main Started')
    db = DBCache(get_db(), purge_loglevel=Conf.DB_CACHE_PURGE_LOGLEVEL)
    display_start()
    connect_manager = ConnectManager(connect, db)
    connect_manager.do_try_connect()
Beispiel #4
0
    def calc_all_rounds(self):
        """
        Repeatedly calculate next round until finals
        - favoring byes on front on even rounds numbers
        - and byes at end on odd round numbers
        :return: True if changes were made else False
        """
        changes_made = False
        rounds = self.rounds
        while rounds[-1].games_count > 1:
            changes_made = True  # Register that changes were made
            log(f'[Tournament] Calculating Round {len(rounds) + 1}',
                logging.DEBUG)
            last_round = rounds[-1]
            new_round = Round()
            if last_round.games_count % 2 != 0 and (len(rounds) + 1) % 2 == 0:
                # Plus 1 to get the number for this round
                # Has bye and round number is even put bye at the front
                new_round.add(last_round[0].winner_player())
                last_round[0].win_next_game = new_round[-1]
                last_round[0].win_next_game_player_ind = 0
                start = 1  # start from next game
            else:
                start = 0  # start from first game bye will go at end
            g1: Union[None, GameSet] = None
            for i in range(start, last_round.games_count):
                if g1 is None:
                    g1 = last_round[i]
                else:
                    new_round.add(g1.winner_player(),
                                  last_round[i].winner_player())
                    g1.win_next_game = new_round[-1]
                    g1.win_next_game_player_ind = 0
                    last_round[i].win_next_game = new_round[-1]
                    last_round[i].win_next_game_player_ind = 1
                    g1 = None
            if g1 is not None:
                # Bye has to go at end
                assert last_round.games_count % 2 != 0
                assert (len(rounds) + 1) % 2 != 0
                # Plus 1 to get the number for this round
                new_round.add(g1.winner_player())
                g1.win_next_game = new_round[-1]
                g1.win_next_game_player_ind = 0
            rounds.append(new_round)
        # TODO Add setting to control if 3rd place match should be held
        if changes_made:
            # Set Finals
            assert rounds[-1].games_count == 1
            rounds[-1][0].is_finals = True

            # Create 3rd place match
            self.add_third_place_match()
        return changes_made
Beispiel #5
0
 def fix_recreate_players(self):
     """
     Utility method used when updated happen to player fields during an
     active tournament to apply the change.
     NOTE: Only works during registration.
     """
     if not self.data.is_reg_open:
         log('[CogTournament]  Registration closed. Fix not applied to '
             'recreate players.',
             logging.ERROR)
         return
     replacement = []
     for x in self.data.players:
         replacement.append(Player(x.id, x.display, x.disp_id))
     self.data.players = replacement
     self.data.invalidate_computed_values()
Beispiel #6
0
 async def on_command_error(ctx, error):
     if isinstance(error, commands.errors.CommandNotFound):
         log(error, logging.DEBUG)
         # No need for noisy fail message right now
         # await ctx.send('Command Not Found (Maybe you have a typo)')
     elif isinstance(error, commands.errors.UserInputError):
         log(error, logging.INFO)
         await ctx.send(error)
     elif isinstance(error, commands.errors.MissingAnyRole):
         log(error, logging.INFO)
         await ctx.send('Restricted Command')
     elif isinstance(error, commands.errors.CheckFailure):
         log(error,
             logging.DEBUG)  # Mostly expected to be because of wrong
         # channel
     else:
         # Command failed for an unexpected reason. Usually this
         # shouldn't happen
         log(error, logging.WARNING)
         await ctx.send('Command Failed!!!')
Beispiel #7
0
    def add_third_place_match(self):
        if len(self.rounds) < 2:
            return  # Not enough rounds do anything

        assert self.rounds[-2].games_count == 2

        # Get games that feed into the match
        g1: GameSet = self.rounds[-2][0]
        g2: GameSet = self.rounds[-2][1]

        if g1.lose_next_game is not None:
            log('[Tournament] Seems there is already a match for losers of '
                'semi finals ABORTING creating 3rd place match',
                logging.WARNING)
            return

        third_place_match = GameSet(g1.loser_player(), g2.loser_player(),
                                    self.rounds[-1])
        g1.lose_next_game = third_place_match
        g1.lose_next_game_player_ind = 0
        g2.lose_next_game = third_place_match
        g2.lose_next_game_player_ind = 1
Beispiel #8
0
 async def on_ready():
     conn_status = (f'Successfully logged in as {self.user}\n'
                    f'{ConnectManager.status(self.db)}')
     log(conn_status)
     if len(conn_status) > Conf.MAX_DISCORD_MSG_LEN:
         log(f'CONNECTION MESSAGE EXCEEDS LIMIT: {len(conn_status)}. '
             f'Truncated')
         conn_status = conn_status[:Conf.MAX_DISCORD_MSG_LEN]
     ConnectManager.reset_fail_count(self.db)
     ConnectManager.set_last_conn_success(datetime.now(), self.db)
     ConnectManager.start_heartbeat(self.db)
     channel = self.get_channel(conf.DEBUG_CHANNEL_ID)
     if channel is not None:
         await channel.send(conn_status)
     else:
         log(f'Unable fo find channel with ID: {conf.DEBUG_CHANNEL_ID}')
     self.db.purge()  # Ensure logon information is saved
Beispiel #9
0
 def invalidate_computed_values(self):
     self.rounds_ = None
     GameSet.reset_id_count()
     self.players_map = {}
     log('[Tournament] Computed Values Invalidated', logging.DEBUG)
     self.calc_all_rounds()