Beispiel #1
0
    def __init__(self,
                 session: Session = None,
                 identifier: Identifier = None,
                 p4sheet: Sheet = None,
                 playersHandler: PlayersHandler = None) -> None:
        if not session:
            self.session = Session()
        else:
            self.session = session
        if not p4sheet:
            self.p4sheet = Sheet(sheet_p4)
        else:
            self.p4sheet = p4sheet
        if not identifier:
            self.identifier = Identifier(self.session, self.p4sheet)
        else:
            self.identifier = identifier
        if not playersHandler:
            self.playersHandler = PlayersHandler(self.session, self.p4sheet,
                                                 self.identifier)
        else:
            self.playersHandler = playersHandler

        self.failed = []
        self.unknown = []
Beispiel #2
0
 def __init__(self, session: Session = None, identifier: Identifier = None):
     if not session:
         self.session = Session()
     else:
         self.session = session
     if not identifier:
         self.identifier = Identifier()
     else:
         self.identifier = identifier
Beispiel #3
0
def id_player(player: dict, identifier: Identifier):
    name = identifier.identify(player['id']['id'])
    if name == None:
        name = identifier.identify(player['name'])
        if name == None:
            name = identifier.tracker_identify(player['name'])
            if name == None:
                name = player['name']

    return name
Beispiel #4
0
    def __init__(
        self,
        bot: commands.Bot,
        session: Session = None,
        identifier: Identifier = None,
        fc_sheet: Sheet = None,
        elo: EloHandler = None,
        poissonHandler: SheetsPoisson = None,
    ):
        self.bot = bot

        self.session = session if session else Session()
        self.identifier = identifier if identifier else Identifier(self.session)
        self.fc_sheet = fc_sheet if fc_sheet else Sheet(forecast_sheet)
        self.elo = elo if elo else EloHandler(session=self.session, identifier=self.identifier)
        self.poissonHandler = poissonHandler if poissonHandler else SheetsPoisson()
Beispiel #5
0
    def __init__(
        self,
        bot: Newsbot,
        session: Session = None,
        identifier: Identifier = None,
        p4sheet: Sheet = None,
        indysheet: Sheet = None,
        teams: TeamsHandler = None,
    ):
        self.bot = bot

        self.session = session if session else Session()
        self.identifier = identifier if identifier else Identifier()
        self.p4sheet = p4sheet if p4sheet else Sheet(sheet_p4)
        self.indysheet = indysheet if indysheet else Sheet(sheet_indy)
        self.teams = teams if teams else TeamsHandler(session=self.session,
                                                      p4sheet=self.p4sheet)
        self.streamsheet = Sheet(stream_sheet)

        super().__init__()
Beispiel #6
0
    def __init__(
        self,
        bot: Newsbot,
        session: Session = None,
        p4sheet: Sheet = None,
        indysheet: Sheet = None,
        gdsheet: Sheet = None,
        identifier: Identifier = None,
        players: PlayersHandler = None,
        stats: StatsHandler = None,
        teams: TeamsHandler = None,
    ):
        self.bot = bot

        self.session = session if session else Session()
        self.p4sheet = p4sheet if p4sheet else Sheet(sheet_p4)
        self.indysheet = indysheet if indysheet else Sheet(sheet_indy)
        self.gdsheet = gdsheet if gdsheet else Sheet(gdstats_sheet)
        self.identifier = identifier if identifier else Identifier(session=self.session, p4sheet=self.p4sheet)
        self.players = players if players else PlayersHandler(session=self.session, p4sheet=self.p4sheet, identifier=self.identifier)
        self.teams = teams if teams else TeamsHandler(session=self.session)
        self.stats = stats if stats else StatsHandler(session=self.session, p4sheet=self.p4sheet, indysheet=self.indysheet, gdsheet=self.gdsheet, teams=self.teams, identifier=self.identifier)
