Beispiel #1
0
    def resolve_user(parent, info, id):
        user = User(id)
        league_info = user.get_all_leagues("nfl", 2020)
        info_list = []
        for i in league_info:
            info = UserType.from_json(i)
            info_list.append(info)

        return info_list
def main(argv):
    # Parse all of the user-provided flags
    args = parse_user_provided_flags()

    # Convert the computed args into our more-verbose local fields
    account_username = args.username
    league_year = args.year
    position = args.position
    team = args.team
    output_format = args.output_format
    league_regex = re.compile(args.league_regex)

    # Retrieve the user and all of their leagues
    admin_user = User(account_username)
    all_leagues = admin_user.get_all_leagues("nfl", league_year)

    # Map to store the drafted player results
    player_id_to_drafted_player = {}

    for league_object in all_leagues:
        league = League(league_object.get("league_id"))
        league_name = league.get_league().get("name")

        # Only look at leagues that match the provided regex
        if league_regex.match(league_name):

            draft_id = league.get_league().get("draft_id")
            draft = Drafts(draft_id)

            for pick in draft.get_all_picks():
                player_id = pick["player_id"]

                if player_id in player_id_to_drafted_player.keys():
                    drafted_player = player_id_to_drafted_player.get(player_id)
                else:
                    drafted_player = DraftedPlayer(
                        pick["player_id"], pick["metadata"]["first_name"],
                        pick["metadata"]["last_name"],
                        pick["metadata"]["position"], pick["metadata"]["team"])
                    player_id_to_drafted_player[player_id] = drafted_player

                drafted_player.add_draft_position(pick["pick_no"])

    # Print the results of all the parsing
    print("")
    for player_id in sorted(player_id_to_drafted_player,
                            key=player_id_to_drafted_player.get):
        drafted_player = player_id_to_drafted_player[player_id]

        if position != INCLUDE_ALL and drafted_player.position != position:
            continue

        if team != INCLUDE_ALL and drafted_player.team != team:
            continue

        print(create_output_for_player(drafted_player, output_format))
Beispiel #3
0
def main(argv):
    args = parse_user_provided_flags()
    user = args.username
    year = args.year
    league_regex = re.compile(args.league_regex)
    week = args.week
    include_covid = args.include_covid
    include_missing = args.include_missing

    # Retrieve the list of all inactive players
    nfl_players = Players()
    inactive_players = find_all_inactive_players_for_week(
        nfl_players.get_all_players(), week, include_covid)

    if include_missing:
        # Empty starting slots fill in as id 0, so add an entry for that
        # 0th player in order to report the empty spot
        inactive_players.append(
            Player("Missing Player", "0", "None", "MISSING", "NONE"))

    # Retrieve all of the leagues
    admin_user = User(user)
    all_leagues = admin_user.get_all_leagues("nfl", year)
    user_store = UserStore()

    inactive_rosters = []

    # Iterate through each league to find the inactive owners in each
    for league_object in all_leagues:
        league = League(league_object.get("league_id"))
        league_name = league.get_league().get("name")

        # Only look at leagues that match the provided regex
        if league_regex.match(league_name):
            user_store.store_users_for_league(league)

            inactive_rosters.extend(
                find_inactive_starters_for_league_and_week(
                    league, week, inactive_players, user_store))

    # Print out the final inactive rosters
    print("")
    for roster in inactive_rosters:
        print(roster)
Beispiel #4
0
def test_get_all_leagues(capsys):
    user = User("78623389212098560")
    leagues = user.get_all_leagues("nfl", 2019)

    assert isinstance(leagues, list)
    assert isinstance(leagues[0], dict)

    user = User("swa")
    leagues = user.get_all_leagues("nfl", 2019)
    assert isinstance(leagues, list)
    assert isinstance(leagues[0], dict)
