def update_players(path): print("Updating players.") p = Players() players = p.get_all_players() # resp_data = json.loads(resp.json()) with open(path, 'w') as outfile: json.dump(players, outfile, indent=2) return players
def test_get_trending_players(capsys): players = Players() added = players.get_trending_players("nfl","add", 1, 4) dropped = players.get_trending_players("nfl","drop") # with capsys.disabled(): # print(added) # print(dropped)
def get_random_player(position, ba_flag): players = Players().get_all_players() position_players = [] for player_id in players: player = players[player_id] try: if player["position"].lower() == position: if position == 'def': full_name_clean = player["first_name"] + " " + player[ "last_name"] position_players.append((full_name_clean)) else: if ba_flag == 'best': if player["team"] is not None and player[ "status"].lower() == 'active' and player[ "injury_status"] is None and player[ "depth_chart_order"] == 1: position_players.append((player["full_name"])) else: position_players.append((player["full_name"])) except: pass response = [random.choice(position_players)] return response
def get_negative_starters(league_id): """ Finds all of the players that scores negative points in standard and :param league_id: Int league_id :return: Dict {"owner_name":[("player_name", std_score), ...], "owner_name":...} """ week = get_current_week() league = League(league_id) users = league.get_users() matchups = league.get_matchups(week) stats = Stats() # WEEK STATS NEED TO BE FIXED week_stats = stats.get_week_stats("regular", STARTING_YEAR, week) players = Players() players_dict = players.get_all_players() owner_id_to_team_dict = map_users_to_team_name(users) roster_id_to_owner_id_dict = map_roster_id_to_owner_id(league_id) result_dict = {} for i, matchup in enumerate(matchups): starters = matchup["starters"] negative_players = [] for starter_id in starters: try: std_pts = week_stats[str(starter_id)]["pts_std"] except KeyError: std_pts = 0 if std_pts < 0: player_info = players_dict[starter_id] player_name = "{} {}".format(player_info["first_name"], player_info["last_name"]) negative_players.append((player_name, std_pts)) if len(negative_players) > 0: owner_id = roster_id_to_owner_id_dict[matchup["roster_id"]] if owner_id is None: team_name = "Team name not available" + str(i) else: team_name = owner_id_to_team_dict[owner_id] result_dict[team_name] = negative_players return result_dict
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)
def get_players(refresh): """ Get all the players from Sleeper Use the player obj from the Sleeper API and get all the players from Sleeper. The relevant information for a player is stored in the player_dict, which has the following structure: {player_key: {'player_name': player name, 'position': position}} Args: refresh (bool): Refresh flag from cmd line Returns: player_dict (dict): Dictionary of all the players """ if refresh: print('Getting all players from Sleeper API...') players = Players().get_all_players() # If data_files doesn't exist, create the directory if not os.path.isdir('./data_files'): try: os.mkdir('data_files') except Exception as e: print(e) assert False with open('data_files/dump_players.json', 'w') as f: f.write(json.dumps(players)) # Try to open the data file for the players. If we can not access, assert and recommend them to use the # --refresh flag try: with open('data_files/dump_players.json') as f: data = json.load(f) except Exception as e: print(e) assert False, 'Unable to open data_files/dump_players.json. \n Use --refresh to get data from Sleeper API' players = data player_dict = dict() for player in players: player_id = players[player]['player_id'] player_name = '{} {}'.format(players[player]['first_name'], players[player]['last_name']) position = players[player]['position'] player_dict[player_id] = dict() player_dict[player_id]['player_name'] = player_name player_dict[player_id]['position'] = position nice_print(player_dict) return player_dict
def make_roster_dict(starters_list, bench_list): """ Takes in a teams starter list and bench list and makes a dictionary with positions. :param starters_list: List of a teams starters :param bench_list: List of a teams bench players :return: {starters:{position: []} , bench:{ position: []} } """ week = get_current_week() players = Players().get_all_players() stats = Stats() week_stats = stats.get_week_stats("regular", STARTING_YEAR, week) roster_dict = {"starters": {}, "bench": {}} for player_id in starters_list: player = players[player_id] player_position = player["position"] player_name = player["first_name"] + " " + player["last_name"] try: player_std_score = week_stats[player_id]["pts_std"] except KeyError: player_std_score = None player_and_score_tup = (player_name, player_std_score) if player_position not in roster_dict["starters"]: roster_dict["starters"][player_position] = [player_and_score_tup] else: roster_dict["starters"][player_position].append( player_and_score_tup) for player_id in bench_list: player = players[player_id] player_position = player["position"] player_name = player["first_name"] + " " + player["last_name"] try: player_std_score = week_stats[player_id]["pts_std"] except KeyError: player_std_score = None player_and_score_tup = (player_name, player_std_score) if player_position not in roster_dict["bench"]: roster_dict["bench"][player_position] = [player_and_score_tup] else: roster_dict["bench"][player_position].append(player_and_score_tup) return roster_dict
def test_get_trending_players(capsys): players = Players() added = players.get_trending_players("nfl", "add", 1, 4) dropped = players.get_trending_players("nfl", "drop")
def test_get_top_players(): players = Players() top_list = players.get_top_players_by_position('2020', 'QB', 'pts_half_ppr', 12) assert isinstance(top_list, dict) assert len(top_list) == 12
def get_player_key(search_string, requestor, name_key_switch): players = Players().get_all_players() bot_type = os.environ["BOT_TYPE"] if bot_type == "groupme": bot_id = os.environ["BOT_ID"] bot = GroupMe(bot_id) elif bot_type == "slack": webhook = os.environ["SLACK_WEBHOOK"] bot = Slack(webhook) elif bot_type == "discord": webhook = os.environ["DISCORD_WEBHOOK"] bot = Discord(webhook) found_players = [] if name_key_switch == 0: for player_id in players: player = players[player_id] try: token_set_ratio = fuzz.token_set_ratio(search_string, player["search_full_name"]) try: injury_status = player["injury_status"] except: injury_status = None if search_string in player["search_full_name"]: found_players.append((player_id, player["full_name"], player["position"], player["team"], injury_status)) elif token_set_ratio > 79: found_players.append((player_id, player["full_name"], player["position"], player["team"], injury_status)) except: pass if player["position"] == "DEF": search_name = player["first_name"].lower() + player["last_name"].lower() search_name = search_name.replace(" ","") full_name_clean = player["first_name"] + " " + player["last_name"] def_ratio = fuzz.ratio(search_string, search_name) try: injury_status = player["injury_status"] except: injury_status = None if def_ratio > 54: found_players.append((player_id, full_name_clean, player["position"], player["team"], injury_status)) if len(found_players) > 1: text = "Which player are you looking for?\n\n" for p in found_players: text += "for {} ({} - {}) - reply {}\n\n".format(p[1], p[2], p[3], p[0]) bot.send(send_any_string, text) return "True" elif len(found_players) == 1: get_player_stats(found_players[0]) return "False" elif len(found_players) == 0: bot.send(send_any_string, 'Player not found') return "False" elif name_key_switch == 1: player = players[search_string] if player["position"] == "DEF": full_name_clean = player["first_name"] + " " + player["last_name"] try: injury_status = player["injury_status"] except: injury_status = None found_players.append((search_string, full_name_clean, player["position"], player["team"], injury_status)) else: try: injury_status = player["injury_status"] except: injury_status = None found_players.append((search_string, player["full_name"], player["position"], player["team"], injury_status)) get_player_stats(found_players[0]) return "False"
def get_depth_chart(team, position): players = Players().get_all_players() bot_type = os.environ["BOT_TYPE"] if bot_type == "groupme": bot_id = os.environ["BOT_ID"] bot = GroupMe(bot_id) elif bot_type == "slack": webhook = os.environ["SLACK_WEBHOOK"] bot = Slack(webhook) elif bot_type == "discord": webhook = os.environ["DISCORD_WEBHOOK"] bot = Discord(webhook) final_string = "Depth Chart for {} - {}\n\n".format(team, position) if position == 'WR': lwrdc_num = [] rwrdc_num = [] swrdc_num = [] for player_id in players: player = players[player_id] if player["team"] == team and player["position"] == position: if player["depth_chart_order"] is not None: if player["depth_chart_position"] == 'LWR': lwrdc_num.append(player["depth_chart_order"]) elif player["depth_chart_position"] == 'RWR': rwrdc_num.append(player["depth_chart_order"]) elif player["depth_chart_position"] == 'SWR': swrdc_num.append(player["depth_chart_order"]) if len(lwrdc_num) > 0: lwrdc_cnt = max(lwrdc_num) i =1 final_string += "WR1:\n" while i <= lwrdc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and player["depth_chart_position"] == 'LWR' and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 final_string += "\n" if len(rwrdc_num) > 0: rwrdc_cnt = max(rwrdc_num) i =1 final_string += "WR2:\n" while i <= rwrdc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and player["depth_chart_position"] == 'RWR' and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 final_string += "\n" if len(swrdc_num) > 0: swrdc_cnt = max(swrdc_num) i = 1 final_string += "WR3:\n" while i <= swrdc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and player["depth_chart_position"] == 'SWR' and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 final_string += "\n" else: dc_num = [] for player_id in players: player = players[player_id] if player["team"] == team and player["position"] == position: if player["depth_chart_order"] is not None: dc_num.append(player["depth_chart_order"]) dc_cnt = max(dc_num) i = 1 while i <= dc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 bot.send(send_any_string, final_string)
from sleeper_wrapper import League from sleeper_wrapper import Players from sleeper_wrapper import Stats import pandas as pd import numpy as np import matplotlib.pyplot as plt import six ##### # Get the player data ##### league_id = 438058453903077376 league = League(league_id) stats = Stats() players = Players() all_rules = { 'pass_2pt': 2.0, # Passing 2 point conversions 'pass_int': -2.0, # Passing interceptions 'pass_lng': 0, # Long pass 'off_snp': 68.0, # Total snaps 'gs': 1.0, # Game started 'cmp_pct': 66.7, # Completion percentage 'pass_fd': 6.0, # Passing first downs 'gp': 1.0, # Game played 'pass_sack': 1.0, # Times sacked passing 'tm_off_snp': 68.0, # Teams total offensive snaps 'wind_speed': 6.0, # Wind speed 'gms_active': 1.0, # Active during game 'pass_cmp': 18.0, # Completions
def main(): with Halo("Setting up script details.", spinner="dots") as spinner: league_id = os.environ.get("SLEEPER_LEAGUE_ID", None) user_id = os.environ.get("SLEEPER_USER_ID", None) args = parser.parse_args() command_args = dict(vars(args)) is_dry_run = command_args.pop("dry_run", None) keep_positions = tuple(command_args.pop("positions", None)) spinner.succeed() Halo(f"Included positions are {', '.join(keep_positions)}", spinner="dots").succeed() league = League(league_id) players = Players() league_rosters = league.get_rosters() if is_dry_run: all_players = players.get_all_players() with open("./data/sleeper_players_current.json", "w") as outfile: json.dump(all_players, outfile) else: with open("./data/sleeper_players_current.json", "r") as infile: all_players = json.load(infile) own_team = [ team for team in league_rosters if team["owner_id"] == user_id ].pop() own_players = own_team["players"] keep_players = { p_id: p_data for p_id, p_data in all_players.items() if p_data["position"] in keep_positions } # save keep_players for testing with open("./data/sleeper_players_keep.json", "w") as outfile: json.dump(keep_players, outfile) # ID free agents by comparing keep_players to rosters rostered_player_ids = [ player for team in league_rosters for player in team["players"] ] with Halo("Separating players into rostered and FAs.", spinner="dots") as spinner: free_agents = { p_id: p_data for p_id, p_data in keep_players.items() if p_id not in rostered_player_ids } rostered_players = { p_id: p_data for p_id, p_data in keep_players.items() if p_id in rostered_player_ids } spinner.succeed() with Halo("Pulling Numberfire Projections", spinner="dots") as spinner: nfp = numberfireProjections("half_ppr") nfp.get_data("flex") nfp.convert_projections() spinner.succeed() nf_cleaned_names = {clean_name(x): x for x in nfp.projections.keys()} # add projections in to rosters for p_id, p_data in free_agents.items(): if p_data["search_full_name"] in nf_cleaned_names.keys(): p_data["numberfire_projections"] = nfp.projections[ nf_cleaned_names[p_data["search_full_name"]]] else: p_data["numberfire_projections"] = 0 for p_id, p_data in rostered_players.items(): if p_data["search_full_name"] in nf_cleaned_names.keys(): p_data["numberfire_projections"] = nfp.projections[ nf_cleaned_names[p_data["search_full_name"]]] else: p_data["numberfire_projections"] = 0 Halo("Added projections to FAs and rostered players.", spinner="dots").succeed() # comparison own_roster = { p_id: p_data for p_id, p_data in rostered_players.items() if p_id in own_players } waiver_players = dict() for p_id, p_data in own_roster.items(): if p_data["status"] == "Injured Reserve": continue waiver_dict = { "drop_proj": p_data["numberfire_projections"], "players_to_add": list(), } for fa_id, fa_data in free_agents.items(): if (fa_data["numberfire_projections"] > p_data["numberfire_projections"]) and ( fa_data["position"] == p_data["position"]): fa_dict = { "waiver_player": fa_data["search_full_name"], "waiver_proj": fa_data["numberfire_projections"], } waiver_dict["players_to_add"].append(fa_dict) waiver_players[p_data["search_full_name"]] = waiver_dict Halo( "Compared FA projections to your roster. Returning players with better projections.", spinner="dots", ).succeed() pp = pprint.PrettyPrinter() pp.pprint(waiver_players)
# Define Inputs league_id = 470314205950504960 players_file = 'sleeper_players.pkl' team_num = 8 # Access API league = League(league_id) rosters = league.get_rosters() # Not supposed to call this all the time because it is a large file (5MB) if os.path.isfile(players_file): with open(players_file, 'rb') as f: players = pickle.load(f) else: P = Players() players = P.get_all_players() with open(players_file, 'wb') as f: pickle.dump(players, f) my_team = rosters[team_num - 1] my_dudes = [players[id] for id in my_team['players']] my_pals = [ dude['full_name'] for dude in my_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] rostered_teams = [roster['players'] for roster in rosters] rostered_players = sum(rostered_teams, []) rostered_dudes = [players[id] for id in rostered_players]
def get_dudes(my_league): starting_lineup = [] if my_league['platform'] == 'ESPN': from ff_espn_api import League league_id = my_league['league_id'] year = my_league['year'] swid = my_league['swid'] espn_s2 = my_league['espn_s2'] team_num = my_league['team_num'] league = League(league_id, year, espn_s2, swid) my_team = league.teams[team_num - 1] my_dudes = my_team.roster my_pals = [ dude.name for dude in my_dudes if not ('D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots) ] my_pos = [ dude.position for dude in my_dudes if not ('D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots) ] my_def = [ dude.proTeam for dude in my_dudes if 'D/ST' in dude.eligibleSlots ] my_kick = [dude.name for dude in my_dudes if 'K' in dude.eligibleSlots] teams = league.teams rosters = [team.roster for team in teams] rostered_pals = [] rostered_def = [] rostered_kick = [] for roster in rosters: dudes = [ dude.name for dude in roster if not ( 'D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots) ] rostered_pals.extend(dudes) rostered_def.extend([ dude.proTeam for dude in roster if 'D/ST' in dude.eligibleSlots ]) rostered_kick.extend( [dude.name for dude in roster if 'K' in dude.eligibleSlots]) team_name = my_team.team_name boxscores = league.box_scores() for boxscore in boxscores: if boxscore.away_team.team_name == team_name: my_guys = boxscore.away_lineup elif boxscore.home_team.team_name == team_name: my_guys = boxscore.home_lineup for guy in my_guys: if guy.slot_position not in ['D/ST', 'K', 'BE']: starting_lineup.append(guy.name) elif my_league['platform'] == 'YAHOO': from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa oauth_file = my_league['oauth_file'] lg_number = my_league['lg_number'] sc = OAuth2(None, None, from_file=oauth_file) gm = yfa.Game(sc, 'nfl') league = gm.to_league(lg_number) week = league.current_week() team_objs = league.teams() team_keys = [team['team_key'] for team in team_objs] teams = [league.to_team(key) for key in team_keys] rosters = [team.roster(week) for team in teams] rostered_pals = [] rostered_def = [] rostered_kick = [] for roster in rosters: dudes = [ dude['name'] for dude in roster if not ('K' in dude['eligible_positions'] or 'DEF' in dude['eligible_positions']) ] rostered_pals.extend(dudes) rostered_def.extend([ dude['name'] for dude in roster if 'DEF' in dude['eligible_positions'] ]) rostered_kick.extend([ dude['name'] for dude in roster if 'K' in dude['eligible_positions'] ]) my_team = league.to_team(league.team_key()) my_roster = my_team.roster(week) my_pals = [ dude['name'] for dude in my_roster if not ('K' in dude['eligible_positions'] or 'DEF' in dude['eligible_positions']) ] my_pos = [ dude['eligible_positions'][0] for dude in my_roster if not ('K' in dude['eligible_positions'] or 'DEF' in dude['eligible_positions']) ] my_def = [ dude['name'] for dude in my_roster if 'DEF' in dude['eligible_positions'] ] my_kick = [ dude['name'] for dude in my_roster if 'K' in dude['eligible_positions'] ] starting_lineup = [ dude['name'] for dude in my_roster if not dude['selected_position'] in ['BN', 'K', 'DEF'] ] def_map = { #This neglects the RAMS and the GIANTS because Yahoo is dumb and I don't want to figure out their player IDs. 'New England': 'NE', 'Chicago': 'CHI', 'Tampa Bay': 'TB', 'Tennessee': 'TEN', 'San Francisco': 'SF', 'New York': 'NYJ', 'Green Bay': 'GB', 'New Orleans': 'NO', 'Pittsburgh': 'PIT', 'Carolina': 'CAR', 'Detroit': 'DET', 'Seattle': 'SEA', 'Cleveland': 'CLE', 'Los Angeles': 'LAC', 'Kansas City': 'KC', 'Minnesota': 'MIN', 'Buffalo': 'BUF', 'Dallas': 'DAL', 'Houston': 'HOU', 'Jacksonville': 'JAX', 'Indianapolis': 'IND', 'Oakland': 'OAK', 'Washington': 'WAS', 'Baltimore': 'BAL', 'Philadelphia': 'PHI', 'Arizona': 'ARI', 'Atlanta': 'ATL', 'Cincinnati': 'CIN', 'Denver': 'DEN', 'Miami': 'MIA' } my_def = [def_map[d] for d in my_def] rostered_def = [def_map[d] for d in rostered_def] elif my_league['platform'] == 'SLEEPER': from sleeper_wrapper import League, Players import pickle import os.path league_id = my_league['league_id'] players_file = my_league['players_file'] team_num = my_league['team_num'] league = League(league_id) rosters = league.get_rosters() # Not supposed to call this all the time because it is a large file (5MB) if os.path.isfile(players_file): with open(players_file, 'rb') as f: players = pickle.load(f) else: P = Players() players = P.get_all_players() with open(players_file, 'wb') as f: pickle.dump(players, f) my_team = rosters[team_num - 1] my_dudes = [players[id] for id in my_team['players']] my_pals = [ dude['full_name'] for dude in my_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] starting_dudes = [players[id] for id in my_team['starters']] starting_lineup = [ dude['full_name'] for dude in starting_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] my_pos = [ dude['position'] for dude in my_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] my_def = [ dude['player_id'] for dude in my_dudes if 'DEF' in dude['fantasy_positions'] ] my_kick = [ dude['full_name'] for dude in my_dudes if 'K' in dude['fantasy_positions'] ] rostered_teams = [roster['players'] for roster in rosters] rostered_players = sum(rostered_teams, []) rostered_dudes = [players[id] for id in rostered_players] rostered_pals = [ dude['full_name'] for dude in rostered_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] rostered_def = [ dude['player_id'] for dude in rostered_dudes if 'DEF' in dude['fantasy_positions'] ] rostered_kick = [ dude['full_name'] for dude in rostered_dudes if 'K' in dude['fantasy_positions'] ] else: raise ValueError('League platform ' + league.platform + ' is not supported.') return my_pals, my_pos, rostered_pals, my_def, rostered_def, my_kick, rostered_kick, clean_names( starting_lineup)