Beispiel #7
0
class RLPCAnalysis:
    def __init__(self,
                 session: Session = None,
                 identifier: Identifier = None,
                 p4sheet: Sheet = None,
                 playersHandler: PlayersHandler = None) -> None:
        if not session:
            self.session = Session()
        else:
            self.session = session
        if not p4sheet:
            self.p4sheet = Sheet(sheet_p4)
        else:
            self.p4sheet = p4sheet
        if not identifier:
            self.identifier = Identifier(self.session, self.p4sheet)
        else:
            self.identifier = identifier
        if not playersHandler:
            self.playersHandler = PlayersHandler(self.session, self.p4sheet,
                                                 self.identifier)
        else:
            self.playersHandler = playersHandler

        self.failed = []
        self.unknown = []

    def checks(self):
        self.playersHandler.check_players()
        # self.playersHandler.download_ids()

    def get_replays(self):
        if os.environ.get('PROD') == 'false':
            path = f'./replay_processing/Downloaded_Replays'
            target = f'./replay_processing/Replay_Files'
        else:
            path = './Downloads'
            target = f'./replay_processing/Replay_Files'
        replays = Retreiver.get_downloaded_replays(path=path, target=target)
        self.replays = replays
        return replays

    def analyze_replays(self):
        stats = pd.DataFrame(columns=["Username", *valid_stats])
        counter = 1
        replays = self.get_replays()
        series_list = []

        for series in list(replays):
            print(
                f'Uploading series {counter} of {len(list(replays))} ({round(((counter-1)/len(list(replays)))*100)}%)'
            )

            games = []
            for replay_path in replays[series]:
                replay = BallchasingReplay(replay_path, self.session,
                                           self.playersHandler,
                                           self.identifier)
                if replay.uploaded:
                    games.append(replay)

            series_obj = Series(self.session, self.identifier, len(games),
                                games)
            series_list.append(series_obj)

            counter += 1

        counter = 1
        for series in series_list:
            print(
                f'Analyzing series {counter} of {len(list(replays))} ({round(((counter-1)/len(list(replays)))*100)}%)'
            )
            series: Series

            try:
                series_stats = series.get_stats()
                failed = series.failed
                unknown = series.unknown
                stats = stats.append(series_stats)
                self.failed = [*self.failed, *failed]
                self.unknown = [*self.unknown, *unknown]
            except KeyError:
                print("SERIES FAILED")
                self.failed.append("SERIES " + str(counter))

            counter += 1

        self.stats = stats
        return stats

    def upload_stats(self, stats: pd.DataFrame):
        stats = stats.groupby(stats.index).agg(
            lambda x: x.sum() if x.dtype == 'float64' else x[0])
        for player in stats.index:
            update = {'$inc': {}}

            for col in stats.columns:
                if col in ('Username', 'Fantasy Points', 'League'):
                    continue

                snake_stat = snakecase_stat(col)
                if type(stats.loc[player, col]) == np.int64:
                    datapoint = int(stats.loc[player, col])
                else:
                    datapoint = round(float(stats.loc[player, col]), 2)
                update['$inc'][
                    f'seasons.$[season].season_stats.{snake_stat}'] = datapoint

            try:
                self.session.all_players.update_one({'_id': player},
                                                    update,
                                                    array_filters=[{
                                                        "season.season_num":
                                                        current_season
                                                    }])
            except:
                print("PLAYER STATS FAILED: " + player)
                continue

    def update_fantasy(self, stats: pd.DataFrame) -> None:
        if 'League' not in stats.columns:
            stats['Fantasy Points'] = stats.apply(
                lambda row: fantasy_formula(row), axis=1)
            stats['League'] = stats.apply(
                lambda row: self.identifier.find_league(
                    self.identifier.find_team([row.name])),
                axis=1)
        fantasy = self.session.fantasy.find()

        if datetime.now(tz=pytz.timezone("US/Eastern")).weekday() == 4:
            self.session.fantasy.update_many({},
                                             {'$set': {
                                                 'transfers_left': 2
                                             }})

        while fantasy.alive:
            if fantasy.count() == 0:
                break
            account = fantasy.next()
            for player in account['players']:
                username = self.session.all_players.find_one({'_id': player
                                                              })['username']

                if username not in stats.index:  # They didn't have stats for this gameday
                    continue

                points = int(stats.loc[username, 'Fantasy Points'])
                self.session.fantasy.update_one(
                    {
                        '_id': account['_id'],
                        'player_history.Player': player
                    }, {
                        '$inc': {
                            'player_history.$.Points': points,
                            'points': points
                        }
                    })

        for player in stats.index:
            self.session.all_players.update_one({'username': player}, {
                '$inc': {
                    'fantasy.fantasy_points':
                    int(stats.loc[player, 'Fantasy Points'])
                }
            })

    def log_data(self, stats: pd.DataFrame, range: str):
        def get_league(row):
            try:
                league = self.identifier.find_league(
                    self.identifier.find_team([row.name]))
                if not league:
                    return "Unknown"
                else:
                    return league
            except:
                return "Unknown"

        if 'League' not in stats.columns:
            stats['Fantasy Points'] = stats.apply(
                lambda row: fantasy_formula(row), axis=1)
            stats['League'] = stats.apply(lambda row: get_league(row), axis=1)

        known = stats.loc[~stats['Username'].isin(self.unknown)]
        unknown = stats.loc[stats['Username'].isin(self.unknown)]

        sheet = Sheet(gdstats_sheet)
        sheet.push_df(range, known.reset_index().fillna(value=0))
        sheet.push_df("Failed Players!A2:Z",
                      unknown.reset_index().fillna(value=0))

    def fix_failed(self):
        sheet = Sheet(gdstats_sheet)
        failed = sheet.to_df('Failed Players!A1:AN')
        fixed = pd.DataFrame(columns=failed.columns)
        if failed.empty:
            return print("No players found!")
        for row in failed.index:
            username = failed.loc[row, 'Username']
            known = input(f"Do you know who {username} is? (y/n) ")
            if known == "y":
                _id = input("Please type their discord id: ")
                # Add rl id to their account
                found = self.session.all_players.find_one_and_update(
                    {"_id": _id},
                    {"$push": {
                        "rl_id": failed.loc[row, "Discord ID"]
                    }})
                if found:
                    fixed = fixed.append(failed.loc[row])
                    fixed.loc[fixed['Username'] == username,
                              'Discord ID'] = _id
                    fixed.loc[fixed['Username'] == username,
                              'Username'] = found['username']
                    failed.drop(row)

        self.unknown = failed['Username'].values
        sheet.clear("Failed Players!A2:AN")
        self.log_data(fixed.set_index("Discord ID"),
                      f'{dates[get_latest_gameday()]}!A2:Z')
        self.upload_stats(fixed.set_index("Discord ID"))

    def main(self):
        print("Checks")
        self.checks()

        print("Getting replays")
        stats = self.analyze_replays()

        print("Logging data")
        self.log_data(stats, f'{dates[get_latest_gameday()]}!A2:Z')

        print("Uploading Stats")
        self.upload_stats(stats)

        # print("Updating fantasy points")
        # self.update_fantasy(stats)

        print("FAILED: " + str(self.failed))
