RosterHash/services/espn_api.py
2025-09-04 21:31:23 -07:00

92 lines
3.8 KiB
Python

import requests
from datetime import datetime, timedelta
class ESPNAPI:
BASE_URL = 'https://site.api.espn.com/apis/site/v2/sports/football/nfl'
def __init__(self):
self.session = requests.Session()
def get_week_schedule(self, week, season):
"""Get NFL schedule for a specific week"""
try:
print(f"ESPN API: Fetching schedule for week {week}, season {season}", flush=True)
# Get current NFL scoreboard
url = f"{self.BASE_URL}/scoreboard"
response = self.session.get(url)
response.raise_for_status()
data = response.json()
print(f"ESPN API: Response status: {response.status_code}", flush=True)
games = []
if 'events' in data:
print(f"ESPN API: Found {len(data['events'])} events", flush=True)
for i, event in enumerate(data['events']):
try:
# Parse the game date
game_date = datetime.strptime(event['date'], '%Y-%m-%dT%H:%MZ')
# Extract team information
competitors = event['competitions'][0]['competitors']
home_team = None
away_team = None
# Identify home and away teams
for comp in competitors:
team_abbrev = comp['team']['abbreviation']
if comp['homeAway'] == 'home':
home_team = team_abbrev
else:
away_team = team_abbrev
print(f"ESPN API: {away_team} @ {home_team} at {game_date}", flush=True)
# Store game data
games.append({
'date': game_date,
'day_of_week': game_date.strftime('%A'),
'time': game_date.strftime('%I:%M %p'),
'home_team': home_team,
'away_team': away_team,
'teams': [home_team, away_team]
})
except Exception as e:
print(f"ESPN API: Error processing event {i+1}: {str(e)}", flush=True)
else:
print("ESPN API: No 'events' key found in response", flush=True)
print(f"ESPN API: Processed {len(games)} games total", flush=True)
schedule = self._organize_by_day(games)
# Log games by day
for day, day_games in schedule.items():
print(f"ESPN API: {day}: {len(day_games)} games", flush=True)
return schedule
except Exception as e:
print(f"ESPN API: Error fetching schedule: {e}", flush=True)
return {}
def _organize_by_day(self, games):
"""Organize games by day of week - dynamically include all days with games"""
schedule = {}
# Group games by day
for game in games:
day = game['day_of_week']
if day not in schedule:
schedule[day] = []
schedule[day].append(game)
# Sort days by chronological order (Monday=0, Sunday=6)
day_order = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6}
sorted_schedule = {}
for day in sorted(schedule.keys(), key=lambda x: day_order.get(x, 7)):
sorted_schedule[day] = schedule[day]
return sorted_schedule