Beispiel #5
0
def save_draft_information(user):
    """ Save the draft information for the current year of YAFL

    This function might change in the future. I think it's possible to get past draft data, if so then I can get
    draft data from those without the need to save them. It might also be possible to get past draft data from the
    user endpoint.

    Currently this function gets the draft data from YAFL and saves it to a file /saved_drafts/draft_xxxx.json, where
    xxxx is the year.

    Args:
        user (str): Username of a YAFL manager
    """
    # Get the user object to get league info
    user_obj = User(user)

    # Get the league object. Will be used to get draft info.
    league = get_league_id(user_obj)

    season = league.get_league()['season']

    all_drafts = league.get_all_drafts()

    # Sleeper will only have 1 draft, so we can access the first result from the list
    draft_id = all_drafts[0]['draft_id']
    draft = Drafts(draft_id)
    draft_picks = draft.get_all_picks()
    nice_print(draft_picks)

    # Might be able to use draft.get_specific_draft() to get the season for the draft if this function changes in
    # the future
    # specific_picks = draft.get_specific_draft()

    # If saved_drafts doesn't exist, create the directory
    if not os.path.isdir('./saved_drafts'):
        try:
            os.mkdir('saved_drafts')
        except Exception as e:
            print(e)
            assert False

    with open('saved_drafts/draft_{}.json'.format(season), 'w') as f:
        f.write(json.dumps(draft_picks))
Beispiel #6
0
def test_get_user(capsys):
    user = User("swa")
    user = user.get_user()
    assert isinstance(user, dict)
    assert user['username'] == "swa"
Beispiel #7
0
def test_get_all_drafts(capsys):
    user = User("swa")
    drafts = user.get_all_drafts("nfl", 2019)
    assert isinstance(drafts, list)
    assert isinstance(drafts[0], dict)
Beispiel #8
0
    def wide_receivers(self, number):
        return self.__num_of_players_in_pos__(number, 'WR')

    def tight_ends(self, number):
        return self.__num_of_players_in_pos__(number, 'TE')

    def defenses(self, number):
        return self.__num_of_players_in_pos__(number, 'DEF')

    def kickers(self, number):
        return self.__num_of_players_in_pos__(number, 'K')


if __name__ == "__main__":
    PLAYER_DATABASE = player_data_base_load()
    user = User(USER_NAME)
    user_id = user.get_user_id()

    league_objs = []
    [
        league_objs.append(League(league['league_id']))
        for league in user.get_all_leagues("nfl", YEAR)
    ]

    my_rosters = []
    [[
        my_rosters.append(Roster(obj.get_league()["name"], roster["players"]))
        for roster in obj.get_rosters() if roster["owner_id"] == user_id
    ] for obj in league_objs]

    [[print(backs) for backs in roster.defenses(5)] for roster in my_rosters]