Beispiel #8
0
from rlpc.players import Session, PlayersHandler, Identifier
import pymongo
import unittest

session = Session()
players = PlayersHandler()
identifier = Identifier()


class TestPlayers(unittest.TestCase):
    # def test_checks(self):
    #     players.check_players()
    #     players.download_ids()

    def test_client(self):
        self.assertIsInstance(session.client, pymongo.MongoClient)

    def test_find_league(self):
        self.assertEqual("Major", identifier.find_league("Hawks"))

    def test_find_team(self):  #
        self.assertEqual("Genesis",
                         identifier.find_team(['SpadL', 'Computer', 'Zero']))

    def test_identify(self):  #
        self.assertEqual("bdong", identifier.identify("76561199015415785"))

    def test_tracker_identify(self):
        self.assertEqual("Lil Uzi Yurt",
                         identifier.tracker_identify("OhWaitWhy"))
    def __init__(self, token: Literal = BOT_TOKEN):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix=prefix, intents=intents, help_command=None, case_insensitive=True)

        self.session = Session()
        self.p4sheet = Sheet(sheet_p4, refresh_cooldown=60)
        self.fc_sheet = Sheet(forecast_sheet)
        self.indysheet = Sheet(sheet_indy, refresh_cooldown=60)
        self.gdsheet = Sheet(gdstats_sheet)
        self.pr_sheet = Sheet(power_rankings_sheet)
        self.identifier = Identifier(self.session, self.p4sheet)
        self.elo = EloHandler(self.session, self.identifier)
        self.fantasy = FantasyHandler(self.session)
        self.players = PlayersHandler(self.session, self.p4sheet, self.identifier)
        self.teams = TeamsHandler(session=self.session)
        self.stats = StatsHandler(
            session=self.session,
            p4sheet=self.p4sheet,
            indysheet=self.indysheet,
            powerrankings=self.pr_sheet,
            teams=self.teams,
            identifier=self.identifier,
        )

        self.token = token

        self.COGS = [
            Elo(
                self,
                session=self.session,
                identifier=self.identifier,
                fc_sheet=self.fc_sheet,
                elo=self.elo,
            ),
            # Fantasy(
            #     self, session=self.session, fantasy=self.fantasy, p4_sheet=self.p4sheet
            # ),
            Help(self),
            Links(self),
            Reddit(self),
            Stats(
                self,
                session=self.session,
                p4sheet=self.p4sheet,
                indysheet=self.indysheet,
                gdsheet=self.gdsheet,
                identifier=self.identifier,
                players=self.players,
                stats=self.stats,
                teams=self.teams,
            ),
            Stocks(
                self,
                session=self.session,
            ),
            Misc(
                self,
                session=self.session,
                identifier=self.identifier,
                p4sheet=self.p4sheet,
                indysheet=self.indysheet,
                teams=self.teams,
            ),
        ]
