Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update espn_api_parser.py #43

Merged
merged 3 commits into from
Sep 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 58 additions & 71 deletions data/espn_api_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
from datetime import datetime
from utils import convert_time
import os
import debug
from pprint import pprint
import json

API_URL = "https://fantasy.espn.com/apis/v3/games/ffl/seasons"
API_URL = "https://lm-api.reads.fantasy.espn.com/apis/v3/games/ffl/seasons"


class ESPNFantasyInfo():
Expand All @@ -19,25 +18,21 @@ def __init__(self, league_id, team_id, swid, espn_s2, week, year):
self.teams_info = self.get_teams()
self.matchup = self.get_matchup()

# yeah these two are stupid and useless functions but right now I'm panicking trying to get this to work
def refresh_matchup(self):
return self.get_matchup()
self.matchup = self.get_matchup()
return self.matchup

def refresh_scores(self):
return self.get_matchup()
self.matchup = self.get_matchup()
return self.matchup

def get_matchup(self):
debug.info('getting matchup')
"""
get all matchups this week and find the matchup you care about
"""
url = '{0}/{1}/segments/0/leagues/{2}'.format(
API_URL, self.year, self.league_id)
print('getting matchup')
matchup_info = {}
try:
matchups = requests.get(url, cookies=self.cookies, params={
"view": "mBoxscore"})
matchups = matchups.json()
url = '{0}/{1}/segments/0/leagues/{2}'.format(
API_URL, self.year, self.league_id)
matchups = requests.get(url, cookies=self.cookies, params={"view": "mBoxscore"}).json()
for matchup in matchups['schedule']:
if int(matchup['matchupPeriodId']) != self.week:
continue
Expand All @@ -49,7 +44,7 @@ def get_matchup(self):
matchup_info['user_team'] = next(
(item for item in self.teams_info if item['team_id'] == matchup['home']['teamId']))['owner']
if 'pointsByScoringPeriod' in matchup['home']:
matchup_info['user_score'] = float(matchup['home']['pointsByScoringPeriod'][str(self.week)])
matchup_info['user_score'] = float(matchup['home']['pointsByScoringPeriod'].get(str(self.week), 0))
else:
matchup_info['user_score'] = float(
matchup['home'].get('rosterForCurrentScoringPeriod', {}).get('appliedStatTotal', 0))
Expand All @@ -60,7 +55,7 @@ def get_matchup(self):
matchup_info['opp_team'] = next(
(item for item in self.teams_info if item['team_id'] == matchup['away']['teamId']))['owner']
if 'pointsByScoringPeriod' in matchup['away']:
matchup_info['opp_score'] = float(matchup['away']['pointsByScoringPeriod'][str(self.week)])
matchup_info['opp_score'] = float(matchup['away']['pointsByScoringPeriod'].get(str(self.week), 0))
else:
matchup_info['opp_score'] = float(
matchup['away'].get('rosterForCurrentScoringPeriod', {}).get('appliedStatTotal', 0))
Expand All @@ -72,7 +67,7 @@ def get_matchup(self):
matchup_info['user_team'] = next(
(item for item in self.teams_info if item['team_id'] == matchup['away']['teamId']))['owner']
if 'pointsByScoringPeriod' in matchup['away']:
matchup_info['user_score'] = float(matchup['away']['pointsByScoringPeriod'][str(self.week)])
matchup_info['user_score'] = float(matchup['away']['pointsByScoringPeriod'].get(str(self.week), 0))
else:
matchup_info['user_score'] = float(
matchup['away'].get('rosterForCurrentScoringPeriod', {}).get('appliedStatTotal', 0))
Expand All @@ -83,71 +78,63 @@ def get_matchup(self):
matchup_info['opp_team'] = next(
(item for item in self.teams_info if item['team_id'] == matchup['home']['teamId']))['owner']
if 'pointsByScoringPeriod' in matchup['home']:
matchup_info['opp_score'] = float(matchup['home']['pointsByScoringPeriod'][str(self.week)])
matchup_info['opp_score'] = float(matchup['home']['pointsByScoringPeriod'].get(str(self.week), 0))
else:
matchup_info['opp_score'] = float(
matchup['home'].get('rosterForCurrentScoringPeriod', {}).get('appliedStatTotal', 0))
return matchup_info
except requests.exceptions.RequestException as e:
print("Error encountered, Can't reach ESPN API", e)
print("Error encountered. Can't reach ESPN API:", e)
return matchup_info
except IndexError:
print("ESPN API Index Error in get_matchup")
return matchup_info
except Exception as e:
print("ESPN API Error in get_matchup", e)
print("ESPN API Error in get_matchup:", e)