Beispiel #9
0
def main_program(username, debug, refresh, position, offline):
    """ Run the main application

    Args:
        username (str): Username of owner in YAFL 2.0
        debug (bool): Debug argument flag. Print debug output.
        refresh (bool): Refresh argument flag. Refresh player data from Sleeper API
        position (str): Position argument. Get keeper value for given position.
        offline (bool): Offline argument. Run in offline mode.
    """

    if offline:
        # For offline mode we need to get all the files from data_files. If the file does not exist, remind the user
        # to use --refresh to get and store data
        try:
            with open('data_files/player_dict.json') as f:
                player_dict = json.load(f)
        except Exception as e:
            print(e)
            assert False, 'Unable to open data_files/player_dict.json. \n Use --refresh to get data from Sleeper API'

        try:
            with open('data_files/draft_dict.json') as f:
                draft_dict = json.load(f)
        except Exception as e:
            print(e)
            assert False, 'Unable to open data_files/draft_dict.json. \n Use --refresh to get data from Sleeper API'

        try:
            with open('data_files/rosters.json') as f:
                roster_dict = json.load(f)
        except Exception as e:
            print(e)
            assert False, 'Unable to open data_files/rosters.json. \n Use --refresh to get data from Sleeper API'

        try:
            with open('data_files/transactions.json') as f:
                transactions = json.load(f)
        except Exception as e:
            print(e)
            assert False, 'Unable to open data_files/transactions.json. \n Use --refresh to get data from Sleeper API'

        try:
            with open('data_files/trades.json') as f:
                trades = json.load(f)
        except Exception as e:
            print(e)
            assert False, 'Unable to open data_files/trades.json. \n Use --refresh to get data from Sleeper API'

        try:
            with open('data_files/traded_picks.json') as f:
                traded_picks = json.load(f)
        except Exception as e:
            print(e)
            assert False, 'Unable to open data_files/traded_picks.json. \n Use --refresh to get data from Sleeper API'

        keeper_dict = determine_eligible_keepers(roster_dict, player_dict, draft_dict, transactions, traded_picks)
        pretty_print_keepers(keeper_dict)

        if position:
            position_keeper(keeper_dict, position)

        return

    # Get the user object to get league info
    user_obj = User(username)

    # Get the league object. Will be used to get draft info, transactions, and rosters.
    league = get_league_id(user_obj)

    # Get the username and id
    user_dict = get_users(league)

    # Get a dictionary of all the players
    player_dict = get_players(refresh)

    # Get the trade deadline from the league settings
    trade_deadline = get_trade_deadline(league)

    # Get a dictionary of all the drafted players
    draft_dict = get_drafted_players(league)

    # Get a dictionary of all the rostered players
    roster_dict = get_rosters(league, user_dict)

    # Get the transactions after the trade deadline
    transactions = get_transactions(league, trade_deadline)

    # Get a list of traded players and dictionary of traded draft picks
    trades, traded_picks = get_trades(league)

    # DEBUG code to process traded_picks
    # process_traded_picks(roster_dict, traded_picks)

    # Get the final keeper list
    keeper_dict = determine_eligible_keepers(roster_dict, player_dict, draft_dict, transactions, traded_picks)

    if debug:
        # If data_files doesn't exist, create the directory
        if not os.path.isdir('./debug_files'):
            try:
                os.mkdir('debug_files')
            except Exception as e:
                print(e)
                assert False
        # Output everything to a file to figure out what is happening
        with open('debug_files/user_dict.json', 'w') as f:
            f.write('{}'.format(pformat(user_dict)))
        with open('debug_files/draft_dict.json', 'w') as f:
            f.write('{}'.format(pformat(draft_dict)))
        with open('debug_files/rosters.json', 'w') as f:
            f.write('{}'.format(pformat(roster_dict)))
        with open('debug_files/player_dict.json', 'w') as f:
            f.write('{}'.format(pformat(player_dict)))
        with open('debug_files/keeper_dict.json', 'w') as f:
            f.write('{}'.format(pformat(keeper_dict)))
        with open('debug_files/transactions.json', 'w') as f:
            f.write('{}'.format(pformat(transactions)))
        with open('debug_files/trades.json', 'w') as f:
            f.write('{}'.format(pformat(trades)))
        with open('debug_files/traded_picks.json', 'w') as f:
            f.write('{}'.format(pformat(traded_picks)))

    if refresh:
        if not os.path.isdir('./data_files'):
            try:
                os.mkdir('date_files')
            except Exception as e:
                print(e)
                assert False
        with open('data_files/user_dict.json', 'w') as f:
            f.write(json.dumps(user_dict))
        with open('data_files/draft_dict.json', 'w') as f:
            f.write(json.dumps(draft_dict))
        with open('data_files/rosters.json', 'w') as f:
            f.write(json.dumps(roster_dict))
        with open('data_files/player_dict.json', 'w') as f:
            f.write(json.dumps(player_dict))
        with open('data_files/keeper_dict.json', 'w') as f:
            f.write(json.dumps(keeper_dict))
        with open('data_files/transactions.json', 'w') as f:
            f.write(json.dumps(transactions))
        with open('data_files/trades.json', 'w') as f:
            f.write(json.dumps(trades))
        with open('data_files/traded_picks.json', 'w') as f:
            f.write(json.dumps(traded_picks))

    pretty_print_keepers(keeper_dict)
    csv_print_keepers(keeper_dict)

    if position:
        position_keeper(keeper_dict, position)

    return
