Skip to content

Add full support basketball #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions lib/sports/apisports/apisports.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ async def run_api_sports(self):
elif 'basketball' == self.sport.get('sport').lower():
self.logger.debug('Got basketball in config')
basketball = Basketball(self.token, self.config['sport'], self.headers)
basketball_return = await basketball.run()
sport_data['Sport'].update({'basketball': basketball_return})
sport_data = await basketball.run()
elif 'hockey' == self.sport.get('sport').lower():
self.logger.debug('Got Hockey from Config')
hockey = Hockey(self.token, self.config['sport'], self.headers)
Expand Down
7 changes: 4 additions & 3 deletions lib/sports/apisports/basketball/basketball.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from lib.run import Runner
from datetime import datetime
from lib.sports.apisports.result import SportApiResult

class Basketball(Runner):
def __init__(self, token, config, headers):
Expand All @@ -24,9 +25,9 @@ def url_builder(self, args):
urls = {}
base = "https://v1.basketball.api-sports.io/"
if 'standings' in args:
urls.update({'standings': base + f'standings?league=12&season=2020-2021'})
urls.update({'standings': base + f'standings?league=12&season=2019-2020'})
if 'next_game' in args:
urls.update({'next_game': base + f"games?team={self.config.getint('team_id')}&league=12&season=2020-2021&timezone=America/Chicago"})
urls.update({'next_game': base + f"games?team={self.config.getint('team_id')}&league=12&season=2019-2020&timezone=America/Chicago"})
return urls

async def run(self):
Expand All @@ -36,4 +37,4 @@ async def run(self):
for section, url in self.url_builder(parsed).items():
api_data.update({section: await self.get_data(url, self.headers)})
api_data['sport'] = 'basketball'
return api_data
return SportApiResult(api_data)
2 changes: 1 addition & 1 deletion lib/sports/apisports/hockey/hockey.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def url_builder(self, args):
urls = {}
base = "https://v1.hockey.api-sports.io/"
if 'standings' in args:
urls.update({'standings': base + f'standings?league=57&season=2021'})
urls.update({'standings': base + f'standings?league=57&season=2020'})
if 'next_game' in args:
urls.update({'next_game': base + f"games?team={self.config.getint('team_id')}&league=57&season=2020&timezone=America/Chicago"})
return urls
Expand Down
34 changes: 16 additions & 18 deletions lib/sports/apisports/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,22 @@ def __init__(self, api) -> None:
self._error = self.set_error()
else:
self._error = self.set_error()
if 'standings' in self.main_sport:
self.standings = self.build_standings()
self._length = len(self.standings)
self._positions = [(team.get('name'), team.get('position')) for team in self.standings]
self._leagues = [(team.get('name'), team.get('league')) for team in self.standings]
self._games_played = [(team.get('name'), team.get('games').get('played')) for team in self.standings]
self._wins = [(team.get('name'), team['games']['win']['total']) for team in self.standings]
self._wins_percentage = [(team.get('name'), team['games']['win']['percentage']) for team in self.standings]
self._losses = [(team.get('name'), team['games']['lose']['total']) for team in self.standings]
self._loss_percentage = [(team.get('name'), team['games']['lose']['percentage']) for team in self.standings]
if 'next_game' in self.main_sport:
self.next_game = self.build_nextgame()
self._game_ids = [game.get('game_id') for game in self.next_game]
self._timestamps = [(game.get('game_id'), game.get('timestamp')) for game in self.next_game]
self._teams = [(game.get('game_id'), game.get('teams')) for game in self.next_game]
self._vs = [(game.get('game_id'), (game['teams']['home']['name'], game['teams']['away']['name'])) for game in self.next_game]
self._status = [(game.get('game_id'), game.get('status')) for game in self.next_game]
self._game_result = {game.get('game_id'): game.get('score') for game in self.next_game}
self.standings = self.build_standings()
self._length = len(self.standings)
self._positions = [(team.get('name'), team.get('position')) for team in self.standings]
self._leagues = [(team.get('name'), team.get('league')) for team in self.standings]
self._games_played = [(team.get('name'), team.get('games').get('played')) for team in self.standings]
self._wins = [(team.get('name'), team['games']['win']['total']) for team in self.standings]
self._wins_percentage = [(team.get('name'), team['games']['win']['percentage']) for team in self.standings]
self._losses = [(team.get('name'), team['games']['lose']['total']) for team in self.standings]
self._loss_percentage = [(team.get('name'), team['games']['lose']['percentage']) for team in self.standings]
self.next_game = self.build_nextgame()
self._game_ids = [game.get('game_id') for game in self.next_game]
self._timestamps = [(game.get('game_id'), game.get('timestamp')) for game in self.next_game]
self._teams = [(game.get('game_id'), game.get('teams')) for game in self.next_game]
self._vs = [(game.get('game_id'), (game['teams']['home']['name'], game['teams']['away']['name'])) for game in self.next_game]
self._status = [(game.get('game_id'), game.get('status')) for game in self.next_game]
self._game_result = {game.get('game_id'): game.get('score') for game in self.next_game}

