filtering NFL and MLB games odds to only check games we favorite

This commit is contained in:
Chuck
2025-07-22 10:40:27 -05:00
parent 0a8e543150
commit e238577f36
2 changed files with 71 additions and 24 deletions

View File

@@ -751,6 +751,15 @@ class MLBLiveManager(BaseMLBManager):
# Fetch live game data from MLB API
games = self._fetch_mlb_api_data()
if games:
# --- Optimization: Filter for favorite teams before processing ---
if self.mlb_config.get("show_favorite_teams_only", False) and self.favorite_teams:
games = {
game_id: game for game_id, game in games.items()
if game['home_team'] in self.favorite_teams or game['away_team'] in self.favorite_teams
}
self.logger.info(f"[MLB Live] Filtered to {len(games)} games for favorite teams.")
# Find all live games involving favorite teams
new_live_games = []
for game in games.values():
@@ -1095,6 +1104,14 @@ class MLBRecentManager(BaseMLBManager):
if not games:
logger.warning("[MLB] No games returned from API for recent games update.")
return
# --- Optimization: Filter for favorite teams before processing ---
if self.mlb_config.get("show_favorite_teams_only", False) and self.favorite_teams:
games = {
game_id: game for game_id, game in games.items()
if game['home_team'] in self.favorite_teams or game['away_team'] in self.favorite_teams
}
self.logger.info(f"[MLB Recent] Filtered to {len(games)} games for favorite teams.")
# Process games
new_recent_games = []
@@ -1220,8 +1237,8 @@ class MLBUpcomingManager(BaseMLBManager):
"""Update upcoming games data."""
current_time = time.time()
# Log config state for debugging
self.logger.info(f"[MLB] show_favorite_teams_only: {self.mlb_config.get('show_favorite_teams_only', False)}")
self.logger.info(f"[MLB] favorite_teams: {self.favorite_teams}")
self.logger.debug(f"[MLB] show_favorite_teams_only: {self.mlb_config.get('show_favorite_teams_only', False)}")
self.logger.debug(f"[MLB] favorite_teams: {self.favorite_teams}")
if self.last_update != 0 and (current_time - self.last_update < self.update_interval):
return
@@ -1232,6 +1249,14 @@ class MLBUpcomingManager(BaseMLBManager):
self.logger.warning("[MLB] No games returned from API for upcoming games update.")
return
# --- Optimization: Filter for favorite teams before processing ---
if self.mlb_config.get("show_favorite_teams_only", False) and self.favorite_teams:
games = {
game_id: game for game_id, game in games.items()
if game['home_team'] in self.favorite_teams or game['away_team'] in self.favorite_teams
}
self.logger.info(f"[MLB Upcoming] Filtered to {len(games)} games for favorite teams.")
# Process games
new_upcoming_games = []
@@ -1240,13 +1265,6 @@ class MLBUpcomingManager(BaseMLBManager):
for game_id, game in games.items():
self.logger.debug(f"[MLB] Processing game {game_id} for upcoming games...")
# Only fetch odds for games that will be displayed
if self.mlb_config.get("show_favorite_teams_only", False):
if not self.favorite_teams:
self.logger.info(f"[MLB] Skipping game {game_id} - no favorite teams configured.")
continue
if game['home_team'] not in self.favorite_teams and game['away_team'] not in self.favorite_teams:
self.logger.info(f"[MLB] Skipping non-favorite team game: {game['away_team']} @ {game['home_team']}")
continue
is_favorite_game = (game['home_team'] in self.favorite_teams or
game['away_team'] in self.favorite_teams)
game_time = datetime.fromisoformat(game['start_time'].replace('Z', '+00:00'))
@@ -1263,6 +1281,7 @@ class MLBUpcomingManager(BaseMLBManager):
)
self.logger.info(f"[MLB] Is upcoming: {is_upcoming}")
if is_upcoming:
# The redundant favorite team check from before is already covered by the initial filter
self.logger.info(f"[MLB] Adding game {game_id} to upcoming games list.")
self._fetch_odds(game)
new_upcoming_games.append(game)

View File

