m0ranwad / nba-led-scoreboard

NBA LED scoreboard! This project displays matches and scores for all of the current day's NBA action
GNU General Public License v3.0
5 stars 3 forks source link

Get game odds. #4

Closed alexanderthebadatcoding closed 9 months ago

alexanderthebadatcoding commented 10 months ago

I may have figured out a way to get game odds from ESPN. This works for the NFL Matrix but it's slow and may need to be improved.

in the nfl_api_parser.py (or NBA) add:

def get_moneyline_odds(game_id):
    url = f"http://sports.core.api.espn.com/v2/sports/basketball/leagues/nba/events/{game_id}/competitions/{game_id}/odds"

    # Make the API request
    response = requests.get(url)

    # Check if the request was successful (status code 200)
    if response.status_code == 200:
        # Parse the JSON data
        data = response.json()

        # Navigate through the structure to access awayTeamOdds for the first item (index 0)
        items = data.get("items", [])

        if items:
            first_item = items[0]
            away_team_odds = first_item.get("awayTeamOdds", {})
            home_team_odds = first_item.get("homeTeamOdds", {})

            # Extract relevant information from awayTeamOdds
            away_moneyline = away_team_odds.get("moneyLine", "N/A")
            away_ML = f"+{away_moneyline}" if away_moneyline >= 0 else str(away_moneyline)

            # Extract relevant information from homeTeamOdds
            home_moneyline = home_team_odds.get("moneyLine", "N/A")
            home_ML = f"+{home_moneyline}" if home_moneyline >= 0 else str(home_moneyline)

            # Return the moneyline odds for both away and home teams
            return away_ML, home_ML

        else:
            print("No items in the response.")

    else:
        print(f"Request failed with status code: {response.status_code}")

def get_all_games():
    # for i in range(5):
    try:
        res = requests.get(URL)
        res = res.json()
        games = []
        # i = 0
        for g in res['events']:
            info = g['competitions'][0]
            game_id = g['id']

            # Fetch the moneyline odds for the current game
            away_moneyline, home_moneyline = get_moneyline_odds(game_id)
            game = {'id': game_id, 'name': g['shortName'], 'date': g['date'],
                    'hometeam': info['competitors'][0]['team']['abbreviation'], 'homeid': info['competitors'][0]['id'], 'homescore': int(info['competitors'][0]['score']),
                    'awayteam': info['competitors'][1]['team']['abbreviation'], 'awayid': info['competitors'][1]['id'], 'awayscore': int(info['competitors'][1]['score']),
                    'down': info.get('situation', {}).get('shortDownDistanceText'), 'spot': info.get('situation', {}).get('possessionText'),
                    'time': info['status']['displayClock'], 'quarter': info['status']['period'], 'over': info['status']['type']['completed'],
                    'redzone': info.get('situation', {}).get('isRedZone'), 'possession': info.get('situation', {}).get('possession'), 'state': info['status']['type']['state'],
                    'away_moneyline': away_moneyline,'home_moneyline': home_moneyline}
            games.append(game)
            # i += 1
            # print(away_moneyline, home_moneyline)
        return games
    except requests.exceptions.RequestException as e:
        print("Error encountered getting game info, can't hit ESPN api, retrying")
        # if i < 4:
        #     t.sleep(1)
        #     continue
        # else:
        #     print("Can't hit ESPN api after multiple retries, dying ", e)
    except Exception as e:
        print("something bad?", e)

And then add the text results for the "away_moneyline, home_moneyline" to the pre-game renderer.

This works but it slows down the script, so it might need a loading text or image first. Or maybe the code can be optimized.

m0ranwad commented 10 months ago

Nice!

I'll be away for much of Thanksgiving break to hang with the kids, but looking forward to playing with this next week.

alexanderthebadatcoding commented 10 months ago

just have to add something like:

self.draw.text((1, 6), game['away_moneyline'], font=self.font_mini, fill=(0, 255, 0))
self.draw.text((46, 6), game['home_moneyline'], font=self.font_mini, fill=(0, 255, 0))
alexanderthebadatcoding commented 10 months ago

image

m0ranwad commented 9 months ago

Added Here