krz/nba-scores

A CLI/TUI app for NBA scores.

clone: git clone https://gitbay.org/krz/nba-scores.git

main: nba/box_score.py · raw

 1"""
 2Fetches and formats live box scores for individual games.
 3"""
 4
 5import json
 6
 7from nba_api.live.nba.endpoints.boxscore import BoxScore
 8from tabulate import tabulate
 9
10BOLD = "\033[1m"
11END = "\033[0m"
12
13_HEADERS = [
14    "Player",
15    "Pos",
16    "Min",
17    "Pts",
18    "Reb",
19    "Ast",
20    "Stl",
21    "Blk",
22    "TO",
23    "FG",
24    "3P",
25    "FT",
26    "+/-",
27]
28
29
30def fetch_box_score(game_id: str) -> dict:
31    endpoint = BoxScore(game_id=game_id)
32    return json.loads(endpoint.get_json())
33
34
35def _parse_minutes(raw: str) -> str:
36    """Convert 'PT35M24.00S''35:24'."""
37    if not raw:
38        return "0:00"
39    try:
40        raw = raw.replace("PT", "").replace("S", "")
41        mins, secs = raw.split("M")
42        return f"{int(mins)}:{int(float(secs)):02d}"
43    except Exception:
44        return raw
45
46
47def _player_rows(players: list) -> list:
48    rows = []
49    for p in players:
50        if p.get("status") == "INACTIVE":
51            continue
52        s = p.get("statistics", {})
53        rows.append(
54            [
55                p.get("name", ""),
56                p.get("position", ""),
57                _parse_minutes(s.get("minutes", "")),
58                s.get("points", 0),
59                s.get("reboundsTotal", 0),
60                s.get("assists", 0),
61                s.get("steals", 0),
62                s.get("blocks", 0),
63                s.get("turnovers", 0),
64                f"{s.get('fieldGoalsMade', 0)}/{s.get('fieldGoalsAttempted', 0)}",
65                f"{s.get('threePointersMade', 0)}/{s.get('threePointersAttempted', 0)}",
66                f"{s.get('freeThrowsMade', 0)}/{s.get('freeThrowsAttempted', 0)}",
67                s.get("plusMinusPoints", 0),
68            ]
69        )
70    return rows
71
72
73def get_box_score_tables(data: dict) -> tuple:
74    """Return (home_table_str, away_table_str)."""
75    game = data["game"]
76    home = game["homeTeam"]
77    away = game["awayTeam"]
78
79    home_rows = _player_rows(home.get("players", []))
80    away_rows = _player_rows(away.get("players", []))
81
82    home_table = (
83        f"{BOLD}{home['teamCity']} {home['teamName']} ({home['score']}){END}\n"
84        + tabulate(home_rows, headers=_HEADERS, tablefmt="grid")
85    )
86    away_table = (
87        f"{BOLD}{away['teamCity']} {away['teamName']} ({away['score']}){END}\n"
88        + tabulate(away_rows, headers=_HEADERS, tablefmt="grid")
89    )
90    return home_table, away_table