@@ -613,20 +613,34 @@ class NFLLiveManager(BaseNFLManager): # Renamed class
self.current_game["down_distance_text"] = f"{['1st','2nd','3rd','4th'][seconds % 4]} & {seconds % 10 + 1}"
self.current_game["status_text"] = f"{self.current_game['period_text']} {self.current_game['clock']}"
# Display update handled by main loop or explicit call if needed immediately
# self.display(force_clear=True) # Only if immediate update is desired here
except ValueError:
self.logger.warning("[NFL] Test mode: Could not parse clock")
# No actual display call here, let main loop handle it
else:
# Fetch live game data
data = self._fetch_data()
new_live_games = []
if data and "events" in data:
for event in data["events"]:
events = data["events"]
# --- Optimization: Filter for favorite teams before extracting details/odds ---
if self.nfl_config.get("show_favorite_teams_only", False) and self.favorite_teams:
filtered_events = []
for event in events:
try:
competitors = event["competitions"][0]["competitors"]
if any(c["team"]["abbreviation"] in self.favorite_teams for c in competitors):
filtered_events.append(event)
except (KeyError, IndexError):
continue # Skip event if data structure is unexpected
events = filtered_events
self.logger.info(f"[NFL Live] Filtered to {len(events)} events for favorite teams.")
for event in events:
details = self._extract_game_details(event)
if details and (details["is_live"] or details["is_halftime"]): # Include halftime as 'live' display
# This second check is somewhat redundant if show_favorite_teams_only is true, but harmless
# And necessary if show_favorite_teams_only is false but favorite_teams has values
if not self.favorite_teams or (
details["home_abbr"] in self.favorite_teams or
details["away_abbr"] in self.favorite_teams
@@ -879,9 +893,10 @@ class NFLRecentManager(BaseNFLManager): # Renamed class
competitors = event["competitions"][0]["competitors"]
if any(c["team"]["abbreviation"] in self.favorite_teams for c in competitors):
filtered_events.append(event)
except Exception:
continue
except (KeyError, IndexError):
continue # Skip event if data structure is unexpected
events = filtered_events
self.logger.info(f"[NFL Recent] Filtered to {len(events)} events for favorite teams.")
# Process games and filter for final & within window & favorite teams
processed_games = []
@@ -894,13 +909,13 @@ class NFLRecentManager(BaseNFLManager): # Renamed class
self._fetch_odds(game)
processed_games.append(game)
# Filter for favorite teams (legacy, in case show_favorite_teams_only is False)
if self.favorite_teams and not self.nfl_config.get("show_favorite_teams_only", False):
# This check is now partially redundant if show_favorite_teams_only is true, but acts as the main filter otherwise
if self.favorite_teams:
team_games = [game for game in processed_games
if game['home_abbr'] in self.favorite_teams or
game['away_abbr'] in self.favorite_teams]
else:
team_games = processed_games # Show all recent games if no favorites defined or already filtered
team_games = processed_games # Show all recent games if no favorites defined
# Sort by game time, most recent first
team_games.sort(key=lambda g: g.get('start_time_utc') or datetime.min.replace(tzinfo=self._get_timezone()), reverse=True)
@@ -1098,21 +1113,34 @@ class NFLUpcomingManager(BaseNFLManager): # Renamed class
competitors = event["competitions"][0]["competitors"]
if any(c["team"]["abbreviation"] in self.favorite_teams for c in competitors):
filtered_events.append(event)
except Exception:
continue
except (KeyError, IndexError):
continue # Skip event if data structure is unexpected
events = filtered_events
self.logger.info(f"[NFL Upcoming] Filtered to {len(events)} events for favorite teams.")
processed_games = []
for event in events:
game = self._extract_game_details(event)
# Filter criteria: must be upcoming ('pre' state)
if game and game['is_upcoming']:
# This check is now partially redundant if show_favorite_teams_only is true, but harmless
# And necessary if show_favorite_teams_only is false but favorite_teams has values
if self.nfl_config.get("show_favorite_teams_only", False):
if not self.favorite_teams:
continue
if game['home_abbr'] not in self.favorite_teams and game['away_abbr'] not in self.favorite_teams:
continue
if self.show_odds:
self._fetch_odds(game)
processed_games.append(game)
# Filter for favorite teams (legacy, in case show_favorite_teams_only is False)
if self.favorite_teams and not self.nfl_config.get("show_favorite_teams_only", False):
# Debug logging to see what games we have
self.logger.debug(f"[NFL Upcoming] Processed {len(processed_games)} upcoming games")
for game in processed_games:
self.logger.debug(f"[NFL Upcoming] Game: {game['away_abbr']}@{game['home_abbr']} - Upcoming: {game['is_upcoming']}")
# This check is now partially redundant if show_favorite_teams_only is true, but acts as the main filter otherwise
if self.favorite_teams:
team_games = [game for game in processed_games
if game['home_abbr'] in self.favorite_teams or
game['away_abbr'] in self.favorite_teams]
@@ -1120,7 +1148,7 @@ class NFLUpcomingManager(BaseNFLManager): # Renamed class
for game in team_games:
self.logger.debug(f"[NFL Upcoming] Favorite game: {game['away_abbr']}@{game['home_abbr']}")
else:
team_games = processed_games # Show all upcoming if no favorites or already filtered
team_games = processed_games # Show all upcoming if no favorites
# Sort by game time, earliest first
team_games.sort(key=lambda g: g.get('start_time_utc') or datetime.max.replace(tzinfo=self._get_timezone()))