Skip to content

Commit d59474e

Browse files
authored
Merge pull request #85 from TheFinalJoke/add_full_support_basketball
Add full support basketball
2 parents 7fb58a1 + 87acd9d commit d59474e

File tree

6 files changed

+38
-48
lines changed

6 files changed

+38
-48
lines changed

lib/sports/apisports/apisports.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@ async def run_api_sports(self):
3535
elif 'basketball' == self.sport.get('sport').lower():
3636
self.logger.debug('Got basketball in config')
3737
basketball = Basketball(self.token, self.config['sport'], self.headers)
38-
basketball_return = await basketball.run()
39-
sport_data['Sport'].update({'basketball': basketball_return})
38+
sport_data = await basketball.run()
4039
elif 'hockey' == self.sport.get('sport').lower():
4140
self.logger.debug('Got Hockey from Config')
4241
hockey = Hockey(self.token, self.config['sport'], self.headers)

lib/sports/apisports/basketball/basketball.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from lib.run import Runner
22
from datetime import datetime
3+
from lib.sports.apisports.result import SportApiResult
34

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

3233
async def run(self):
@@ -36,4 +37,4 @@ async def run(self):
3637
for section, url in self.url_builder(parsed).items():
3738
api_data.update({section: await self.get_data(url, self.headers)})
3839
api_data['sport'] = 'basketball'
39-
return api_data
40+
return SportApiResult(api_data)

lib/sports/apisports/hockey/hockey.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def url_builder(self, args):
2525
urls = {}
2626
base = "https://v1.hockey.api-sports.io/"
2727
if 'standings' in args:
28-
urls.update({'standings': base + f'standings?league=57&season=2021'})
28+
urls.update({'standings': base + f'standings?league=57&season=2020'})
2929
if 'next_game' in args:
3030
urls.update({'next_game': base + f"games?team={self.config.getint('team_id')}&league=57&season=2020&timezone=America/Chicago"})
3131
return urls

lib/sports/apisports/result.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,22 @@ def __init__(self, api) -> None:
1313
self._error = self.set_error()
1414
else:
1515
self._error = self.set_error()
16-
if 'standings' in self.main_sport:
17-
self.standings = self.build_standings()
18-
self._length = len(self.standings)
19-
self._positions = [(team.get('name'), team.get('position')) for team in self.standings]
20-
self._leagues = [(team.get('name'), team.get('league')) for team in self.standings]
21-
self._games_played = [(team.get('name'), team.get('games').get('played')) for team in self.standings]
22-
self._wins = [(team.get('name'), team['games']['win']['total']) for team in self.standings]
23-
self._wins_percentage = [(team.get('name'), team['games']['win']['percentage']) for team in self.standings]
24-
self._losses = [(team.get('name'), team['games']['lose']['total']) for team in self.standings]
25-
self._loss_percentage = [(team.get('name'), team['games']['lose']['percentage']) for team in self.standings]
26-
if 'next_game' in self.main_sport:
27-
self.next_game = self.build_nextgame()
28-
self._game_ids = [game.get('game_id') for game in self.next_game]
29-
self._timestamps = [(game.get('game_id'), game.get('timestamp')) for game in self.next_game]
30-
self._teams = [(game.get('game_id'), game.get('teams')) for game in self.next_game]
31-
self._vs = [(game.get('game_id'), (game['teams']['home']['name'], game['teams']['away']['name'])) for game in self.next_game]
32-
self._status = [(game.get('game_id'), game.get('status')) for game in self.next_game]
33-
self._game_result = {game.get('game_id'): game.get('score') for game in self.next_game}
16+
self.standings = self.build_standings()
17+
self._length = len(self.standings)
18+
self._positions = [(team.get('name'), team.get('position')) for team in self.standings]
19+
self._leagues = [(team.get('name'), team.get('league')) for team in self.standings]
20+
self._games_played = [(team.get('name'), team.get('games').get('played')) for team in self.standings]
21+
self._wins = [(team.get('name'), team['games']['win']['total']) for team in self.standings]
22+
self._wins_percentage = [(team.get('name'), team['games']['win']['percentage']) for team in self.standings]
23+
self._losses = [(team.get('name'), team['games']['lose']['total']) for team in self.standings]
24+
self._loss_percentage = [(team.get('name'), team['games']['lose']['percentage']) for team in self.standings]
25+
self.next_game = self.build_nextgame()
26+
self._game_ids = [game.get('game_id') for game in self.next_game]
27+
self._timestamps = [(game.get('game_id'), game.get('timestamp')) for game in self.next_game]
28+
self._teams = [(game.get('game_id'), game.get('teams')) for game in self.next_game]
29+
self._vs = [(game.get('game_id'), (game['teams']['home']['name'], game['teams']['away']['name'])) for game in self.next_game]
30+
self._status = [(game.get('game_id'), game.get('status')) for game in self.next_game]
31+
self._game_result = {game.get('game_id'): game.get('score') for game in self.next_game}
3432

