#!/usr/bin/env python """Download fixtures for today""" import argparse import asyncio import datetime import dateparser import typing as tp import arrow import crayons import httpx api_url = "https://statsapi.web.nhl.com/api/v1{}".format def fixtures_url(date: tp.Optional[datetime.date]) -> str: if date is None: # Always better to specify date explicitly, as the NHL API # sometimes gets confused. date = arrow.now().date() return api_url(f"/schedule?date={date.strftime('%Y-%m-%d')}") def start_time(game): return arrow.get(game["gameDate"]).to("US/Pacific") async def get_fixtures(client: httpx.Client, date: datetime.date) -> list[dict]: resp = await client.get(fixtures_url(date)) fixtures = resp.json() try: return fixtures["dates"][0]["games"] except IndexError: return [] def show_game_state(state: str) -> str: if state == "Live": return crayons.green(state, bold=True) else: return state def show_game(g): print( g["gamePk"], start_time(g).strftime("%Y-%m-%d"), start_time(g).strftime("%H:%M"), show_game_state(g["status"]["abstractGameState"]), g["teams"]["home"]["team"]["name"], "v", g["teams"]["away"]["team"]["name"], ) async def main(when: datetime.date): async with httpx.AsyncClient() as c: games = await get_fixtures(c, when) for game in games: show_game(game) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Download NHL game feeds") parser.add_argument( "when", default="today", nargs="?", type=lambda x: dateparser.parse(x).date() ) args = parser.parse_args() asyncio.run(main(args.when))