Beispiel #10
0
class EloHandler:
    def __init__(self, session: Session = None, identifier: Identifier = None):
        if not session:
            self.session = Session()
        else:
            self.session = session
        if not identifier:
            self.identifier = Identifier()
        else:
            self.identifier = identifier

    def get_elo(self, team: str) -> int:
        doc = self.session.teams.find_one({'_id': team.title()})
        return doc['current_elo']

    def set_elo(self, team: str, elo: int) -> None:
        doc = self.session.teams.find_one({'_id': team.title()})
        self.session.teams.find_one_and_update({"_id": team.title()}, {
            '$set': {
                'current_elo': elo,
                'previous_elo': doc['current_elo']
            },
            '$push': {
                'seasons.$[season].elo_history': elo
            }
        },
                                               array_filters=[{
                                                   'season.season_num':
                                                   current_season
                                               }])

    def add_game_manual(self, league: str, team1: str, team2: str, winner: str,
                        score: str) -> None:
        if 'ff' in score:
            return

        league = leagues[league.lower()]
        team1 = team1.title()
        team2 = team2.title()

        Ra = self.get_elo(team1)  # Team 1 rating
        Rb = self.get_elo(team2)  # Team 2 rating
        score = list(score.strip())
        score = f"{score[0]} - {score[-1]}"  # Putting it in the right format
        score1 = int(score[0])
        score2 = int(score[-1])
        Qa = 10**(Ra / 200)
        Qb = 10**(Rb / 200)
        Ea = Qa / (Qa + Qb)  # Team 1 expected score (percentage of games)
        Eb = Qb / (Qa + Qb)  # Team 2 expected score (percentage of games)
        Sa = 0  # Team 1 actual score
        Sb = 0  # Team 2 actual score

        if score.lower() != "ff":
            if winner == team1 and score1 > score2:
                Sa = score1 / (score1 + score2)
                Sb = score2 / (score1 + score2)
            elif winner == team1 and score2 > score1:
                Sb = score1 / (score1 + score2)
                Sa = score2 / (score1 + score2)
            elif winner == team2 and score1 > score2:
                Sa = score1 / (score1 + score2)
                Sb = score2 / (score1 + score2)
            elif winner == team2 and score2 > score1:
                Sb = score1 / (score1 + score2)
                Sa = score2 / (score1 + score2)
            elif winner.lower() == "double ff":
                Sa = Ea
                Sb = Eb
            else:
                Sa = Ea
                Sb = Eb
        elif score.lower() == "ff":
            Sa = Ea
            Sb = Eb
        else:
            Sa = Ea
            Sb = Eb

        team1_rating = round(Ra + k * (Sa - Ea))
        team2_rating = round(Rb + k * (Sb - Eb))

        self.set_elo(team1, team1_rating)
        self.set_elo(team2, team2_rating)

    def predict(self, team1: str, team2: str, bestof: int = 5) -> str:
        team1 = team1.title()
        team2 = team2.title()
        try:
            league = self.identifier.find_league(team1)
        except:
            return "Could not find that team"

        if league != self.identifier.find_league(team2):
            return "Teams must be from the same league"

        Ra = self.get_elo(team1)  # Team 1 rating
        Rb = self.get_elo(team2)  # Team 2 rating
        Qa = 10**(Ra / 200)
        Qb = 10**(Rb / 200)
        exp_score_1 = Qa / (Qa + Qb)
        exp_score_2 = Qb / (Qa + Qb)
        firstto = round((bestof / 2) + 0.51)

        wins1 = round(exp_score_1 * bestof)
        wins2 = round(exp_score_2 * bestof)

        if wins1 >= firstto:
            wins1 = firstto
            return f'Winner: {team1}\nScore: {wins1} - {int(wins2)}'
        elif wins2 >= firstto:
            wins2 = firstto
            return f'Winner: {team2}\nScore: {wins2} - {int(wins1)}'
        elif wins1 == wins2:
            winner = np.random.choice([team1, team2],
                                      replace=True,
                                      p=[exp_score_1, exp_score_2])
            if winner == team1:
                wins1 += 1
            elif winner == team2:
                wins2 += 1
            else:
                return "Something went catastrophically wrong with the tiebreaker game."
            if wins1 == firstto:
                return f'Winner: {team1}\nScore: {wins1} - {int(wins2)}\nSettled with a tiebreaker game'
            elif wins2 == firstto:
                return f'Winner: {team2}\nScore: {wins2} - {int(wins1)}\nSettled with a tiebreaker game'
        else:
            print(wins1, wins2, firstto)
            return "Something went catastrophically wrong, nothing seems to exist."

    def rank_teams(self, league: str) -> pd.DataFrame:
        league = leagues[league.lower()]
        lb = pd.DataFrame(columns=['Team', 'Elo', 'Previous'])
        lb.set_index('Team', inplace=True)
        teams = self.session.teams.find({'league': league})
        count = self.session.teams.count_documents({'league': league})

        if count == 0:
            return f" `{league}` appears to be an invalid league"

        for i in range(count):
            team = teams.next()
            lb.loc[team['_id']] = [team['current_elo'], team['previous_elo']]

        lb.sort_values(by='Elo', ascending=False, inplace=True)
        return lb

    def autoparse(self, games: str) -> None:
        games = games.split("\n")
        for game in games:
            team1 = game.split()[0].title()
            if team1 == "Yellow":
                team1 = "Yellow Jackets"
            elif team1 == "The":
                team1 = "The Snowmen"
            team2 = game.split()[-1].title()
            if team2 == "Jackets":
                team2 = "Yellow Jackets"
            elif team2 == "Snowmen":
                team2 = "The Snowmen"
            score = ""
            if team1 not in ["Yellow Jackets", "The Snowmen"]:
                score = game.split()[1]
            else:
                score = game.split()[2]

            league = self.identifier.find_league(team1)
            if league != self.identifier.find_league(team2):
                return f"{game} failed: Not same league"

            try:
                self.add_game_manual(league, team1, team2, team1, score)
            except:
                return f"{game} failed"