5454fdc0 |
#!/usr/bin/env python
"""Download fixtures for today"""
import argparse
import asyncio
|
cf8b96d9 |
import datetime
|
29fb5c13 |
import dateparser
|
cf8b96d9 |
import typing as tp
|
5454fdc0 |
|
cf8b96d9 |
import arrow
|
442caf16 |
import crayons
|
5454fdc0 |
import httpx
api_url = "https://statsapi.web.nhl.com/api/v1{}".format
|
cf8b96d9 |
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')}")
|
5454fdc0 |
def start_time(game):
|
c4590423 |
return arrow.get(game["gameDate"]).to("US/Pacific")
|
5454fdc0 |
|
69004ec2 |
async def get_fixtures(client: httpx.Client, date: datetime.date) -> list[dict]:
|
cf8b96d9 |
resp = await client.get(fixtures_url(date))
|
5454fdc0 |
fixtures = resp.json()
|
69004ec2 |
try:
return fixtures["dates"][0]["games"]
except IndexError:
return []
|
cf8b96d9 |
|
442caf16 |
def show_game_state(state: str) -> str:
if state == "Live":
return crayons.green(state, bold=True)
else:
return state
|
cf8b96d9 |
def show_game(g):
print(
g["gamePk"],
|
3ef0f7ca |
start_time(g).strftime("%Y-%m-%d"),
|
cf8b96d9 |
start_time(g).strftime("%H:%M"),
|
442caf16 |
show_game_state(g["status"]["abstractGameState"]),
|
cf8b96d9 |
g["teams"]["home"]["team"]["name"],
"v",
g["teams"]["away"]["team"]["name"],
)
|
5454fdc0 |
|
29fb5c13 |
async def main(when: datetime.date):
|
5454fdc0 |
async with httpx.AsyncClient() as c:
|
29fb5c13 |
games = await get_fixtures(c, when)
|
cf8b96d9 |
for game in games:
show_game(game)
|
5454fdc0 |
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Download NHL game feeds")
|
29fb5c13 |
parser.add_argument(
"when", default="today", nargs="?", type=lambda x: dateparser.parse(x).date()
)
|
5454fdc0 |
args = parser.parse_args()
|
29fb5c13 |
asyncio.run(main(args.when))
|