3533
def __repr__(self):
3634
attrs = [

lib/sports/sports.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ async def run(self):
2222
if self.config['sport']['api'] == "api-sports":
2323
api_sports = ApiSports(self.config)
2424
api_result = await api_sports.run_api_sports()
25-
return SportFinal(api_result)
25+
return api_result
2626
return
2727

2828
class SportFinal(Caller):

matrix/sport/sportmatrix.py

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import time
66
import urllib.request
77
from datetime import datetime
8+
from collections import defaultdict
89
from typing import List, Dict, Tuple
910
from collections import deque
1011
from matrix.error import ErrorMatrix
@@ -21,17 +22,12 @@ def __str__(self) -> str:
2122
return "SportMatrix"
2223
async def poll_api(self) -> SportFinal:
2324
return SportFinal(await self.api.run())
24-
25-
def baseball_divisions(self, standings: List[Dict]) -> List[str]:
26-
american_queue = deque(["American League"])
27-
national_queue = deque(["National League"])
28-
for team in standings:
29-
if team["league"] == "American League":
30-
american_queue.append(f"{team['position']}: {team['name']}")
31-
elif team["league"] == "National League":
32-
national_queue.append(f"{team['position']}: {team['name']}")
33-
return list(american_queue), list(national_queue)
3425

26+
def divisions(self, standings: List[Dict]) -> Tuple[List[str], List[str]]:
27+
leagues = {league['league']: [] for league in standings}
28+
for team in standings:
29+
leagues[team['league']].append(f"{team['position']}: {team['name']}")
30+
return leagues
3531
def determine_nextgame(self, nextgame_api):
3632
status: Tuple = ("FT", "ABD")
3733
for game in nextgame_api:
@@ -166,28 +162,28 @@ def build_standings_image(self, api, xpos) -> Tuple[int, int]:
166162
scrolling_font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8)
167163
color = (156,163,173)
168164
# Can't Have multiple images and or buffers
169-
american, national = self.baseball_divisions(api.standings)
170-
american.extend(national)
171-
text = " ".join(american)
165+
divs = self.divisions(api.get_standings)
166+
master = []
167+
for league, names in divs.items():
168+
master.append(f"{league} " + " ".join(names))
169+
text = " ".join(master)
172170
standings_draw.text(
173171
(-xpos, 0),
174172
text,
175173
font=scrolling_font,
176174
fill=color
177-
)
175+
)
176+
178177
return standings_image, (0, 25)
179178

180179
async def render(self, api, loop):
180+
181181
try:
182182
self.clear()
183183
self.reload_image()
184184
if not api.get_error[0]:
185185
raise Exception(api.get_error)
186186
if 'baseball' in api.get_sport:
187-
# Check Data if Offseason if yes Diplay Offseason, Otherwise Display Data
188-
# Check data if Game is active, if yes Display game -> Score Inning AT bat Maybe?
189-
# Else Display next game
190-
# Only do standings right now
191187
self.logger.info("Found Baseball, Displaying Baseball Matrix")
192188
if self.check_offseason(api):
193189
xpos = 0
@@ -214,10 +210,6 @@ async def render(self, api, loop):
214210
time.sleep(30)
215211

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

246238
if 'hockey' in api.get_sport:

0 commit comments

Comments
 (0)