def create_oauth(key, secret, use_file=False): if use_file: try: return OAuth2(None, None, from_file='yahoo_creds.json') except FileNotFoundError: creds = {'consumer_key': key, 'consumer_secret': secret} with open('yahoo_creds.json', 'w') as f: json.dump(creds, f, indent=4) return OAuth2(key, secret)
def yahoo_login(): if consumer_key: oauth = OAuth2(consumer_key, consumer_secret, access_token=access_token, refresh_token=refresh_token, token_type="bearer", token_time=1599612658.9733138) else: oauth = OAuth2(None, None, from_file='helpers/oauth2yahoo.json') # if not oauth.token_is_valid(): # oauth.refresh_access_token() return oauth
def __init__(self, cfg, reset_cache): self.logger = logging.getLogger() self.cfg = cfg self.sc = OAuth2(None, None, from_file=cfg['Connection']['oauthFile']) self.lg = yfa.League(self.sc, cfg['League']['id']) self.tm = self.lg.to_team(self.lg.team_key()) self.tm_cache = utils.TeamCache(self.cfg, self.lg.team_key()) self.lg_cache = utils.LeagueCache(self.cfg) if reset_cache: self.tm_cache.remove() self.lg_cache.remove() self.load_league_statics() self.pred_bldr = None self.my_team_bldr = self._construct_roster_builder() self.ppool = None Scorer = self._get_scorer_class() self.scorer = Scorer(self.cfg) Display = self._get_display_class() self.display = Display(self.cfg) self.lineup = None self.bench = [] self.injury_reserve = [] self.opp_sum = None self.opp_team_name = None self.init_prediction_builder() self.score_comparer = ScoreComparer(self.cfg, self.scorer, self.fetch_league_lineups()) self.fetch_player_pool() self.sync_lineup() self.pick_injury_reserve() self._auto_pick_opponent()
def yahoo_session(): #use yahoo_oauth library to authenticate via oauth 2.0 #note that yahoo (apparently) no longer supports oauth 1.0 oauth = OAuth2(None, None, from_file='oauth2.json') if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth
def main(oauth_path, week, league_id, excel_dest_path): sc = OAuth2(None, None, from_file=oauth_path) stats = pd.DataFrame( curate_team_stats( flatten_team_matchup_information_from_api( get_team_data(sc, league_id, week)))) to_excel(stats, excel_dest_path)
def test_fun(): sc = OAuth2(None, None, from_file='oauth2.json') gm = game.Game(sc, 'nfl') ids = gm.league_ids() print(ids) for lg_id in ids: if lg_id.find("auto") > 0: continue lg = league.League(sc, lg_id) standings = lg.standings() for i, t in zip(range(1, 100), standings): print("{} - {}".format(i, t)) league_id = gm.league_ids(year=2018) print('league id {}'.format(league_id)) lg = gm.to_league(league_id[0]) settings = lg.settings() print('settings {}'.format(settings)) team_key = lg.team_key() print('LG Team Key {}'.format(team_key)) print("Current Week = {}".format(lg.current_week())) print("Ending Week = {}".format(lg.end_week())) print(lg.week_date_range(16)) tm = team.Team(sc, team_key) print('{}'.format(pformat(tm.roster(1)))) print('{}'.format(pformat(tm.roster(2))))
def oauth_session(): # Authenticate using oauth credentials # New users: Create 'oauth2.json' yourself and copy the format in oauth2Sample.json oauth = OAuth2(None, None, from_file='oauth2.json') if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth
def get_session(): dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'oauth2.json') oauth = OAuth2(None, None, from_file=filename) if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth.session
def refresh_oauth(self): """ Method that initializes or refreshes the `oauth` attribute. """ self.oauth = OAuth2(consumer_key=None, consumer_secret=None, from_file=self.private_json_path)
def get_session(self): oauth = OAuth2(None, None, from_file='fantasy_app\\static\\auth\\oauth2.json') if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth.session
def get_oauth_session(self, url, creds_file): oauth = OAuth2(None, None, from_file=creds_file, base_url=url) if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth
def leag(idx = -1, file = '../trade_managment/oauth2.json'): ''' function to just return the leauge to abstract away the authentication in other files ''' oauth = OAuth2(None, None, from_file=file) g = yfa.Game(oauth, 'nhl') lg = yfa.League(oauth, g.league_ids()[-1]) return lg
def authenticate(): """ Creates an authenticated Yahoo API session, getting a new token if necessary. :return: the authenticated session """ auth = OAuth2(None, None, from_file='_oauth.json') if not auth.token_is_valid(): auth.refresh_access_token() return auth
def get_all_rosters(team_names): """ Get the roster at week 15 for each team. Args: team_names (dict): Dictionary of a Team Key and manager name. Returns: player_names (dict): Dictionary of all the players rostered by a team during week 15 of the season """ sc = OAuth2(None, None, from_file='oauth2.json') # This is where we will store the manager and player data. This dictionary will be: # {Manager Name: { Player Name: {Player Key: Key, Draft Cost: $$, Keeper Cost: $$, Eligible: bool}}} player_names = dict() # Loop through the team. for team in team_names: manager_name = team_names[team] print(manager_name) url = 'https://fantasysports.yahooapis.com/fantasy/v2/team/{}/roster;week=15'.format( team) response = sc.session.get(url, params={'format': 'json'}) r = response.json() # Write the data to the rosters.json in case we need it in the future. with open('data_files/rosters.json', 'w') as f: # r = r.replace("\'", "\"") f.write(json.dumps(r)) with open('data_files/rosters.json') as f: data = json.load(f) player_names[team_names[team]] = dict() # The player data for a team roster is stored as a list of dictionaries in the Yahoo API. We need to loop list # and get each dictionary so we can get the player name and key of each player rostered. for key, value_dict in data['fantasy_content']['team'][1]['roster'][ '0']['players'].items(): if key == 'count': continue print('Key {}: Player Key: {} Player Name: {}'.format( key, value_dict['player'][0][0]['player_key'], value_dict['player'][0][2]['name']['full'])) player_key = value_dict['player'][0][0]['player_key'] player_name = value_dict['player'][0][2]['name']['full'] player_names[manager_name][player_name] = dict() player_names[manager_name][player_name]['key'] = player_key time.sleep(1) print('{}'.format(pformat(player_names))) return player_names
def main(league_id): sc = OAuth2(None, None, from_file="oauth2.json") gm = yfa.Game(sc, "nfl") lg = gm.to_league(league_id) print(f"The current week is {lg.current_week()}") print(get_alternative_standings(lg))
def __init__(self): self.oauth = OAuth2( None, None, from_file=f"{os.getenv('BBALL_HOME')}/src/yahootils/oauth_keys.json" ) if not self.oauth.token_is_valid(): self.oauth.refresh_access_token() self.game_id = self._get_game_id()
def get_session(auth_file=None): """Get a valid yahoo session object""" if auth_file is None: auth_file = Path.home() / '.yahoo_oauth.json' oauth = OAuth2(None, None, from_file=auth_file) if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth.session
async def check_auth(discordUser, ctx): if not os.path.exists(creds_folder + str(discordUser.id) + "_oauth2.json"): await ctx.send( "Sorry, I am not connected to your Yahoo Fantasy account. Please say the 'fantasy setup' command to " "link me to your account.") return False else: print("file exists") file = creds_folder + str(discordUser.id) + "_oauth2.json" print(file) oauth = OAuth2(None, None, from_file=file) if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth
def get_roster(team_names): sc = OAuth2(None, None, from_file='oauth2.json') key = '380.l.841493.t.7' #for key in team_names: # print('Getting roster for {}\'s team'.format(team_names[key])) # print(key) # url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/380.l.841493/team/{}/roster;week=15'.format(key) url = 'https://fantasysports.yahooapis.com/fantasy/v2/team/{}/roster;week=15'.format( key) response = sc.session.get(url, params={'format': 'json'}) r = response.json() with open('data_files/rosters_pretty.json', 'w') as f: # r = r.replace("\'", "\"") f.write('{}'.format(pformat(r))) with open('data_files/rosters.json', 'w') as f: # r = r.replace("\'", "\"") f.write(json.dumps(r)) print('{}'.format(pformat(r))) with open('data_files/rosters.json') as f: data = json.load(f) print('{}'.format(pformat(data))) print('{}'.format( pformat(data['fantasy_content']['team'][1]['roster']['0']['players']))) player_names = dict() for key, value_dict in data['fantasy_content']['team'][1]['roster']['0'][ 'players'].items(): if key == 'count': continue # print('{}'.format(value_dict['player'][0][0])) print('Key {}: Player Key: {} Player Name: {}'.format( key, value_dict['player'][0][0]['player_key'], value_dict['player'][0][2]['name']['full'])) # player_names[value_dict['team'][0][0]['team_key']] = value_dict['team'][0][19]['managers'][0]['manager'][ # 'nickname'] print(player_names) for key in player_names: print(key)
def get_team_names(): """ Get the team key for every team in the league Returns: team_names (dict): Dictionary of Team Keys and Manager Names """ sc = OAuth2(None, None, from_file='oauth2.json') url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/380.l.841493/teams' response = sc.session.get(url, params={'format': 'json'}) r = response.json() with open('data_files/teams.json', 'w') as f: # r = r.replace("\'", "\"") f.write(json.dumps(r)) print('{}'.format(pformat(r))) with open('data_files/teams.json') as f: data = json.load(f) # print('{}'.format(pfromat(data['fantasy_content']['league']['draft_results'][0]))) print('{}'.format(pformat(data))) print('{}'.format(pformat(data['fantasy_content']['league'][1]['teams']))) team_names = dict() for key, value_dict in data['fantasy_content']['league'][1]['teams'].items( ): if key == 'count': continue team_key = value_dict['team'][0][0]['team_key'] manager_name = value_dict['team'][0][19]['managers'][0]['manager'][ 'nickname'] # print('{}'.format(value_dict['team'][0][0])) print('Key {}: Team Key: {} Manager Name: {}'.format( key, team_key, manager_name)) team_names[team_key] = manager_name print(team_names) for key in team_names: print(key) return team_names
def one_time_auth(): # Check that auth dir exists, otherwise make it if not os.path.isdir('./auth'): os.makedirs('./auth') # Send API keys to Yahoo to request authorization token oauth = OAuth2(os.environ['YAHOO_CLIENT_ID'], os.environ['YAHOO_CLIENT_SECRET']) # After copy-paste into browser, get verifier, and copy-paste into terminal # Yahoo authorization token will be stored in a file called 'secrets.json'. with open('./auth/secrets.json', 'r') as f: secrets = json.load(f) # Add Yahoo API keys to authorization key dictionary secrets['consumer_key'] = os.environ['YAHOO_CLIENT_ID'] secrets['consumer_secret'] = os.environ['YAHOO_CLIENT_SECRET'] # Write API keys and authorization token to file with open('./auth/oauth2_.json', 'w') as f: f.write(json.dumps(secrets))
def makeOauth(): """ Makes the oauth2 authorization object based on unique key and secret. Argument: Return: oauth object 'oauth' """ myKey = 'dj0yJmk9R0pxc0dOeVZYQVJMJmQ9WVdrOU5qWjBRMGx5TXpBbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PTFi' mySecret = 'a207ce01c63ca298d40f0010ddf06a7ed9f8ba75' if not os.path.exists('oauth2.json'): creds = {'consumer_key': myKey, 'consumer_secret': mySecret} with open('oauth2.json', "w") as f: f.write(json.dumps(creds)) oauth = OAuth2(None, None, from_file='oauth2.json') if not oauth.token_is_valid(): oauth.refresh_access_token() return oauth
def __init__(self, year=2019, maxweek=1): # get creds with open("yahoo_creds.yaml", 'r') as yahoo_creds: creds = yaml.safe_load(yahoo_creds) with open("yahoo_leagues.yaml", 'r') as yahoo_leagues: leagues = yaml.safe_load(yahoo_leagues) self.oauth = OAuth2(creds['key'], creds['secret']) self.guid = self.oauth.guid self.leagues = leagues['leagues'] self.year = year self.week = maxweek + 1 #parse uniqueId output = [(l['gameid'], l['leagueid']) for l in self.leagues if l['year'] == self.year] self.uniqueId = f'{output[0][0]}.l.{output[0][1]}'
def get_transactions(): sc = OAuth2(None, None, from_file='oauth2.json') # url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/390.l.414010/transactions' url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/380.l.841493/transactions' response = sc.session.get(url, params={'format': 'json'}) r = response.json() with open('data_files/transactions.json', 'w') as f: # r = r.replace("\'", "\"") f.write(json.dumps(r)) print('{}'.format(pformat(r))) with open('data_files/transactions.json') as f: data = json.load(f) # print('{}'.format(pformat(data['fantasy_content']['league']['draft_results'][0]))) print('{}'.format( pformat(data['fantasy_content']['league'][1]['transactions']))) # print('{}'.format(pformat(data['fantasy_content']['league'][1]['transactions']['0']['transaction'][1]['players']['0']['player'][0]))) # print('{}'.format(pformat(data['fantasy_content']['league'][1]['transactions']))) transactions = dict() for key, value_dict in data['fantasy_content']['league'][1][ 'transactions'].items(): if key == 'count': break print('{}'.format(pformat(value_dict['transaction'][1]['players']))) for key2, value_dict2 in value_dict['transaction'][1]['players'].items( ): if key2 == 'count': continue print(key2) print(value_dict2['player'][1]['transaction_data']) # print('{}'.format(value_dict['transaction'][1]['players'][0])) # print('Key {}: Player Key: {} Manager Name: {}'.format(key, value_dict['team'][0][0]['team_key'], # value_dict['team'][0][19]['managers'][0]['manager'][ # 'nickname'])) # team_names[value_dict['team'][0][0]['team_key']] = value_dict['team'][0][19]['managers'][0]['manager'][ # 'nickname'] transactions[value_dict['transaction'][0]['transaction_key']] = dict()
def get_draft_results(): """ Get the draft results from Yahoo API Returns: drafted_players (dict): { Player Key: { Draft Cost: $$$$, Draft Team: Team Key}} """ sc = OAuth2(None, None, from_file='oauth2.json') url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/380.l.841493/draftresults' response = sc.session.get(url, params={'format': 'json'}) r = response.json() with open('data_files/draft.json', 'w') as f: f.write(json.dumps(r)) print('{}'.format(pformat(r))) with open('data_files/draft.json') as f: data = json.load(f) drafted_players = dict() for key, value_dict in data['fantasy_content']['league'][1][ 'draft_results'].items(): if key == 'count': continue player_key = value_dict['draft_result']['player_key'] draft_cost = value_dict['draft_result']['cost'] draft_team = value_dict['draft_result']['team_key'] print('Key {}: Player Key: {} Cost: {}'.format(key, player_key, draft_cost)) drafted_players[player_key] = dict() drafted_players[player_key] = { 'draft cost': draft_cost, 'draft team': draft_team } print(drafted_players) return drafted_players
def get_player_data(): sc = OAuth2(None, None, from_file='oauth2.json') # url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/390.l.414010/transactions' url = 'https://fantasysports.yahooapis.com/fantasy/v2/player/380.p.24851' response = sc.session.get(url, params={'format': 'json'}) r = response.json() with open('data_files/player_pretty.json', 'w') as f: # r = r.replace("\'", "\"") f.write('{}'.format(pformat(r))) with open('data_files/player.json', 'w') as f: # r = r.replace("\'", "\"") f.write(json.dumps(r)) print('{}'.format(pformat(r))) with open('data_files/player.json') as f: data = json.load(f)
def __init__(self, auth_dir, league_id, game_id=None, offline=False): """ :param auth_dir: location of both private.json (containing Yahoo dev app consumer_key and consumer_secret) and token.json (generated by OAuth2 three-legged handshake) :param league_id: league id of selected Yahoo fantasy league :param game_id: game id of selected Yahoo fantasy football game corresponding to a specific year, and defaulting to the current year :param offline: boolean to run in offline mode (ONLY WORKS IF ALL NEEDED YAHOO FANTASY FOOTBALL DATA HAS BEEN PREVIOUSLY SAVED LOCALLY USING data.py) """ self.league_id = league_id self.game_id = game_id self.league_key = None self.league_name = None self.offline = offline if not self.offline: # load credentials with open(os.path.join(auth_dir, "private.json")) as yahoo_app_credentials: auth_info = json.load(yahoo_app_credentials) self._yahoo_consumer_key = auth_info["consumer_key"] self._yahoo_consumer_secret = auth_info["consumer_secret"] # load or create OAuth2 refresh token token_file_path = os.path.join(auth_dir, "token.json") if os.path.isfile(token_file_path): with open(token_file_path) as yahoo_oauth_token: auth_info = json.load(yahoo_oauth_token) else: with open(token_file_path, "w") as yahoo_oauth_token: json.dump(auth_info, yahoo_oauth_token) if "access_token" in auth_info.keys(): self._yahoo_access_token = auth_info["access_token"] # complete OAuth2 3-legged handshake by either refreshing existing token or requesting account access and # returning a verification code to input to the command line prompt self.oauth = OAuth2(None, None, from_file=token_file_path) if not self.oauth.token_is_valid(): self.oauth.refresh_access_token()
def __init__(self, year, oauth2_file): sc = OAuth2(None, None, from_file = oauth2_file) game = yfa.Game(sc, "nba") league_name_id_dict = {} for item in game.league_ids(year=year): league_name_id_dict[game.to_league(item).settings()["name"]] = item if not league_name_id_dict: print("No fantasy teams in {}-{} seasons...".format(year, year + 1)) exit(0) questions = [ { "type": "rawlist", "name": "league", "message": "And the Fantasy league:", "choices": league_name_id_dict.keys() } ] answers = prompt(questions) self.__league = game.to_league(league_name_id_dict[answers["league"]])
def _call(self, url): oauth = OAuth2(self.client_id, self.client_secret) if not oauth.token_is_valid(): oauth.refresh_access_token() req = oauth.session.get(url) if self.log: self.logger.info("Request URL: %s" % req.url) self.logger.info("Status Code: %s" % req.status_code) self.logger.info("JSON Response: %s" % req.content) if not req.ok: req.raise_for_status() results = req.json() if self.log: self.logger.info(results) if int(results['query']['count']) > 0: wo = WeatherObject(results['query']['results']['channel']) return wo else: if self.log: self.logger.warn("No results found: %s " % results) return
def __init__(self): super().__init__() self.title = "Yahoo Draft Board" self.left = 10 self.top = 10 self.width = 3200 self.height = 1000 self.main_widget = QWidget(self) self.oauth = OAuth2(None, None, from_file='oauth2.json') league_id = "403.l.41177" self.game_type = "nhl" self.game_year = 2020 self.league = None self.setup_menubar() self.my_draft_picks = None self.label_num_picks_before_pick = QLabel( "Number picks until your turn: 4") self.positional_filter_checkboxes = None # runnable to grab draft picks from yahoo self.draft_monitor = None self.draft_complete = False self.draft_results = [] self.position_filtering_layout = QHBoxLayout() self.draft_list_widget = QListWidget() self.projection_table = QTableView() self.projection_table.setSortingEnabled(True) self.pause_draft_button = QPushButton("Pause") self.pause_draft_button.clicked.connect(self.pause_pressed) self.team_combo_box = QComboBox() self.draft_status_label = QLabel("Status: Running") self.roster_table = QTableView() self.roster_table_model = None # self.league_changed("403.l.41177", "nhl", 2020) self.league_changed("406.l.246660", "nfl", 2021) self.initUI()