def get_teams(self):
debug.info('getting teams')
url = '{0}/{1}/segments/0/leagues/{2}'.format(
API_URL, self.year, self.league_id)
user_info = []
try:
users = requests.get(url, cookies=self.cookies,
params={"view": "mTeam"})
users = users.json()
for user in users['teams']:
avatar = user.get('logo', 'https://upload.wikimedia.org/wikipedia/en/thumb/a/a2/National_Football_League_logo.svg/800px-National_Football_League_logo.svg.png')
team_id = user['id']
abbrev = user['abbrev']
team_name = user['location'] + ' ' + user['nickname']
owner = user['primaryOwner']
user_dict = {"abbrev": abbrev, "team_id": team_id,
"owner": owner, "team": team_name, "avatar": avatar}
user_info.append(user_dict)
for member in users['members']:
for ui in user_info:
if ui['owner'] == member['id']:
ui['display_name'] = member['displayName']
break
self.get_avatars(user_info)
return user_info
except requests.exceptions.RequestException:
print("Error encountered, Can't reach ESPN API")
return 0
except IndexError:
print("something somehow ended up out of index")
return 0
print('getting teams')
user_info = []
try:
url = '{0}/{1}/segments/0/leagues/{2}'.format(API_URL, self.year, self.league_id)
users = requests.get(url, cookies=self.cookies, params={"view": "mTeam"}).json()
for user in users['teams']:
avatar = user.get('logo', 'https://upload.wikimedia.org/wikipedia/en/thumb/a/a2/National_Football_League_logo.svg/800px-National_Football_League_logo.svg.png')
team_id = user['id']
abbrev = user['abbrev']
team_name = user.get('location', '') + ' ' + user.get('nickname', '')
owner = user.get('primaryOwner', 'Unknown Owner')
user_dict = {"abbrev": abbrev, "team_id": team_id, "owner": owner, "team": team_name, "avatar": avatar, "display_name": None}
user_info.append(user_dict)
for member in users.get('members', []):
for ui in user_info:
if ui.get('owner') == member.get('id'):
ui['display_name'] = member.get('displayName', 'Unknown Display Name')
break
self.get_avatars(user_info)
return user_info
except requests.exceptions.RequestException:
print("Error encountered. Can't reach ESPN API")
return []
except IndexError:
print("Something somehow ended up out of index")
return []

def get_avatars(self, teams):
debug.info('getting avatars')
logospath = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', 'logos'))
if not os.path.exists(logospath):
os.makedirs(logospath, 0o777)
for team in teams:
avatar = team['avatar']
filename = os.path.join(
logospath, '{0}'.format(avatar.split("/")[-1]))
if not os.path.exists(filename):
debug.info('downloading avatar for {0}'.format(
team['display_name']))
r = requests.get(avatar, stream=True)
with open(filename, 'wb') as fd:
print(filename)
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
# can't render SVGs
if filename.endswith('.svg'):
debug.warning(
'Warning! There are multiple SVG files that need to be converted manually into PNG due to crappy pi/python2 limitations. Check the ESPN SETUP STUFF part of the readme!')
logospath = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', 'logos'))
if not os.path.exists(logospath):
os.makedirs(logospath, 0o777)
default_avatar_url = 'https://example.com/default_avatar.png' # Replace with your default avatar URL
for team in teams:
avatar = team['avatar']
filename = os.path.join(
logospath, '{0}'.format(avatar.split("/")[-1]))
if not os.path.exists(filename):
filename = os.path.join(logospath, 'default_avatar.png') # Replace with your default avatar file path
print('Downloading avatar for {0}'.format(team['display_name']))
r = requests.get(avatar, stream=True)
with open(filename, 'wb') as fd:
print(filename)
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)