def __repr__(self):
attrs = [
Expand Down
2 changes: 1 addition & 1 deletion lib/sports/sports.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async def run(self):
if self.config['sport']['api'] == "api-sports":
api_sports = ApiSports(self.config)
api_result = await api_sports.run_api_sports()
return SportFinal(api_result)
return api_result
return

class SportFinal(Caller):
Expand Down
38 changes: 15 additions & 23 deletions matrix/sport/sportmatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import time
import urllib.request
from datetime import datetime
from collections import defaultdict
from typing import List, Dict, Tuple
from collections import deque
from matrix.error import ErrorMatrix
Expand All @@ -21,17 +22,12 @@ def __str__(self) -> str:
return "SportMatrix"
async def poll_api(self) -> SportFinal:
return SportFinal(await self.api.run())

def baseball_divisions(self, standings: List[Dict]) -> List[str]:
american_queue = deque(["American League"])
national_queue = deque(["National League"])
for team in standings:
if team["league"] == "American League":
american_queue.append(f"{team['position']}: {team['name']}")
elif team["league"] == "National League":
national_queue.append(f"{team['position']}: {team['name']}")
return list(american_queue), list(national_queue)

def divisions(self, standings: List[Dict]) -> Tuple[List[str], List[str]]:
leagues = {league['league']: [] for league in standings}
for team in standings:
leagues[team['league']].append(f"{team['position']}: {team['name']}")
return leagues
def determine_nextgame(self, nextgame_api):
status: Tuple = ("FT", "ABD")
for game in nextgame_api:
Expand Down Expand Up @@ -166,28 +162,28 @@ def build_standings_image(self, api, xpos) -> Tuple[int, int]:
scrolling_font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8)
color = (156,163,173)
# Can't Have multiple images and or buffers
american, national = self.baseball_divisions(api.standings)
american.extend(national)
text = " ".join(american)
divs = self.divisions(api.get_standings)
master = []
for league, names in divs.items():
master.append(f"{league} " + " ".join(names))
text = " ".join(master)
standings_draw.text(
(-xpos, 0),
text,
font=scrolling_font,
fill=color
)
)

return standings_image, (0, 25)

async def render(self, api, loop):

try:
self.clear()
self.reload_image()
if not api.get_error[0]:
raise Exception(api.get_error)
if 'baseball' in api.get_sport:
# Check Data if Offseason if yes Diplay Offseason, Otherwise Display Data
# Check data if Game is active, if yes Display game -> Score Inning AT bat Maybe?
# Else Display next game
# Only do standings right now
self.logger.info("Found Baseball, Displaying Baseball Matrix")
if self.check_offseason(api):
xpos = 0
Expand All @@ -214,10 +210,6 @@ async def render(self, api, loop):
time.sleep(30)

if 'basketball' in api.get_sport:
# Check Data if Offseason if yes Diplay Offseason, Otherwise Display Data
# Check data if Game is active, if yes Display game -> Score Inning AT bat Maybe?
# Else Display next game
# Only do standings right now
self.logger.info("Found Basketball, Displaying Basketball Matrix")
if self.check_offseason(api):
xpos = 0
Expand All @@ -240,7 +232,7 @@ async def render(self, api, loop):
else:
font = ImageFont.truetype("/usr/share/fonts/fonts/04b24.otf", 14)
self.draw_multiline_text((0, 0), "Basketball\nOffseason", font=font)
self.render_image()
await self.render_image()
time.sleep(30)

if 'hockey' in api.get_sport:
Expand Down