Beispiel #10
0
def main(argv):
    # Parse all of the user-provided flags
    args = parse_user_provided_flags()

    # Convert the computed args into our more-verbose local fields
    account_username = args.username
    league_year = args.year
    league_regex = re.compile(args.league_regex)
    starting_week = args.start
    ending_week = args.end
    weekly_score_output_count = args.weekly_count
    seasonal_score_output_count = args.season_count
    find_weekly = args.weekly or args.current_week
    print_max_this_week = args.max and args.current_week
    print_min_this_week = args.min and args.current_week
    print_max_weekly = args.weekly and args.max
    print_min_weekly = args.weekly and args.min
    find_seasonal = args.season
    print_max_seasonal = args.season and args.max
    print_min_seasonal = args.season and args.min

    # Lists containing all of the collated data
    weekly_scores = []
    seasonal_scores = []
    user_store = UserStore()

    # Retrieve all of the leagues
    admin_user = User(account_username)
    all_leagues = admin_user.get_all_leagues("nfl", league_year)

    # Iterate over all the leagues in the account
    for league_object in all_leagues:
        league = League(league_object.get("league_id"))
        league_name = league.get_league().get("name")

        # Only look at leagues that match the provided regex
        if league_regex.match(league_name):

            user_store.store_users_for_league(league)

            # Iterate over each indiviudal week, since we need to grab the max weekly score for the league
            if find_weekly:
                for week_num in range(starting_week, ending_week + 1):
                    weekly_scores.extend(
                        get_weekly_scores_for_league_and_week(
                            league, week_num, user_store))

            if find_seasonal:
                # Grab the points-for in each league
                seasonal_scores.extend(
                    get_pf_for_entire_league(league, user_store))

    # Sublists used for sorted results
    max_weekly_scores = []
    min_weekly_scores = []
    max_scores_this_week = []
    min_scores_this_week = []
    max_seasonal_points_for = []
    min_seasonal_points_for = []

    # Sort all of the lists
    if find_seasonal:
        max_seasonal_points_for = seasonal_scores.copy()
        max_seasonal_points_for.sort(
            key=lambda annual_score: annual_score.points_for, reverse=True)
        min_seasonal_points_for = seasonal_scores.copy()
        min_seasonal_points_for.sort(
            key=lambda annual_score: annual_score.points_for)
    if find_weekly:
        max_weekly_scores = weekly_scores.copy()
        max_weekly_scores.sort(key=lambda weekly_score: weekly_score.points,
                               reverse=True)
        min_weekly_scores = weekly_scores.copy()
        min_weekly_scores.sort(key=lambda weekly_score: weekly_score.points)
        max_scores_this_week = list(
            filter(lambda weekly_score: weekly_score.week == ending_week,
                   max_weekly_scores.copy()))
        min_scores_this_week = list(
            filter(lambda weekly_score: weekly_score.week == ending_week,
                   min_weekly_scores.copy()))

    # Print out the results
    this_week_template = "{main_header}, Week {week_num}"
    if print_max_this_week:
        print_non_empty_list_with_header(
            max_scores_this_week,
            this_week_template.format(main_header="HIGHEST SCORES THIS WEEK",
                                      week_num=ending_week),
            weekly_score_output_count)
    if print_min_this_week:
        print_non_empty_list_with_header(
            min_scores_this_week,
            this_week_template.format(main_header="LOWEST SCORES THIS WEEK",
                                      week_num=ending_week),
            weekly_score_output_count)
    if print_max_weekly:
        print_non_empty_list_with_header(max_weekly_scores,
                                         "HIGHEST WEEKLY SCORES THIS SEASON",
                                         weekly_score_output_count)
    if print_min_weekly:
        print_non_empty_list_with_header(min_weekly_scores,
                                         "LOWEST WEEKLY SCORES THIS SEASON",
                                         weekly_score_output_count)
    if print_max_seasonal:
        print_non_empty_list_with_header(max_seasonal_points_for,
                                         "HIGHEST POINTS-FOR THIS SEASON",
                                         seasonal_score_output_count)
    if print_min_seasonal:
        print_non_empty_list_with_header(min_seasonal_points_for,
                                         "LOWEST POINTS-FOR THIS SEASON",
                                         seasonal_score_output_count)