diff --git a/bots/nhl_game_threads/__init__.py b/bots/nhl_game_threads/__init__.py index 02bd9ed..9111e7b 100644 --- a/bots/nhl_game_threads/__init__.py +++ b/bots/nhl_game_threads/__init__.py @@ -32,7 +32,7 @@ import praw -__version__ = "1.0.4" +__version__ = "2.0.0" DATA_LOCK = threading.Lock() @@ -153,37 +153,6 @@ def run(self): ) self.nhl = pynhlapi.API() - # Get info about configured team - if self.settings.get("NHL", {}).get("TEAM", "") == "": - self.log.critical("No team selected! Set NHL > TEAM in Bot Config.") - self.bot.STOP = True - break - - self.allTeams = self.nhl.teams() - self.myTeamId = int( - self.settings.get("NHL", {}).get("TEAM", "").split("|")[1] - ) - self.log.debug(f"{self.myTeamId=}") - self.myTeam = next( - (t for t in self.allTeams if t["id"] == self.myTeamId), None - ) - if not self.myTeam: - self.log.critical( - "Unable to look up team info! Check NHL > TEAM in Bot Config." - ) - self.bot.STOP = True - break - self.log.info("Configured team: {}".format(self.myTeam["name"])) - self.log.debug(f"{self.myTeam=}") - - # Other division teams - self.otherDivisionTeams = [ - t - for t in self.allTeams - if t["division"]["id"] == self.myTeam["division"]["id"] - ] - self.otherDivisionTeamIds = [t["id"] for t in self.otherDivisionTeams] - if todayOverrideFlag: self.log.info( "Overriding game date per GAME_DATE_OVERRIDE setting [{}].".format( @@ -222,38 +191,62 @@ def run(self): False # Only override once, then go back to current date ) - # Get today's games - todayAllGames = self.nhl.schedule( - self.today["Y-m-d"], - expand="schedule.linescore,schedule.venue,schedule.broadcasts,schedule.radioBroadcasts", + # Get info about configured team + if self.settings.get("NHL", {}).get("TEAM", "") == "": + self.log.critical("No team selected! Set NHL > TEAM in Bot Config.") + self.bot.STOP = True + break + + self.allTeams = self.nhl.teams_with_conf_div(self.today["Y-m-d"]) + self.myTeamId = int( + self.settings.get("NHL", {}).get("TEAM", "").split("|")[1] ) - todayAllGames = next( - ( - x["games"] - for x in todayAllGames["dates"] - if x["date"] == self.today["Y-m-d"] - ), - [], + self.log.debug(f"{self.myTeamId=}") + self.myTeam = next( + (t for t in self.allTeams if t["id"] == self.myTeamId), None + ) + if not self.myTeam: + self.log.critical( + "Unable to look up team info! Check NHL > TEAM in Bot Config." + ) + self.bot.STOP = True + break + self.log.info("Configured team: {}".format(self.myTeam["name"])) + self.log.debug(f"{self.myTeam=}") + + # Other division teams + self.otherDivisionTeams = [ + t + for t in self.allTeams + if t["isNhl"] and t["divisionAbbrev"] == self.myTeam["divisionAbbrev"] + ] + self.otherDivisionTeamIds = [t["id"] for t in self.otherDivisionTeams] + self.otherDivisionTeamAbbrevs = [ + t["abbrev"] for t in self.otherDivisionTeams + ] + + # Get today's games + todayAllGames = self.nhl.scoreboard( + start_date=self.today["Y-m-d"], + end_date=self.today["Y-m-d"], + # expand="schedule.linescore,schedule.venue,schedule.broadcasts,schedule.radioBroadcasts", ) todayGames = [ x for x in todayAllGames - if self.myTeam["id"] - in [x["teams"]["away"]["team"]["id"], x["teams"]["home"]["team"]["id"]] + if self.myTeam["id"] in [x["awayTeam"]["id"], x["homeTeam"]["id"]] ] - todayOtherGames = [ + todayOtherGames = [x for x in todayAllGames if x not in todayGames] + todayOtherDivisionGames = [ x - for x in todayAllGames - if self.myTeam["id"] - not in [ - x["teams"]["away"]["team"]["id"], - x["teams"]["home"]["team"]["id"], - ] + for x in todayOtherGames + if x["awayTeam"]["id"] in self.otherDivisionTeamIds + or x["homeTeam"]["id"] in self.otherDivisionTeamIds ] self.log.debug(f"Today's game(s): {todayGames}") if len(todayGames) > 1: self.log.warning( - f"Multiple games found, but only one game supported per day: {[g['gamePk'] for g in todayGames]}" + f"Multiple games found, but only one game supported per day: {[g['id'] for g in todayGames]}" ) # (Re-)Initialize dict to hold game data @@ -263,7 +256,9 @@ def run(self): "todayGames": todayGames, "otherDivisionTeams": self.otherDivisionTeams, "otherDivisionTeamIds": self.otherDivisionTeamIds, + "otherDivisionTeamAbbrevs": self.otherDivisionTeamAbbrevs, "todayOtherGames": todayOtherGames, + "todayOtherDivisionGames": todayOtherDivisionGames, "teamSubs": self.teamSubs, "teamSubsById": self.teamSubsById, } @@ -281,15 +276,15 @@ def run(self): if redball.SIGNAL is not None or self.bot.STOP: break else: - gamePk = todayGames[0]["gamePk"] + gamePk = todayGames[0]["id"] self.log.info("IT'S GAME DAY!") self.log.debug(f"Gathering initial data for gamePk [{gamePk}]...") game = self.nhl.game(gamePk) homeAway = ( "home" - if game["gameData"]["teams"]["home"]["id"] == self.myTeam["id"] + if game["homeTeam"]["id"] == self.myTeam["id"] else "away" - if game["gameData"]["teams"]["away"]["id"] == self.myTeam["id"] + if game["awayTeam"]["id"] == self.myTeam["id"] else None ) self.log.debug(f"My team is [{homeAway}] (homeAway)") @@ -299,9 +294,9 @@ def run(self): for x in self.allTeams if x["id"] == ( - game["gameData"]["teams"]["home"]["id"] + game["homeTeam"]["id"] if homeAway == "away" - else game["gameData"]["teams"]["away"]["id"] + else game["awayTeam"]["id"] ) ), None, @@ -311,37 +306,32 @@ def run(self): self.log.debug(f"oppTeam: {oppTeam}") gameTime = ( self.convert_timezone( # Convert Zulu to my team TZ - datetime.strptime( - game["gameData"]["datetime"]["dateTime"], - "%Y-%m-%dT%H:%M:%SZ", + datetime.fromisoformat(game["startTimeUTC"]), + self.settings.get("Bot", {}).get( + "TEAM_TIMEZONE", "America/New_York" ), - self.myTeam["venue"]["timeZone"]["id"], ) # .replace(tzinfo=None) # .isoformat() # Convert back to tz-naive ) gameTime_homeTeam = ( self.convert_timezone( # Convert Zulu to my team TZ - datetime.strptime( - game["gameData"]["datetime"]["dateTime"], - "%Y-%m-%dT%H:%M:%SZ", - ), - game["gameData"]["teams"]["home"]["venue"]["timeZone"]["id"], + datetime.fromisoformat(game["startTimeUTC"]), + game["venueTimezone"], ) .replace(tzinfo=None) .isoformat() # Convert back to tz-naive ) gameTime_local = self.convert_timezone( # Convert Zulu to my team TZ - datetime.strptime( - game["gameData"]["datetime"]["dateTime"], "%Y-%m-%dT%H:%M:%SZ" - ), + datetime.fromisoformat(game["startTimeUTC"]), "local", ) self.log.debug( f"gameTime (my team TZ): {gameTime}; gameTime_homeTeam: {gameTime_homeTeam}; gameTime_local: {gameTime_local}" ) - standings = self.nhl.standings(self.today["season"]["seasonId"]) - content = self.nhl.game_content(gamePk) + standings = self.nhl.standings(self.today["Y-m-d"]) + game_boxscore = self.nhl.game_boxscore(gamePk) + game_pbp = self.nhl.game_playbyplay(gamePk) # Initialize var to hold game data throughout the day self.allData.update( @@ -356,7 +346,8 @@ def run(self): "myTeam": gameTime, }, "game": game, - "content": content, + "game_boxscore": game_boxscore, + "game_pbp": game_pbp, "standings": standings, } ) @@ -408,7 +399,7 @@ def run(self): { "game": threading.Thread( target=self.game_thread_update_loop, - args=(g["gamePk"],), + args=(g["id"],), name="bot-{}-{}-game".format( self.bot.id, self.bot.name.replace(" ", "-"), @@ -493,7 +484,7 @@ def run(self): { "game": threading.Thread( target=self.game_thread_update_loop, - args=(g["gamePk"],), + args=(g["id"],), name="bot-{}-{}-game".format( self.bot.id, self.bot.name.replace(" ", "-"), @@ -664,6 +655,24 @@ def run(self): }, } + def game_is_final(self, game=None): + if not game: + game = self.allData.get("game", {}) + if game.get("gameState", "UNKNOWN") in [ + "FINAL", + "OFF", + "OVER", + ]: + return True + if game.get("gameScheduleState", "UNKNOWN") in [ + "PPD", + "SUSP", + "CNCL", + ]: + return True + + return False + def tailgate_thread_update_loop(self): skipFlag = None # Will be set later if tailgate thread edit should be skipped @@ -914,30 +923,16 @@ def tailgate_thread_update_loop(self): self.stopFlags.update({"tailgate": True}) break elif update_tailgate_thread_until == "All division games are final": - if ( # This game is final - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ) and not next( # And all division games are final - ( - True - for x in self.allData["todayOtherGames"] - if x["status"]["abstractGameState"] != "Final" - and x["status"]["statusCode"] != "9" # Postponed - and any( - ( - True - for divTeam in self.otherDivisionTeams - if divTeam["id"] - in [ - x["teams"]["away"]["team"]["id"], - x["teams"]["home"]["team"]["id"], - ] - ) - ) - ), - False, + if ( + self.game_is_final() + and not next( # And all division games are final + ( + True + for x in self.allData["todayOtherDivisionGames"] + if not self.game_is_final(x) + ), + False, + ) ): # Division games are all final self.log.info( @@ -946,17 +941,11 @@ def tailgate_thread_update_loop(self): self.stopFlags.update({"tailgate": True}) break elif update_tailgate_thread_until == "All NHL games are final": - if ( # This game is final - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ) and not next( # All NHL games are final + if self.game_is_final() and not next( # All NHL games are final ( True for x in self.allData["todayOtherGames"] - if x["status"]["abstractGameState"] != "Final" - and x["status"]["statusCode"] != "9" # Postponed + if not self.game_is_final(x) ), False, ): @@ -1082,12 +1071,7 @@ def game_thread_update_loop(self, gamePk): and not self.bot.STOP and not self.threadCache["game"].get("thread") ): - if ( - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ): + if self.game_is_final(): if not self.settings.get("Post Game Thread", {}).get( "ENABLED", True ): @@ -1104,20 +1088,15 @@ def game_thread_update_loop(self, gamePk): # Post game thread is enabled, so skip game thread self.log.info( "Game is {}; skipping game thread...".format( - self.allData["game"]["gameData"]["status"][ - "detailedState" - ], + self.allData["game"]["gameState"], ) ) skipFlag = True break - elif ( - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Live" - ): - # Game is already in live status (including halftime), so submit the game thread! + elif self.allData["game"]["gameState"] in ["LIVE", "CRIT"]: + # Game is already in live status (including intermissions), so submit the game thread! self.log.info( - "It's technically not time to submit the game thread yet, but the game status is INGAME/HALFTIME. Proceeding..." + "It's technically not time to submit the game thread yet, but the game status is LIVE. Proceeding..." ) break elif not self.settings.get("Game Thread", {}).get("ENABLED", True): @@ -1232,22 +1211,21 @@ def game_thread_update_loop(self, gamePk): if text != self.threadCache["game"].get("text") and text != "": self.threadCache["game"].update({"text": text}) # Add last updated timestamp - text += ( - """ + text += """ -^^^Last ^^^Updated: ^^^""" - + self.convert_timezone( - datetime.utcnow(), - self.settings.get("Bot", {}).get( - "TEAM_TIMEZONE", "America/New_York" - ), - ).strftime("%m/%d/%Y ^^^%I:%M:%S ^^^%p ^^^%Z") +^^^Last ^^^Updated: ^^^""" + self.convert_timezone( + datetime.utcnow(), + self.settings.get("Bot", {}).get( + "TEAM_TIMEZONE", "America/New_York" + ), + ).strftime( + "%m/%d/%Y ^^^%I:%M:%S ^^^%p ^^^%Z" ) self.threadCache["game"]["thread"].edit(text) self.log.info("Edits submitted for game thread.") self.count_check_edit( self.threadCache["game"]["thread"].id, - self.allData["game"]["gameData"]["status"]["statusCode"], + self.allData["game"]["gameState"], edit=True, ) self.log_last_updated_date_in_db( @@ -1261,7 +1239,7 @@ def game_thread_update_loop(self, gamePk): self.log.info("No changes to game thread.") self.count_check_edit( self.threadCache["game"]["thread"].id, - self.allData["game"]["gameData"]["status"]["statusCode"], + self.allData["game"]["gameState"], edit=False, ) @@ -1285,12 +1263,7 @@ def game_thread_update_loop(self, gamePk): self.stopFlags.update({"game": True}) break elif update_game_thread_until == "My team's game is final": - if ( - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ): + if self.game_is_final(): # My team's game is final self.log.info( "My team's game is final. Stopping game thread update loop per UPDATE_UNTIL setting." @@ -1298,30 +1271,16 @@ def game_thread_update_loop(self, gamePk): self.stopFlags.update({"game": True}) break elif update_game_thread_until == "All division games are final": - if ( # This game is final - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ) and not next( # And all division games are final - ( - True - for x in self.allData["todayOtherGames"] - if x["status"]["abstractGameState"] != "Final" - and x["status"]["statusCode"] != "9" # Postponed - and any( - ( - True - for divTeam in self.otherDivisionTeams - if divTeam["id"] - in [ - x["teams"]["away"]["team"]["id"], - x["teams"]["home"]["team"]["id"], - ] - ) - ) - ), - False, + if ( + self.game_is_final() + and not next( # And all division games are final + ( + True + for x in self.allData["todayOtherDivisionGames"] + if not self.game_is_final(x) + ), + False, + ) ): # Division games are all final self.log.info( @@ -1330,17 +1289,11 @@ def game_thread_update_loop(self, gamePk): self.stopFlags.update({"game": True}) break elif update_game_thread_until == "All NHL games are final": - if ( # This game is final - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ) and not next( # All NHL games are final + if self.game_is_final() and not next( # All NHL games are final ( True for x in self.allData["todayOtherGames"] - if x["status"]["abstractGameState"] != "Final" - and x["status"]["statusCode"] != "9" # Postponed + if self.game_is_final(x) ), False, ): @@ -1357,10 +1310,7 @@ def game_thread_update_loop(self, gamePk): ) ) # debug - need this to tell if logic is working - if ( - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Live" - ): + if self.allData["game"]["gameState"] in ["LIVE", "CRIT", "OVER"]: # Update interval is in seconds (minutes for all other cases) gtWait = self.settings.get("Game Thread", {}).get("UPDATE_INTERVAL", 10) if gtWait < 1: @@ -1380,7 +1330,7 @@ def game_thread_update_loop(self, gamePk): gtnlWait = 1 self.log.info( "Game is not live ({}), sleeping for {} minutes...".format( - self.allData["game"]["gameData"]["status"]["detailedState"], + self.allData["game"]["gameState"], gtnlWait, ) ) @@ -1406,30 +1356,33 @@ def postgame_thread_update_loop(self): ) while redball.SIGNAL is None and not self.bot.STOP: - if ( - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ): + if not self.settings.get("Game Thread", {}).get("ENABLED", True): + # Game thread is disabled, so ensure we have fresh data + self.log.info( + f"Game thread is disabled, so updating data... current gameState: {self.allData['game']['gameState']}" + ) + self.collect_data() + if self.game_is_final(): # Game is over self.log.info( "Game is over ({}). Proceeding with post game thread...".format( - self.allData["game"]["gameData"]["status"]["detailedState"], + self.allData["game"]["gameState"], ) ) break - elif self.stopFlags["game"]: - # Game thread process has stopped, but game status isn't final yet... get fresh data! + elif self.stopFlags["game"] and self.settings.get("Game Thread", {}).get( + "ENABLED", True + ): + # Game thread is enabled and process has stopped, but game status isn't final yet... get fresh data! self.log.info( - f"Game thread process has ended, but cached game status is still ({self.allData['game']['gameData']['status']['detailedState']}). Refreshing data..." + f"Game thread process has ended, but cached game status is still ({self.allData['game']['gameState']}). Refreshing data..." ) # Update data self.collect_data() else: self.log.debug( "Game is not yet final ({}). Sleeping for 1 minute...".format( - self.allData["game"]["gameData"]["status"]["detailedState"], + self.allData["game"]["gameState"], ) ) self.sleep(60) @@ -1550,16 +1503,15 @@ def postgame_thread_update_loop(self): self.log.debug(f"Rendered post game thread text: {text}") if text != self.threadCache["post"]["text"] and text != "": self.threadCache["post"]["text"] = text - text += ( - """ + text += """ -^^^Last ^^^Updated: ^^^""" - + self.convert_timezone( - datetime.utcnow(), - self.settings.get("Bot", {}).get( - "TEAM_TIMEZONE", "America/New_York" - ), - ).strftime("%m/%d/%Y ^^^%I:%M:%S ^^^%p ^^^%Z") +^^^Last ^^^Updated: ^^^""" + self.convert_timezone( + datetime.utcnow(), + self.settings.get("Bot", {}).get( + "TEAM_TIMEZONE", "America/New_York" + ), + ).strftime( + "%m/%d/%Y ^^^%I:%M:%S ^^^%p ^^^%Z" ) self.threadCache["post"]["thread"].edit(text) self.log.info("Post game thread edits submitted.") @@ -1568,7 +1520,7 @@ def postgame_thread_update_loop(self): ) self.count_check_edit( self.threadCache["post"]["thread"].id, - self.allData["game"]["gameData"]["status"]["statusCode"], + self.allData["game"]["gameState"], edit=True, ) elif text == "": @@ -1579,7 +1531,7 @@ def postgame_thread_update_loop(self): self.log.info("No changes to post game thread.") self.count_check_edit( self.threadCache["post"]["thread"].id, - self.allData["game"]["gameData"]["status"]["statusCode"], + self.allData["game"]["gameState"], edit=False, ) except Exception as e: @@ -1623,30 +1575,16 @@ def postgame_thread_update_loop(self): self.stopFlags.update({"post": True}) break elif update_postgame_thread_until == "All division games are final": - if ( # This game is final - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ) and not next( # And all division games are final - ( - True - for x in self.allData["todayOtherGames"] - if x["status"]["abstractGameState"] != "Final" - and x["status"]["statusCode"] != "9" # Postponed - and any( - ( - True - for divTeam in self.otherDivisionTeams - if divTeam["id"] - in [ - x["teams"]["away"]["team"]["id"], - x["teams"]["home"]["team"]["id"], - ] - ) - ) - ), - False, + if ( + self.game_is_final() + and not next( # And all division games are final + ( + True + for x in self.allData["todayOtherDivisionGames"] + if self.game_is_final(x) + ), + False, + ) ): # Division games are all final self.log.info( @@ -1655,17 +1593,11 @@ def postgame_thread_update_loop(self): self.stopFlags.update({"post": True}) break elif update_postgame_thread_until == "All NHL games are final": - if ( # This game is final - self.allData["game"]["gameData"]["status"]["abstractGameState"] - == "Final" - or self.allData["game"]["gameData"]["status"]["statusCode"] - == "9" # Postponed - ) and not next( # All NHL games are final + if self.game_is_final() and not next( # All NHL games are final ( True for x in self.allData["todayOtherGames"] - if x["status"]["abstractGameState"] != "Final" - and x["status"]["statusCode"] != "9" # Postponed + if self.game_is_final(x) ), False, ): @@ -1721,40 +1653,30 @@ def collect_data(self): # Collect the data... # Get today's games - todayAllGames = self.nhl.schedule( - self.today["Y-m-d"], - expand="schedule.linescore,schedule.venue,schedule.broadcasts,schedule.radioBroadcasts", - ) - todayAllGames = next( - ( - x["games"] - for x in todayAllGames["dates"] - if x["date"] == self.today["Y-m-d"] - ), - [], + todayAllGames = self.nhl.scoreboard( + start_date=self.today["Y-m-d"], + end_date=self.today["Y-m-d"], + # expand="schedule.linescore,schedule.venue,schedule.broadcasts,schedule.radioBroadcasts", ) todayGames = [ x for x in todayAllGames - if self.myTeam["id"] - in [x["teams"]["away"]["team"]["id"], x["teams"]["home"]["team"]["id"]] + if self.myTeam["id"] in [x["awayTeam"]["id"], x["homeTeam"]["id"]] ] - todayOtherGames = [ + todayOtherGames = [x for x in todayAllGames if x not in todayGames] + todayOtherDivisionGames = [ x - for x in todayAllGames - if self.myTeam["id"] - not in [ - x["teams"]["away"]["team"]["id"], - x["teams"]["home"]["team"]["id"], - ] + for x in todayOtherGames + if x["awayTeam"]["id"] in self.otherDivisionTeamIds + or x["homeTeam"]["id"] in self.otherDivisionTeamIds ] self.log.debug(f"Gathering data for gamePk [{self.allData['gamePk']}]...") game = self.nhl.game(self.allData["gamePk"]) homeAway = ( "home" - if game["gameData"]["teams"]["home"]["id"] == self.myTeam["id"] + if game["homeTeam"]["id"] == self.myTeam["id"] else "away" - if game["gameData"]["teams"]["away"]["id"] == self.myTeam["id"] + if game["awayTeam"]["id"] == self.myTeam["id"] else None ) self.log.debug(f"My team is [{homeAway}] (homeAway)") @@ -1764,9 +1686,9 @@ def collect_data(self): for x in self.allTeams if x["id"] == ( - game["gameData"]["teams"]["home"]["id"] + game["homeTeam"]["id"] if homeAway == "away" - else game["gameData"]["teams"]["away"]["id"] + else game["awayTeam"]["id"] ) ), None, @@ -1776,35 +1698,32 @@ def collect_data(self): self.log.debug(f"oppTeam: {oppTeam}") gameTime = ( self.convert_timezone( # Convert Zulu to my team TZ - datetime.strptime( - game["gameData"]["datetime"]["dateTime"], "%Y-%m-%dT%H:%M:%SZ" + datetime.fromisoformat(game["startTimeUTC"]), + self.settings.get("Bot", {}).get( + "TEAM_TIMEZONE", "America/New_York" ), - self.myTeam["venue"]["timeZone"]["id"], ) # .replace(tzinfo=None) # .isoformat() # Convert back to tz-naive ) gameTime_homeTeam = ( self.convert_timezone( # Convert Zulu to my team TZ - datetime.strptime( - game["gameData"]["datetime"]["dateTime"], "%Y-%m-%dT%H:%M:%SZ" - ), - game["gameData"]["teams"]["home"]["venue"]["timeZone"]["id"], + datetime.fromisoformat(game["startTimeUTC"]), + game["venueTimezone"], ) .replace(tzinfo=None) .isoformat() # Convert back to tz-naive ) gameTime_local = self.convert_timezone( # Convert Zulu to my team TZ - datetime.strptime( - game["gameData"]["datetime"]["dateTime"], "%Y-%m-%dT%H:%M:%SZ" - ), + datetime.fromisoformat(game["startTimeUTC"]), "local", ) self.log.debug( f"gameTime (my team TZ): {gameTime}; gameTime_homeTeam: {gameTime_homeTeam}; gameTime_local: {gameTime_local}" ) - standings = self.nhl.standings(self.today["season"]["seasonId"]) - content = self.nhl.game_content(self.allData["gamePk"]) + standings = self.nhl.standings(self.today["Y-m-d"]) + game_boxscore = self.nhl.game_boxscore(self.allData["gamePk"]) + game_pbp = self.nhl.game_playbyplay(self.allData["gamePk"]) # Initialize var to hold game data throughout the day self.allData.update( @@ -1819,8 +1738,10 @@ def collect_data(self): "myTeam": gameTime, }, "game": game, - "content": content, + "game_boxscore": game_boxscore, + "game_pbp": game_pbp, "todayOtherGames": todayOtherGames, + "todayOtherDivisionGames": todayOtherDivisionGames, "standings": standings, } ) @@ -2133,8 +2054,8 @@ def prep_and_post(self, thread, postFooter=None): else: self.notify_prowl( apiKey=prowlKey, - event=f"{self.myTeam['teamName']} {thread.title()} Thread Posted", - description=f"""{self.myTeam['teamName']} {thread} thread was posted to r/{self.settings["Reddit"]["SUBREDDIT"]} at {self.convert_timezone(datetime.utcfromtimestamp(theThread.created_utc),'local').strftime('%I:%M %p %Z')}\nThread title: {theThread.title}\nURL: {theThread.shortlink}""", + event=f"{self.myTeam['commonName']} {thread.title()} Thread Posted", + description=f"""{self.myTeam['commonName']} {thread} thread was posted to r/{self.settings["Reddit"]["SUBREDDIT"]} at {self.convert_timezone(datetime.utcfromtimestamp(theThread.created_utc),'local').strftime('%I:%M %p %Z')}\nThread title: {theThread.title}\nURL: {theThread.shortlink}""", priority=prowlPriority, url=theThread.shortlink, appName=f"redball - {self.bot.name}", @@ -2157,11 +2078,11 @@ def prep_and_post(self, thread, postFooter=None): self.log.debug("Twitter disabled or not configured") else: if thread == "game": - message = f"""{theThread.title} - Join the discussion: {theThread.shortlink} #{self.myTeam['teamName'].replace(' ','')}""" + message = f"""{theThread.title} - Join the discussion: {theThread.shortlink} #{self.myTeam['commonName'].replace(' ','')}""" elif thread == "tailgate": - message = f"""{theThread.title} - Join the discussion: {theThread.shortlink} #{self.myTeam['teamName'].replace(' ','')}""" + message = f"""{theThread.title} - Join the discussion: {theThread.shortlink} #{self.myTeam['commonName'].replace(' ','')}""" elif thread == "post": - message = f"""{theThread.title} - The discussion continues: {theThread.shortlink} #{self.myTeam['teamName'].replace(' ','')}""" + message = f"""{theThread.title} - The discussion continues: {theThread.shortlink} #{self.myTeam['commonName'].replace(' ','')}""" else: self.log.error(f"Can't tweet about unknown thread type [{thread}]!") return (None, text) @@ -2469,7 +2390,7 @@ def render_template(self, thread, templateType, **kwargs): if ( self.settings.get("Bot", {}).get("NO_CAPS_AGAINST_CAPS") - and self.allData.get("oppTeam", {}).get("teamName") == "Capitals" + and self.allData.get("oppTeam", {}).get("commonName") == "Capitals" ): self.log.debug("no caps!") text = text.lower() @@ -2789,9 +2710,9 @@ def bot_state(self): "myTeam": { "id": self.myTeam["id"], "name": self.myTeam["name"], - "abbreviation": self.myTeam["abbreviation"], - "teamName": self.myTeam["teamName"], - "locationName": self.myTeam["locationName"], + "abbreviation": self.myTeam["abbrev"], + "teamName": self.myTeam["commonName"], + "locationName": self.myTeam["placeName"], }, "today": self.today, "tailgateThread": { diff --git a/bots/nhl_game_threads/pynhlapi/__init__.py b/bots/nhl_game_threads/pynhlapi/__init__.py index 984d7bc..5ba1e35 100644 --- a/bots/nhl_game_threads/pynhlapi/__init__.py +++ b/bots/nhl_game_threads/pynhlapi/__init__.py @@ -3,6 +3,6 @@ from .constants import APP_NAME from .api import API -__version__ = "0.0.2" +__version__ = "0.1.0" logger = logging.Logger(APP_NAME) diff --git a/bots/nhl_game_threads/pynhlapi/api.py b/bots/nhl_game_threads/pynhlapi/api.py index 29f6323..6e31271 100644 --- a/bots/nhl_game_threads/pynhlapi/api.py +++ b/bots/nhl_game_threads/pynhlapi/api.py @@ -8,69 +8,75 @@ class API: - def __init__(self, api_url=constants.API_URL): - self.api_url = api_url - logger.debug(f"Set API URL to {self.api_url}") + def __init__(self): + pass - def game(self, game_pk, json=True, **kwargs): - url = f"{self.api_url}{constants.GAME_ENDPOINT.format(game_pk=game_pk)}" + def game(self, game_pk, **kwargs): + url = f"{constants.GAME_ENDPOINT.format(game_pk=game_pk)}" url = self.add_kwargs_to_url(url, kwargs) json = self.get_json(url) if json: return json - def game_content(self, game_pk, json=True, **kwargs): - url = f"{self.api_url}{constants.GAME_CONTENT_ENDPOINT.format(game_pk=game_pk)}" + def game_boxscore(self, game_pk, **kwargs): + url = f"{constants.GAME_BOXSCORE_ENDPOINT.format(game_pk=game_pk)}" url = self.add_kwargs_to_url(url, kwargs) json = self.get_json(url) if json: return json - def schedule( + def game_playbyplay(self, game_pk, **kwargs): + url = f"{constants.GAME_PLAYBYPLAY_ENDPOINT.format(game_pk=game_pk)}" + url = self.add_kwargs_to_url(url, kwargs) + json = self.get_json(url) + if json: + return json + + def scoreboard( self, start_date=datetime.today().strftime("%Y-%m-%d"), end_date=None, team_id=None, - json=True, **kwargs, ): - url = f"{self.api_url}{constants.SCHEDULE_ENDPOINT}" + url = f"{constants.SCOREBOARD_ENDPOINT.format(ymd=start_date)}" if not self.check_date_format(start_date): raise ValueError( - "Parameter start_date contains invalid value (format should be %Y-%m-%d e.g. '2021-10-05')." + "Parameter start_date contains invalid value (format should be %Y-%m-%d e.g. '2021-10-05', or 'now')." ) if end_date and not self.check_date_format(end_date): raise ValueError( - "Parameter end_date contains invalid value (format should be %Y-%m-%d e.g. '2021-10-05')." + "Parameter end_date contains invalid value (format should be %Y-%m-%d e.g. '2021-10-05', or 'now')." ) - url += f"?startDate={start_date}&endDate={end_date if end_date else start_date}" - url += f"&teamId={team_id}" if team_id else "" url = self.add_kwargs_to_url(url, kwargs) json = self.get_json(url) if json: - return json - - def season_by_date( - self, date_str, pre_season_allowance_days=30, json=True, **kwargs - ): + games = json.get("games", []) + if games and end_date: + games = [x for x in games if x["gameDate"] <= end_date] + if games and team_id: + games = [ + x + for x in games + if team_id in [x["awayTeam"]["id"], x["homeTeam"]["id"]] + ] + return games + + def season_by_date(self, date_str, **kwargs): if not self.check_date_format(date_str): raise ValueError( "Parameter date_str contains invalid value (format should be %Y-%m-%d e.g. '2021-10-05')." ) - all_seasons = self.seasons(ids=[], **kwargs) + all_seasons = self.seasons(**kwargs) date_obj = datetime.strptime(date_str, "%Y-%m-%d") given_year = date_obj.strftime("%Y") - relevant_seasons = [x for x in all_seasons if given_year in str(x["seasonId"])] + relevant_seasons = [x for x in all_seasons if given_year in str(x["id"])] in_season = next( ( x for x in relevant_seasons - if date_obj - >= ( - datetime.strptime(x["regularSeasonStartDate"], "%Y-%m-%d") - - timedelta(days=pre_season_allowance_days) - ) - and date_obj <= datetime.strptime(x["seasonEndDate"], "%Y-%m-%d") + if date_obj >= (datetime.fromisoformat(x["preseasonStartdate"])) + and date_obj <= datetime.fromisoformat(x["endDate"]) ), None, ) @@ -79,68 +85,86 @@ def season_by_date( return ( relevant_seasons[0] if ( - date_obj - - datetime.strptime(relevant_seasons[0]["seasonEndDate"], "%Y-%m-%d") - < ( - datetime.strptime( - relevant_seasons[1]["regularSeasonStartDate"], "%Y-%m-%d" - ) - - timedelta(days=pre_season_allowance_days) - ) + date_obj - datetime.fromisoformat(relevant_seasons[0]["endDate"]) + < (datetime.fromisoformat(relevant_seasons[1]["preseasonStartDate"])) - date_obj ) else relevant_seasons[1] ) - def season_by_id(self, season_id, json=True, **kwargs): - url = f"{self.api_url}{constants.SEASON_ENDPOINT.format(season_id=season_id)}" - url = self.add_kwargs_to_url(url, kwargs) - json = self.get_json(url) - if json: - return json.get("seasons", [])[0] + def season_by_id(self, season_id, **kwargs): + all_seasons = self.seasons(**kwargs) + return next( + (x for x in all_seasons if x["id"] == season_id), + None, + ) - def seasons(self, ids=[], json=True, **kwargs): - url = f"{self.api_url}{constants.SEASONS_ENDPOINT}" + def seasons(self, ids=[], **kwargs): + url = f"{constants.SEASONS_ENDPOINT}" url = self.add_kwargs_to_url(url, kwargs) json = self.get_json(url) if ids == []: - return json["seasons"] + return json["data"] if isinstance(ids, int) or isinstance(ids, str): ids = [str(ids)] ids = [str(i) for i in ids] - seasons = [s for s in json["seasons"] if s["seasonId"] in ids] + seasons = [s for s in json["data"] if s["id"] in ids] if json: return seasons - def standings(self, season=None, **kwargs): - url = f"{self.api_url}{constants.STANDINGS_ENDPOINT}" - if season: - url += f"?season={season}" + def standings(self, ymd="now", **kwargs): + if not self.check_date_format(ymd): + raise ValueError( + "Parameter ymd contains invalid value (format should be %Y-%m-%d e.g. '2021-10-05', or 'now')." + ) + url = f"{constants.STANDINGS_ENDPOINT.format(ymd=ymd)}" url = self.add_kwargs_to_url(url, kwargs) json = self.get_json(url) if json: - return json.get("records", []) + return json.get("standings", []) - def team_by_id(self, team_id, json=True, **kwargs): - url = f"{self.api_url}{constants.TEAM_ENDPOINT.format(team_id=team_id)}" - url = self.add_kwargs_to_url(url, kwargs) - json = self.get_json(url) - if json: - return json.get("teams", [])[0] - - def teams(self, ids=[], json=True, **kwargs): - if isinstance(ids, list): - ids = ",".join([str(id) for id in ids]) - elif isinstance(ids, int): - ids = str(ids) - url = f"{self.api_url}{constants.TEAMS_ENDPOINT}" - if len(ids): - url += f"?teamId={ids}" + def team_by_id(self, team_id): + return next((x for x in self.teams() if x["id"] == team_id), None) + + def teams(self, ymd="now", ids=[], **kwargs): + if not self.check_date_format(ymd): + raise ValueError( + "Parameter ymd contains invalid value (format should be %Y-%m-%d e.g. '2021-10-05', or 'now')." + ) + url = f"{constants.TEAMS_ENDPOINT.format(ymd=ymd)}" url = self.add_kwargs_to_url(url, kwargs) json = self.get_json(url) - if json: + if not json: + return [] + if ids: + return [x for x in json["teams"] if x["id"] in ids] + else: return json["teams"] + def teams_with_conf_div(self, ymd="now", ids=[]): + all_teams = self.teams(ymd=ymd, ids=ids) + standings = self.standings() + if not standings: + logger.error( + "No data returned for standings/now. Teams won't have valid division or conference data included!" + ) + standings = [] + for t in all_teams: + st = next( + (x for x in standings if x["teamAbbrev"]["default"] == t["abbrev"]), + {}, + ) + t.update( + { + "conferenceAbbrev": st.get("conferenceAbbrev", "U"), + "conferenceName": st.get("conferenceName", "Unknown"), + "divisionAbbrev": st.get("divisionAbbrev", "U"), + "divisionName": st.get("divisionName", "Unknown"), + } + ) + + return all_teams + @staticmethod def add_kwargs_to_url(url, kwargs=None): if not kwargs or not len(kwargs): @@ -152,6 +176,8 @@ def add_kwargs_to_url(url, kwargs=None): @staticmethod def check_date_format(d): + if d == "now": + return True try: datetime.strptime(d, "%Y-%m-%d") except ValueError: diff --git a/bots/nhl_game_threads/pynhlapi/constants.py b/bots/nhl_game_threads/pynhlapi/constants.py index a7054c3..e6cf4ff 100644 --- a/bots/nhl_game_threads/pynhlapi/constants.py +++ b/bots/nhl_game_threads/pynhlapi/constants.py @@ -1,10 +1,10 @@ APP_NAME = "pynhlapi" -API_URL = "https://statsapi.web.nhl.com" -SCHEDULE_ENDPOINT = "/api/v1/schedule" -TEAM_ENDPOINT = "/api/v1/teams/{team_id}" -TEAMS_ENDPOINT = "/api/v1/teams" -GAME_ENDPOINT = "/api/v1/game/{game_pk}/feed/live" -SEASON_ENDPOINT = "/api/v1/seasons/{season_id}" -SEASONS_ENDPOINT = "/api/v1/seasons" -STANDINGS_ENDPOINT = "/api/v1/standings" -GAME_CONTENT_ENDPOINT = "/api/v1/game/{game_pk}/content" +API_URL = "https://api-web.nhle.com" +TEAMS_ENDPOINT = API_URL + "/v1/schedule-calendar/{ymd}" +STANDINGS_ENDPOINT = API_URL + "/v1/standings/{ymd}" +SCOREBOARD_ENDPOINT = API_URL + "/v1/score/{ymd}" +SCHEDULE_ENDPOINT = API_URL + "/v1/schedule/{ymd}" +GAME_ENDPOINT = API_URL + "/v1/gamecenter/{game_pk}/landing" +SEASONS_ENDPOINT = "https://api.nhle.com/stats/rest/en/season?sort=%5B%7B%22property%22:%22id%22,%22direction%22:%22DESC%22%7D%5D" +GAME_BOXSCORE_ENDPOINT = API_URL + "/v1/gamecenter/{game_pk}/boxscore" +GAME_PLAYBYPLAY_ENDPOINT = API_URL + "/v1/gamecenter/{game_pk}/play-by-play" diff --git a/bots/nhl_game_threads/templates/decisions.mako b/bots/nhl_game_threads/templates/decisions.mako index abe8dcf..b1854ce 100644 --- a/bots/nhl_game_threads/templates/decisions.mako +++ b/bots/nhl_game_threads/templates/decisions.mako @@ -2,21 +2,24 @@ awayTeam = data["myTeam"] if data["homeAway"] == "away" else data["oppTeam"] homeTeam = data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] def playerLink(p): - return f"[{p['fullName']}](https://www.nhl.com/player/{p['id']})" + return f"[{p['name']}](https://www.nhl.com/player/{p['playerId']})" + threeStars = data["game"].get("summary", {}).get("threeStars") + labels = ["First", "Second", "Third"] %>\ -${'##'} Decisions -%if data["game"]["liveData"]["decisions"].get("winner", {}).get("fullName"): -* Winner: ${playerLink(data["game"]["liveData"]["decisions"]["winner"])} -%endif -%if data["game"]["liveData"]["decisions"].get("loser", {}).get("fullName"): -* Loser: ${playerLink(data["game"]["liveData"]["decisions"]["loser"])} -%endif -%if data["game"]["liveData"]["decisions"].get("firstStar", {}).get("fullName"): -* First Star: ${playerLink(data["game"]["liveData"]["decisions"]["firstStar"])} -%endif -%if data["game"]["liveData"]["decisions"].get("secondStar", {}).get("fullName"): -* Second Star: ${playerLink(data["game"]["liveData"]["decisions"]["secondStar"])} -%endif -%if data["game"]["liveData"]["decisions"].get("thirdStar", {}).get("fullName"): -* Third Star: ${playerLink(data["game"]["liveData"]["decisions"]["thirdStar"])} -%endif +% if threeStars: +${'##'} Stars of the Game +##% if data["game"]["liveData"]["decisions"].get("winner", {}).get("fullName"): +##* Winner: ${playerLink(data["game"]["liveData"]["decisions"]["winner"])} +##% endif +##% if data["game"]["liveData"]["decisions"].get("loser", {}).get("fullName"): +##* Loser: ${playerLink(data["game"]["liveData"]["decisions"]["loser"])} +##% endif +% for p in threeStars: +* ${labels[p["star"] - 1]} Star: ${playerLink(p)} (${p["teamAbbrev"]})\ +% if p.get("goals") is not None and p.get("assists") is not None: + Goals: ${p["goals"]}, Assists: ${p["assists"]} +% else: + +% endif +% endfor +% endif \ No newline at end of file diff --git a/bots/nhl_game_threads/templates/division_scoreboard.mako b/bots/nhl_game_threads/templates/division_scoreboard.mako index e1639a2..6499d48 100644 --- a/bots/nhl_game_threads/templates/division_scoreboard.mako +++ b/bots/nhl_game_threads/templates/division_scoreboard.mako @@ -1,43 +1,30 @@ <% from datetime import datetime import pytz - divGames = [ - x - for x in data["todayOtherGames"] - if ( - x["teams"]["away"]["team"]["id"] in data["otherDivisionTeamIds"] - or x["teams"]["home"]["team"]["id"] in data["otherDivisionTeamIds"] - ) and data["myTeam"]["id"] not in [ - x["teams"]["away"]["team"]["id"], - x["teams"]["home"]["team"]["id"], - ] - ] def subLink(t): - return f"[{t['teamName']}]({data['teamSubs'].get(t['abbreviation'], '')})" + return f"[{t['name']}]({data['teamSubs'].get(t['abbrev'], '')})" + ordDict = {1:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},2:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},3:{1:'1st',2:'2nd',3:'3rd',4:'OT1',5:'OT2',6:'OT3',7:'OT4',8:'OT5'}} + def format_period(game): + return ordDict[game["gameType"]].get(game.get("period"), "") %>\ -% if len(divGames): -${'##'} ${data["myTeam"]["division"]["nameShort"]} Division Scoreboard -% for game in divGames: +% if len(data["todayOtherDivisionGames"]): +${'##'} ${data["myTeam"]["divisionName"]} Division Scoreboard +% for game in data["todayOtherDivisionGames"]: <% - dt = datetime.strptime(game["gameDate"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=pytz.utc) + dt = datetime.strptime(game["startTimeUTC"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=pytz.utc) toTz = pytz.timezone(settings.get("Bot", {}).get("TEAM_TIMEZONE", "America/New_York")) formattedGameTime = dt.astimezone(toTz).strftime("%I:%M %p") + #formattedPeriod = "" if game["gameState"] == "FUT" else game["period"] if game.get("period") and game["period"] <= 3 else (game.get("periodDescriptor", {}).get("otPeriods", "") + "OT") if game.get("periodDescriptor", {}).get("periodType") == "OT" else "SO" if game.get("periodDescriptor", {}).get("periodType") == "SO" else game["period"] %>\ -% if game["status"]["statusCode"] == "9": -${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["away"]["team"]["id"]), "Unknown Team")} @ \ -${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["home"]["team"]["id"]), "Unknown Team")} - PPD -% elif game["status"]["abstractGameState"] == "Final": -${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["away"]["team"]["id"]), "Unknown Team")} (${game["teams"]["away"]["score"]}) @ \ -(${game["teams"]["home"]["score"]}) ${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["home"]["team"]["id"]), "Unknown Team")} - Final -% elif game["status"]["abstractGameState"] == "Live": -${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["away"]["team"]["id"]), "Unknown Team")} (${game["teams"]["away"]["score"]}) @ \ -(${game["teams"]["home"]["score"]}) ${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["home"]["team"]["id"]), "Unknown Team")} \ -- ${game["linescore"]["currentPeriodOrdinal"]} ${game["linescore"]["currentPeriodTimeRemaining"]} +% if data["game"].get("gameScheduleState") in ["PPD", "SUSP", "CNCL"]: +${subLink(game["awayTeam"])} @ ${subLink(game["homeTeam"])} - ${data["game"].get("gameScheduleState")} +% elif game["gameState"] in ["FINAL", "OFF", "OVER"]: +${subLink(game["awayTeam"])} @ ${subLink(game["homeTeam"])} - Final +% elif game["gameState"] in ["LIVE", "CRIT"]: +${subLink(game["awayTeam"])} @ ${subLink(game["homeTeam"])} - ${format_period(game)} ${game.get("clock", {}).get("timeRemaining", "")} % else: -${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["away"]["team"]["id"]), "Unknown Team")} @ \ -${next((subLink(t) for t in data["allTeams"] if t["id"] == game["teams"]["home"]["team"]["id"]), "Unknown Team")} \ -- ${formattedGameTime} +${subLink(game["awayTeam"])} @ ${subLink(game["homeTeam"])} - ${formattedGameTime} % endif % endfor -% endif # if len(divGames) \ No newline at end of file +% endif \ No newline at end of file diff --git a/bots/nhl_game_threads/templates/game_info.mako b/bots/nhl_game_threads/templates/game_info.mako index 212c946..75e4d63 100644 --- a/bots/nhl_game_threads/templates/game_info.mako +++ b/bots/nhl_game_threads/templates/game_info.mako @@ -1,24 +1,29 @@ -% if data["game"]["gameData"]["status"]["statusCode"] == "9": +<% + def highlight_url(clip_id): + return f"https://players.brightcove.net/6415718365001/EXtG1xJ7H_default/index.html?videoId={clip_id}" +%>\ +% if data["game"].get("gameScheduleState") == "PPD": * Game Time: POSTPONED +% elif data["game"].get("gameScheduleState") == "SUSP": +* Game Time: SUSPENDED +% elif data["game"].get("gameScheduleState") == "CNCL": +* Game Time: CANCELED % else: ## Date/Time * Game Time: ${data["gameTime"]["myTeam"].strftime(settings.get("Game Thread", {}).get("TITLE_DATE_FORMAT","%B %d, %Y @ %I:%M %p %Z"))} % endif ## Venue -* Venue: ${data["game"]["gameData"].get("venue", {}).get("name")} +* Venue: ${data["game"].get("venue", "Unknown")} <% - awayTv = [x for x in data['todayGames'][0].get('broadcasts', []) if x.get('type')=='away'] - awayRadio = [x for x in data['todayGames'][0].get('radioBroadcasts', []) if x.get('type')=='away'] - homeTv = [x for x in data['todayGames'][0].get('broadcasts', []) if x.get('type')=='home'] - homeRadio = [x for x in data['todayGames'][0].get('radioBroadcasts', []) if x.get('type')=='home'] - nationalTv = [x for x in data['todayGames'][0].get('broadcasts', []) if x.get('type')=='national'] - nationalRadio = [x for x in data['todayGames'][0].get('radioBroadcasts', []) if x.get('type')=='home'] + awayTv = [x for x in data['game'].get('tvBroadcasts', []) if x.get('market')=='A'] + homeTv = [x for x in data['game'].get('tvBroadcasts', []) if x.get('market')=='H'] + nationalTv = [x for x in data['game'].get('tvBroadcasts', []) if x.get('market')=='N'] %>\ * TV: \ <% tv = '' flag = False - for info in [(nationalTv, "National"), (awayTv, data["game"]["gameData"]["teams"]["away"]["teamName"]), (homeTv, data["game"]["gameData"]["teams"]["home"]["teamName"])]: + for info in [(nationalTv, "National"), (awayTv, data["game"]["awayTeam"]["name"]), (homeTv, data["game"]["homeTeam"]["name"])]: if len(info[0]): if flag: tv += ', ' flag = True @@ -26,41 +31,18 @@ used = [] while len(info[0]): r = info[0].pop() - if r['name'] not in used: - tv += ' {}{}'.format(r['name'],' (' + r['language'] + ')' if r.get('language', 'en')!='en' else '') - used.append(r['name']) - if len(info[0]) and info[0][0]['name'] not in used: tv += ',' + if r['network'] not in used: + tv += ' {}{}'.format(r['network'],' (' + r['countryCode'] + ')' if r.get('countryCode', 'US')!='US' else '') + used.append(r['network']) + if len(info[0]) and info[0][0]['network'] not in used: tv += ',' if tv == '': tv = 'None' %>\ ${tv} -* Radio: \ -<% - radio = '' - flag = False - if len(awayRadio): - if flag: radio += ', ' - flag = True - radio += '**{}**:'.format(data["game"]["gameData"]["teams"]["away"]["teamName"]) - used = [] - while len(awayRadio): - r = awayRadio.pop() - if r['name'] not in used: - radio += ' {}{}'.format(r['name'],' (' + r['language'] + ')' if r.get('language', 'en')!='en' else '') - used.append(r['name']) - if len(awayRadio) and awayRadio[0]['name'] not in used: radio += ',' - - if len(homeRadio): - if flag: radio += ', ' - flag = None - radio += '**{}**:'.format(data["game"]["gameData"]["teams"]["home"]["teamName"]) - used = [] - while len(homeRadio): - r = homeRadio.pop() - radio += ' {}{}'.format(r['name'],' (' + r['language'] + ')' if r.get('language', 'en')!='en' else '') - if len(homeRadio) and homeRadio[0]['name'] not in used: radio += ',' - - if radio == '': radio = 'None' -%>\ -${radio} -* [NHL GameCenter](https://www.nhl.com/gamecenter/${data["game"]["gamePk"]}) \ No newline at end of file +* [NHL GameCenter](https://www.nhl.com/gamecenter/${data["game"]["id"]}) +% if data["game_boxscore"].get("gameVideo", {}).get("threeMinRecap"): +* [Three Minute Recap](${highlight_url(data["game_boxscore"]["gameVideo"]["threeMinRecap"])}) +% endif +% if data["game_boxscore"].get("gameVideo", {}).get("condensedGame"): +* [Condensed Game](${highlight_url(data["game_boxscore"]["gameVideo"]["condensedGame"])}) +% endif diff --git a/bots/nhl_game_threads/templates/game_stats.mako b/bots/nhl_game_threads/templates/game_stats.mako index 2c01c42..3b9382b 100644 --- a/bots/nhl_game_threads/templates/game_stats.mako +++ b/bots/nhl_game_threads/templates/game_stats.mako @@ -7,65 +7,72 @@ data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] ) - awayStats = data["game"]["liveData"]["boxscore"]["teams"]["away"]["teamStats"]["teamSkaterStats"] - homeStats = data["game"]["liveData"]["boxscore"]["teams"]["home"]["teamStats"]["teamSkaterStats"] - - awaySkaterIds = data["game"]["liveData"]["boxscore"]["teams"]["away"]["skaters"] - homeSkaterIds = data["game"]["liveData"]["boxscore"]["teams"]["home"]["skaters"] - awayGoalieIds = data["game"]["liveData"]["boxscore"]["teams"]["away"]["goalies"] - homeGoalieIds = data["game"]["liveData"]["boxscore"]["teams"]["home"]["goalies"] - awayPlayers = data["game"]["liveData"]["boxscore"]["teams"]["away"]["players"] - homePlayers = data["game"]["liveData"]["boxscore"]["teams"]["home"]["players"] - awaySkaters = sorted([s for k, s in awayPlayers.items() if int(k[2:]) in awaySkaterIds and s.get("stats", {}).get("skaterStats")], key=lambda p: p["position"]["abbreviation"]) - homeSkaters = sorted([s for k, s in homePlayers.items() if int(k[2:]) in homeSkaterIds and s.get("stats", {}).get("skaterStats")], key=lambda p: p["position"]["abbreviation"]) - awayGoalies = sorted([s for k, s in awayPlayers.items() if int(k[2:]) in awayGoalieIds and s.get("stats", {}).get("goalieStats")], key=lambda g: g["stats"]["goalieStats"]["timeOnIce"], reverse=1) - homeGoalies = sorted([s for k, s in homePlayers.items() if int(k[2:]) in homeGoalieIds and s.get("stats", {}).get("goalieStats")], key=lambda g: g["stats"]["goalieStats"]["timeOnIce"], reverse=1) - awayOnIce = data["game"]["liveData"]["boxscore"]["teams"]["away"]["onIce"] - homeOnIce = data["game"]["liveData"]["boxscore"]["teams"]["home"]["onIce"] - def playerLink(p): - return f"[{p['person']['fullName']}](https://www.nhl.com/player/{p['person']['id']})" + awayStats = data["game_boxscore"].get("awayTeam") + homeStats = data["game_boxscore"].get("homeTeam") %>\ ${'##'} Game Stats -||SOG|FO%|PP|PIM|Hits|Blks|GVA| -|:--|:--|:--|:--|:--|:--|:--|:--| +||SOG|FO%|PP|PIM|Hits|Blks| +|:--|:--|:--|:--|:--|:--|:--| ## Team -|[${awayTeam["teamName"]}](${data["teamSubs"][awayTeam["abbreviation"]]})|${awayStats["shots"]}|${round(float(awayStats["faceOffWinPercentage"]))}%|\ -${int(awayStats["powerPlayGoals"])}/${int(awayStats["powerPlayOpportunities"])} (${int(float(awayStats["powerPlayPercentage"]))}%)|\ -${awayStats["pim"]}|${awayStats["hits"]}|${awayStats["blocked"]}|${awayStats["giveaways"]}| -|[${homeTeam["teamName"]}](${data["teamSubs"][homeTeam["abbreviation"]]})|${homeStats["shots"]}|${round(float(homeStats["faceOffWinPercentage"]))}%|\ -${int(homeStats["powerPlayGoals"])}/${int(homeStats["powerPlayOpportunities"])} (${int(float(homeStats["powerPlayPercentage"]))}%)|\ -${homeStats["pim"]}|${homeStats["hits"]}|${homeStats["blocked"]}|${homeStats["giveaways"]}| +|[${awayTeam["commonName"]}](${data["teamSubs"][awayTeam["abbrev"]]})|${awayStats.get("sog", "-")}|${round(float(awayStats.get("faceoffWinningPctg", 0)))}%|\ +${awayStats.get("powerPlayConversion", "-")}|\ +${awayStats.get("pim", "-")}|${awayStats.get("hits", "-")}|${awayStats.get("blocks", "-")}| +|[${homeTeam["commonName"]}](${data["teamSubs"][homeTeam["abbrev"]]})|${homeStats.get("sog", "-")}|${round(float(homeStats.get("faceoffWinningPctg", 0)))}%|\ +${homeStats.get("powerPlayConversion", "-")}|\ +${homeStats.get("pim", "-")}|${homeStats.get("hits", "-")}|${homeStats.get("blocks", "-")}| + <% - if not len(data["game"]["liveData"]["boxscore"]["teams"]["away"]["skaters"]) and not len(data["game"]["liveData"]["boxscore"]["teams"]["home"]["skaters"]): + awayF = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("awayTeam", {}).get("forwards", []) + awayL = [x for x in awayF if x["position"] == "L"] + awayC = [x for x in awayF if x["position"] == "C"] + awayR = [x for x in awayF if x["position"] == "R"] + awayD = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("awayTeam", {}).get("defense", []) + awayG = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("awayTeam", {}).get("goalies", []) + awaySkaters = awayF + awayD + awayOnIce = data["game_pbp"].get("awayTeam", {}).get("onIce", []) + awaySkatersOnIce = [x for x in awaySkaters if x["playerId"] in awayOnIce] + awaySkatersOnBench = [x for x in awaySkaters if x["playerId"] not in awayOnIce] + homeF = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("homeTeam", {}).get("forwards", []) + homeL = [x for x in homeF if x["position"] == "L"] + homeC = [x for x in homeF if x["position"] == "C"] + homeR = [x for x in homeF if x["position"] == "R"] + homeD = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("homeTeam", {}).get("defense", []) + homeG = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("homeTeam", {}).get("goalies", []) + homeSkaters = homeF + homeD + homeOnIce = data["game_pbp"].get("homeTeam", {}).get("onIce", []) + homeSkatersOnIce = [x for x in homeSkaters if x["playerId"] in homeOnIce] + homeSkatersOnBench = [x for x in homeSkaters if x["playerId"] not in homeOnIce] + def playerLink(p): + return f"[{p['name']}](https://www.nhl.com/player/{p['playerId']})" + if not (awaySkaters or awayG or homeSkaters or homeG): return -%> -% for info in [(awayTeam, awaySkaters, awayOnIce, awayGoalies), (homeTeam, homeSkaters, homeOnIce, homeGoalies)]: -% if len(info[1]): -|[${info[0]["teamName"]}](${data["teamSubs"][info[0]["abbreviation"]]}) Skaters|G|A|+/-|S|Blk|Tkwy|Gvwy|PIM|TOI| -|:--|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:| -% for p in info[1]: -|^${p['position']['abbreviation']} ${'**' if p["person"]["id"] in info[2] else ''}${playerLink(p)}${'**' if p["person"]["id"] in info[2] else ''}|\ -${p["stats"]["skaterStats"]["goals"]}|\ -${p["stats"]["skaterStats"]["assists"]}|\ -${p["stats"]["skaterStats"]["plusMinus"]}|\ -${p["stats"]["skaterStats"]["shots"]}|\ -${p["stats"]["skaterStats"]["blocked"]}|\ -${p["stats"]["skaterStats"]["takeaways"]}|\ -${p["stats"]["skaterStats"]["giveaways"]}|\ -${p["stats"]["skaterStats"]["penaltyMinutes"]}|\ -${p["stats"]["skaterStats"]["timeOnIce"]}| +%>\ +\ +% for info in [(awayTeam, awaySkatersOnIce, awaySkatersOnBench, awayG, awayOnIce), (homeTeam, homeSkatersOnIce, homeSkatersOnBench, homeG, homeOnIce)]: +% if len(info[1]) or len(info[2]): +|[${info[0]["commonName"]}](${data["teamSubs"][info[0]["abbrev"]]}) Skaters|G|A|+/-|S|Blk|PIM|FO|TOI| +|:--|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:| +% for p in info[1] + info[2]: +|^${p['position']} ${'**' if p in info[1] else ''}${playerLink(p)}${'**' if p in info[1] else ''}|\ +${p["goals"]}|\ +${p["assists"]}|\ +${p["plusMinus"]}|\ +${p["shots"]}|\ +${p["blockedShots"]}|\ +${p["pim"]}|\ +${p["faceoffs"]}|\ +${p["toi"]}| % endfor % endif % if len(info[3]): -|[${info[0]["teamName"]}](${data["teamSubs"][info[0]["abbreviation"]]}) Goalies|Saves|Shots|Save %|TOI| -|:--|:-:|:-:|:-:|:-:| +|[${info[0]["commonName"]}](${data["teamSubs"][info[0]["abbrev"]]}) Goalies|Saves/Shots|Save %|TOI| +|:--|:-:|:-:|:-:| % for g in info[3]: -|${'**' if g["person"]["id"] in info[2] else ''}${playerLink(g)}${'**' if g["person"]["id"] in info[2] else ''}|\ -${g["stats"]["goalieStats"]["saves"]}|\ -${g["stats"]["goalieStats"]["shots"]}|\ -${f'{g["stats"]["goalieStats"]["savePercentage"]:.1f}%' if g["stats"]["goalieStats"].get("savePercentage") else "-"}|\ -${g["stats"]["goalieStats"]["timeOnIce"]}| +|${'**' if g["playerId"] in info[4] else ''}${playerLink(g)}${'**' if g["playerId"] in info[4] else ''}|\ +${g.get("saveShotsAgainst", "-")}|\ +${f'{float(g["savePctg"])*100:.1f}%' if g.get("savePctg") is not None else "-"}|\ +${g["toi"]}| % endfor % endif diff --git a/bots/nhl_game_threads/templates/game_thread.mako b/bots/nhl_game_threads/templates/game_thread.mako index 38ecdc4..6559807 100644 --- a/bots/nhl_game_threads/templates/game_thread.mako +++ b/bots/nhl_game_threads/templates/game_thread.mako @@ -1,83 +1,92 @@ <% from datetime import datetime, timedelta - if data["game"]["gameData"]["status"]["abstractGameState"] == "Final": + if data["game"]["gameState"] in ["FINAL", "OFF", "OVER"] or data["game"].get("gameScheduleState") in ["PPD", "SUSP", "CNCL"]: result = ( - "tie" if data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] == data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + "postponed" if data["game"].get("gameScheduleState") == "PPD" + else "suspended" if data["game"].get("gameScheduleState") == "SUSP" + else "canceled" if data["game"].get("gameScheduleState") == "CNCL" + else "tie" if data["game"].get("awayTeam", {}).get("score") == data["game"].get("homeTeam", {}).get("score") else "win" if ( - data["homeAway"] == "home" and data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] > data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] - or data["homeAway"] == "away" and data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] > data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + data["homeAway"] == "home" and data["game"].get("homeTeam", {}).get("score") > data["game"].get("awayTeam", {}).get("score") + or data["homeAway"] == "away" and data["game"].get("awayTeam", {}).get("score") > data["game"].get("homeTeam", {}).get("score") ) else "loss" if ( - data["homeAway"] == "home" and data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] < data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] - or data["homeAway"] == "away" and data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] < data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + data["homeAway"] == "home" and data["game"].get("homeTeam", {}).get("score") < data["game"].get("awayTeam", {}).get("score") + or data["homeAway"] == "away" and data["game"].get("awayTeam", {}).get("score") < data["game"].get("homeTeam", {}).get("score") ) else "" ) - elif data["game"]["gameData"]["status"]["statusCode"] == "9": - result = "postponed" else: result = None oppHomeAway = "away" if data["homeAway"] == "home" else "home" - myLeagueRecord = data["todayGames"][0]["teams"][data["homeAway"]]['leagueRecord'] - oppLeagueRecord = data["todayGames"][0]["teams"][oppHomeAway]['leagueRecord'] - myTeamRecord = ( - f" ({myLeagueRecord['wins']}-{myLeagueRecord['losses']}{'-'+str(myLeagueRecord['ot']) if myLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][data["homeAway"]].get("leagueRecord") else "" - oppTeamRecord = ( - f" ({oppLeagueRecord['wins']}-{oppLeagueRecord['losses']}{'-'+str(oppLeagueRecord['ot']) if oppLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][oppHomeAway].get("leagueRecord") else "" + if data["standings"]: + myTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["myTeam"]["abbrev"]), {}) + myTeamRecord = f" ({myTeamStandingsData.get('wins', 0)}-{myTeamStandingsData.get('losses', 0)}{'-'+str(myTeamStandingsData['otLosses']) if myTeamStandingsData.get('otLosses', 0) > 0 else ''})" if myTeamStandingsData else "" + oppTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["oppTeam"]["abbrev"]), {}) + oppTeamRecord = f" ({oppTeamStandingsData.get('wins', 0)}-{oppTeamStandingsData.get('losses', 0)}{'-'+str(oppTeamStandingsData['otLosses']) if oppTeamStandingsData.get('otLosses', 0) > 0 else ''})" if oppTeamStandingsData else "" + else: + myTeamRecord = "" + oppTeamRecord = "" + + homeTeam = data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] + awayTeam = data["myTeam"] if data["homeAway"] == "away" else data["oppTeam"] + maxScore = max(int(data["game"].get("awayTeam", {}).get("score", 0)), int(data["game"].get("homeTeam", {}).get("score", 0))) + minScore = min(int(data["game"].get("awayTeam", {}).get("score", 0)), int(data["game"].get("homeTeam", {}).get("score", 0))) + ordDict = {1:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},2:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},3:{1:'1st',2:'2nd',3:'3rd',4:'OT1',5:'OT2',6:'OT3',7:'OT4',8:'OT5'}} + periodOrd = ordDict[data["game"]["gameType"]] %>\ ## Visiting Team -${'##'} [${data["game"]["gameData"]["teams"]["away"]["name"]}](${data["teamSubs"][data["game"]["gameData"]["teams"]["away"]["abbreviation"]]})${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ +${'##'} [${awayTeam["name"]}](${data["teamSubs"][awayTeam["abbrev"]]})${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ @ \ ## Home Team -[${data["game"]["gameData"]["teams"]["home"]["name"]}](${data["teamSubs"][data["game"]["gameData"]["teams"]["home"]["abbreviation"]]})${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} +[${homeTeam["name"]}](${data["teamSubs"][homeTeam["abbrev"]]})${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} <%include file="game_info.mako" /> -%if data["game"]["gameData"]["status"]["abstractGameState"] == "Live": +%if data["game"]["gameState"] in ["LIVE", "CRIT"]: ${'##'} Game Status - \ -% if data["game"]["liveData"]["linescore"]["hasShootout"]: -Shootout! ${data["game"]["gameData"]["teams"]["away"]["teamName"]}: ${data["game"]["liveData"]["linescore"]["shootoutInfo"]["away"]["scores"]}/${data["game"]["liveData"]["linescore"]["shootoutInfo"]["away"]["attempts"]}, ${data["game"]["gameData"]["teams"]["home"]["teamName"]}: ${data["game"]["liveData"]["linescore"]["shootoutInfo"]["home"]["scores"]}/${data["game"]["liveData"]["linescore"]["shootoutInfo"]["home"]["attempts"]} -% elif data["game"]["liveData"]["linescore"]["intermissionInfo"].get("inIntermission"): -Intermission, ${str(timedelta(seconds=int(data["game"]["liveData"]["linescore"]["intermissionInfo"]["intermissionTimeRemaining"])))[-5:]} Remaining +% if data["game_boxscore"].get("periodDescriptor", {}).get("periodType") == "SO": +<% + shootout_data = data["game_boxscore"].get("boxscore", {}).get("linescore", {}).get("shootout", {}) +%> +Shootout! ${data["game"]["awayTeam"]["name"]}: ${shootout_data.get("awayConversions", 0)}/${shootout_data.get("awayAttempts", 0)}, ${data["game"]["homeTeam"]["name"]}: ${shootout_data.get("homeConversions", 0)}/${shootout_data.get("homeAttempts", 0)} +% elif data["game"].get("clock", {}).get("inIntermission"): +Intermission % else: -${data["game"]["liveData"]["linescore"]["currentPeriodOrdinal"]}${' Period' if data["game"]["liveData"]["linescore"]["currentPeriod"] <= 3 else ''} - ${data["game"]["liveData"]["linescore"]["currentPeriodTimeRemaining"]} \ -% if data["game"]["liveData"]["linescore"]["teams"]["away"]["powerPlay"]: -- ${data["game"]["gameData"]["teams"]["away"]["teamName"]} Power Play (${data["game"]["liveData"]["linescore"]["teams"]["away"]["numSkaters"]} on ${data["game"]["liveData"]["linescore"]["teams"]["home"]["numSkaters"]}) \ -% elif data["game"]["liveData"]["linescore"]["teams"]["home"]["powerPlay"]: -- ${data["game"]["gameData"]["teams"]["home"]["teamName"]} Power Play (${data["game"]["liveData"]["linescore"]["teams"]["home"]["numSkaters"]} on ${data["game"]["liveData"]["linescore"]["teams"]["away"]["numSkaters"]}) \ -% endif -% if data["game"]["liveData"]["linescore"]["teams"]["away"]["goaliePulled"]: -- ${data["game"]["gameData"]["teams"]["away"]["teamName"]} Goalie Pulled \ -% endif -% if data["game"]["liveData"]["linescore"]["teams"]["home"]["goaliePulled"]: -- ${data["game"]["gameData"]["teams"]["home"]["teamName"]} Goalie Pulled \ -% endif +${periodOrd[data["game_boxscore"]["period"]]}${' Period' if data["game_boxscore"]["period"] <= 3 else ''} - ${data["game"]["clock"]["timeRemaining"]} \ +##% if data["game"]["liveData"]["linescore"]["teams"]["away"]["powerPlay"]: +##- ${data["game"]["gameData"]["teams"]["away"]["teamName"]} Power Play (${data["game"]["liveData"]["linescore"]["teams"]["away"]["numSkaters"]} on ${data["game"]["liveData"]["linescore"]["teams"]["home"]["numSkaters"]}) \ +##% elif data["game"]["liveData"]["linescore"]["teams"]["home"]["powerPlay"]: +##- ${data["game"]["gameData"]["teams"]["home"]["teamName"]} Power Play (${data["game"]["liveData"]["linescore"]["teams"]["home"]["numSkaters"]} on ${data["game"]["liveData"]["linescore"]["teams"]["away"]["numSkaters"]}) \ +##% endif +##% if data["game"]["liveData"]["linescore"]["teams"]["away"]["goaliePulled"]: +##- ${data["game"]["gameData"]["teams"]["away"]["teamName"]} Goalie Pulled \ +##% endif +##% if data["game"]["liveData"]["linescore"]["teams"]["home"]["goaliePulled"]: +##- ${data["game"]["gameData"]["teams"]["home"]["teamName"]} Goalie Pulled \ +##% endif % endif %elif result == "postponed": ${'##'} Game Status: Postponed %elif result: -${'##'} Final${f'/{data["game"]["liveData"]["linescore"]["currentPeriodOrdinal"]}' if data["game"]["liveData"]["linescore"]["currentPeriod"] > 3 else ""}: \ -${max(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"]))}\ --\ -${min(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"]))} \ +${'##'} Final${f'/{periodOrd[data["game_boxscore"]["period"]]}' if data["game_boxscore"]["period"] > 3 else ""}: \ +${maxScore} - ${minScore} \ % if result == "tie": TIE % elif result == "win": -${data["myTeam"]["teamName"]} +${data["myTeam"]["commonName"]} % elif result == "loss": -${data["oppTeam"]["teamName"]} +${data["oppTeam"]["commonName"]} % endif %endif -%if data["game"]["gameData"]["status"]["abstractGameState"] == "Final" and len(data["game"]["liveData"].get("decisions", {})): +%if data["game"]["gameState"] in ["FINAL", "OFF", "OVER"] and len(data["game"].get("summary", {}).get("threeStars", {})): ## Only include decisions if the game has ended <%include file="decisions.mako" /> %endif -%if data["game"]["gameData"]["status"]["abstractGameState"] in ["Live", "Final"]: +%if data["game"]["gameState"] in ["LIVE", "CRIT", "OFF", "OVER", "FINAL"]: ## Only include the line score if the game has already started <%include file="linescore.mako" /> @@ -86,16 +95,16 @@ ${data["oppTeam"]["teamName"]} <%include file="penalties.mako" /> %endif -%if data["game"]["gameData"]["status"]["abstractGameState"] == "Preview" and data["game"]["gameData"]["status"]["statusCode"] != "9": +%if data["game"]["gameState"] in ["FUT", "PRE"] and data["game"].get("gameScheduleState") not in ["PPD", "SUSP", "CNCL"]: <%include file="skaters.mako" /> %endif -%if data["game"]["gameData"]["status"]["statusCode"] != "9": +%if data["game"].get("gameScheduleState") not in ["PPD", "SUSP", "CNCL"]: <%include file="scratches.mako" /> %endif -%if data["game"]["gameData"]["status"]["abstractGameState"] in ["Live", "Final"]: +%if data["game"]["gameState"] in ["LIVE", "CRIT", "OFF", "OVER", "FINAL"]: <%include file="game_stats.mako" /> %endif diff --git a/bots/nhl_game_threads/templates/game_title.mako b/bots/nhl_game_threads/templates/game_title.mako index e8bdd76..5f2cee9 100644 --- a/bots/nhl_game_threads/templates/game_title.mako +++ b/bots/nhl_game_threads/templates/game_title.mako @@ -1,26 +1,29 @@ <% prefix = settings.get("Game Thread", {}).get("TITLE_PREFIX","Game Thread:") oppHomeAway = "away" if data["homeAway"] == "home" else "home" - myLeagueRecord = data["todayGames"][0]["teams"][data["homeAway"]]['leagueRecord'] - oppLeagueRecord = data["todayGames"][0]["teams"][oppHomeAway]['leagueRecord'] - myTeamRecord = ( - f" ({myLeagueRecord['wins']}-{myLeagueRecord['losses']}{'-'+str(myLeagueRecord['ot']) if myLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][data["homeAway"]].get("leagueRecord") else "" - oppTeamRecord = ( - f" ({oppLeagueRecord['wins']}-{oppLeagueRecord['losses']}{'-'+str(oppLeagueRecord['ot']) if oppLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][oppHomeAway].get("leagueRecord") else "" + if data["standings"]: + myTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["myTeam"]["abbrev"]), {}) + myTeamRecord = f" ({myTeamStandingsData.get('wins', 0)}-{myTeamStandingsData.get('losses', 0)}{'-'+str(myTeamStandingsData['otLosses']) if myTeamStandingsData.get('otLosses', 0) > 0 else ''})" if myTeamStandingsData else "" + oppTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["oppTeam"]["abbrev"]), {}) + oppTeamRecord = f" ({oppTeamStandingsData.get('wins', 0)}-{oppTeamStandingsData.get('losses', 0)}{'-'+str(oppTeamStandingsData['otLosses']) if oppTeamStandingsData.get('otLosses', 0) > 0 else ''})" if oppTeamStandingsData else "" + else: + myTeamRecord = "" + oppTeamRecord = "" %>\ ## Prefix ${prefix + (" " if len(prefix) and not prefix.endswith(" ") else "")}\ ## Visiting Team -${data["game"]["gameData"]["teams"]["away"]["name"]}${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ +${data["myTeam"]["name"] if data["homeAway"] == "away" else data["oppTeam"]["name"]}${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ @ \ ## Home Team -${data["game"]["gameData"]["teams"]["home"]["name"]}${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} \ +${data["myTeam"]["name"] if data["homeAway"] == "home" else data["oppTeam"]["name"]}${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} \ - \ -% if data["game"]["gameData"]["status"]["statusCode"] == "9": -## Postponed +% if data["game"].get("gameScheduleState") == "PPD": POSTPONED +% elif data["game"].get("gameScheduleState") == "SUSP": +SUSPENDED +% elif data["game"].get("gameScheduleState") == "CNCL": +CANCELED % else: ## Date/Time ${data["gameTime"]["myTeam"].strftime(settings.get("Game Thread", {}).get("TITLE_DATE_FORMAT","%B %d, %Y @ %I:%M %p %Z"))} diff --git a/bots/nhl_game_threads/templates/linescore.mako b/bots/nhl_game_threads/templates/linescore.mako index edd14a0..a48221a 100644 --- a/bots/nhl_game_threads/templates/linescore.mako +++ b/bots/nhl_game_threads/templates/linescore.mako @@ -7,31 +7,28 @@ data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] ) - if ( - data["game"]["liveData"]["linescore"]["teams"]["away"].get("goals") is not None - and data["game"]["liveData"]["linescore"]["teams"]["home"].get("goals") is not None - ): + linescore = data["game"].get("summary", {}).get("linescore", {}).get("byPeriod", []) + ordDict = {1:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},2:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},3:{1:'1st',2:'2nd',3:'3rd',4:'OT1',5:'OT2',6:'OT3',7:'OT4',8:'OT5'}} + periodOrd = ordDict[data["game"]["gameType"]] + if linescore: headerLine = "||" alignmentLine = "|:--|" - awayLine = f'|[{awayTeam["teamName"]}]({data["teamSubs"][awayTeam["abbreviation"]]})|' - homeLine = f'|[{homeTeam["teamName"]}]({data["teamSubs"][homeTeam["abbreviation"]]})|' - for period in data["game"]["liveData"]["linescore"]["periods"]: - headerLine += f'{period["ordinalNum"]}|' + awayLine = f'|[{awayTeam["commonName"]}]({data["teamSubs"][awayTeam["abbrev"]]})|' + homeLine = f'|[{homeTeam["commonName"]}]({data["teamSubs"][homeTeam["abbrev"]]})|' + for period in linescore: + headerLine += f'{periodOrd[period["period"]]}|' alignmentLine += ":--|" - awayLine += f'{period["away"]["goals"]}|' - homeLine += f'{period["home"]["goals"]}|' - if data["game"]["liveData"]["linescore"]["hasShootout"]: - headerLine += "SO|" - alignmentLine += ":--|" - awayLine += f"{data['game']['liveData']['linescore']['shootoutInfo']['away']['scores']}/{data['game']['liveData']['linescore']['shootoutInfo']['away']['attempts']}|" - homeLine += f"{data['game']['liveData']['linescore']['shootoutInfo']['home']['scores']}/{data['game']['liveData']['linescore']['shootoutInfo']['home']['attempts']}|" + awayLine += f'{period["away"]}|' + homeLine += f'{period["home"]}|' headerLine += "|TOTAL|" alignmentLine += ":--|:--|" - awayLine += f'|{data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]}|' - homeLine += f'|{data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"]}|' + awayLine += f'|{data["game"].get("summary", {}).get("linescore", {}).get("totals", {}).get("away")}|' + homeLine += f'|{data["game"].get("summary", {}).get("linescore", {}).get("totals", {}).get("away")}|' %>\ +% if linescore: ${'##'} Linescore ${headerLine} ${alignmentLine} ${awayLine} -${homeLine} \ No newline at end of file +${homeLine} +% endif \ No newline at end of file diff --git a/bots/nhl_game_threads/templates/penalties.mako b/bots/nhl_game_threads/templates/penalties.mako index 0d99718..1c9b30b 100644 --- a/bots/nhl_game_threads/templates/penalties.mako +++ b/bots/nhl_game_threads/templates/penalties.mako @@ -1,26 +1,29 @@ ## Penalties <% - if not len(data["game"]["liveData"]["plays"].get('penaltyPlays', [])): + if not data["game"].get("summary", {}).get("penalties", []): return - else: - plays = [] - for i in data["game"]["liveData"]["plays"]["penaltyPlays"]: - play = next( - (p for p in data["game"]["liveData"]["plays"]["allPlays"] if p["about"].get("eventIdx") == i and p["result"]["eventTypeId"]=="PENALTY"), - None, - ) - if play and play['result'].get('description'): - plays.append(play) + ordDict = {1:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},2:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},3:{1:'1st',2:'2nd',3:'3rd',4:'OT1',5:'OT2',6:'OT3',7:'OT4',8:'OT5'}} + periodOrd = ordDict[data["game"]["gameType"]] + sevs = {"MIN": "Minor", "MAJ": "Major", "BEN": "Bench", "GAM": "Game Misconduct"} %> -% if len(plays): ${'##'} Penalty Summary |Per./Time|Team|Type|Description| |:--|:--|:--|:--| -% for p in plays: -|${f"{p['about']['ordinalNum']}{(' ' + p['about']['periodTime']) if p['about']['periodType'] != 'SHOOTOUT' else ''}"}|\ -[${p['team']['triCode']}](${data['teamSubsById'].get(p['team']['id'], '')})|\ -${p['result']['penaltyMinutes']}:00 ${p['result']['penaltySeverity']}|\ -${p['result']['description']}| +% for per in data["game"]["summary"]["penalties"]: +% for p in per.get("penalties", []): +<% + desc = (p.get("descKey", "").title() + " - ") if p.get("descKey") else "" + if p.get("committedByPlayer"): + desc += f"Committed by {p['committedByPlayer']}. " + if p.get("drawnBy"): + desc += f"Drawn by {p['drawnBy']}. " + if p.get("servedBy"): + desc += f"Served by {p['servedBy']}." +%>\ +|${periodOrd[per.get('period')]}\ +${(' ' + p.get('timeInPeriod')) if per.get('periodDescriptor', {}).get('periodType') != 'SO' else ''}|\ +[${p['teamAbbrev']}](${data['teamSubs'].get(p['teamAbbrev'], '')})|\ +${p['duration']}:00 ${sevs.get(p['type'], "")}|\ +${desc}| % endfor - -% endif \ No newline at end of file +% endfor diff --git a/bots/nhl_game_threads/templates/post_thread.mako b/bots/nhl_game_threads/templates/post_thread.mako index ac332a9..76dd1fd 100644 --- a/bots/nhl_game_threads/templates/post_thread.mako +++ b/bots/nhl_game_threads/templates/post_thread.mako @@ -1,55 +1,115 @@ <% result = ( - "postponed" if data["game"]["gameData"]["status"]["statusCode"] == "9" - else "tie" if data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] == data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + "postponed" if data["game"].get("gameScheduleState") == "PPD" + else "suspended" if data["game"].get("gameScheduleState") == "SUSP" + else "canceled" if data["game"].get("gameScheduleState") == "CNCL" + else "tie" if data["game"].get("awayTeam", {}).get("score") == data["game"].get("homeTeam", {}).get("score") else "win" if ( - data["homeAway"] == "home" and data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] > data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] - or data["homeAway"] == "away" and data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] > data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + data["homeAway"] == "home" and data["game"].get("homeTeam", {}).get("score") > data["game"].get("awayTeam", {}).get("score") + or data["homeAway"] == "away" and data["game"].get("awayTeam", {}).get("score") > data["game"].get("homeTeam", {}).get("score") ) else "loss" if ( - data["homeAway"] == "home" and data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] < data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] - or data["homeAway"] == "away" and data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] < data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + data["homeAway"] == "home" and data["game"].get("homeTeam", {}).get("score") < data["game"].get("awayTeam", {}).get("score") + or data["homeAway"] == "away" and data["game"].get("awayTeam", {}).get("score") < data["game"].get("homeTeam", {}).get("score") ) else "" ) - maxScore = max(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"])) - minScore = min(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"])) + maxScore = max(int(data["game"].get("awayTeam", {}).get("score")), int(data["game"].get("homeTeam", {}).get("score"))) + minScore = min(int(data["game"].get("awayTeam", {}).get("score")), int(data["game"].get("homeTeam", {}).get("score"))) oppHomeAway = "away" if data["homeAway"] == "home" else "home" - myLeagueRecord = data["todayGames"][0]["teams"][data["homeAway"]]['leagueRecord'] - oppLeagueRecord = data["todayGames"][0]["teams"][oppHomeAway]['leagueRecord'] - myTeamRecord = ( - f" ({myLeagueRecord['wins']}-{myLeagueRecord['losses']}{'-'+str(myLeagueRecord['ot']) if myLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][data["homeAway"]].get("leagueRecord") else "" - oppTeamRecord = ( - f" ({oppLeagueRecord['wins']}-{oppLeagueRecord['losses']}{'-'+str(oppLeagueRecord['ot']) if oppLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][oppHomeAway].get("leagueRecord") else "" + if data["standings"]: + myTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["myTeam"]["abbrev"]), {}) + myTeamRecord = f" ({myTeamStandingsData.get('wins', 0)}-{myTeamStandingsData.get('losses', 0)}{'-'+str(myTeamStandingsData['otLosses']) if myTeamStandingsData.get('otLosses', 0) > 0 else ''})" if myTeamStandingsData else "" + oppTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["oppTeam"]["abbrev"]), {}) + oppTeamRecord = f" ({oppTeamStandingsData.get('wins', 0)}-{oppTeamStandingsData.get('losses', 0)}{'-'+str(oppTeamStandingsData['otLosses']) if oppTeamStandingsData.get('otLosses', 0) > 0 else ''})" if oppTeamStandingsData else "" + else: + myTeamRecord = "" + oppTeamRecord = "" + + homeTeam = data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] + awayTeam = data["myTeam"] if data["homeAway"] == "away" else data["oppTeam"] + maxScore = max(int(data["game"].get("awayTeam", {}).get("score")), int(data["game"].get("homeTeam", {}).get("score"))) + minScore = min(int(data["game"].get("awayTeam", {}).get("score")), int(data["game"].get("homeTeam", {}).get("score"))) + ordDict = {1:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},2:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},3:{1:'1st',2:'2nd',3:'3rd',4:'OT1',5:'OT2',6:'OT3',7:'OT4',8:'OT5'}} + periodOrd = ordDict[data["game"]["gameType"]] + def highlight_url(clip_id): + return f"https://players.brightcove.net/6415718365001/EXtG1xJ7H_default/index.html?videoId={clip_id}" %>\ ## Visiting Team -${'##'} [${data["game"]["gameData"]["teams"]["away"]["name"]}](${data["teamSubs"][data["game"]["gameData"]["teams"]["away"]["abbreviation"]]})${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ +${'##'} [${awayTeam["name"]}](${data["teamSubs"][awayTeam["abbrev"]]})${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ @ \ ## Home Team -[${data["game"]["gameData"]["teams"]["home"]["name"]}](${data["teamSubs"][data["game"]["gameData"]["teams"]["home"]["abbreviation"]]})${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} +[${homeTeam["name"]}](${data["teamSubs"][homeTeam["abbrev"]]})${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} %if result == "postponed": ${'##'} Game Status: Postponed %elif result != "": -${'##'} Final${f'/{data["game"]["liveData"]["linescore"]["currentPeriodOrdinal"]}' if data["game"]["liveData"]["linescore"]["currentPeriod"] > 3 else ""}: \ -${max(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"]))}\ --\ -${min(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"]))} \ +${'##'} Final${f'/{periodOrd[data["game_boxscore"]["period"]]}' if data["game_boxscore"]["period"] > 3 else ""}: \ +${maxScore} - ${minScore} \ % if result == "tie": TIE % elif result == "win": -${data["myTeam"]["teamName"]} +${data["myTeam"]["commonName"]} % elif result == "loss": -${data["oppTeam"]["teamName"]} +${data["oppTeam"]["commonName"]} % endif %endif -%if len(data["game"]["liveData"].get("decisions", {})): +% if data["game_boxscore"].get("gameVideo", {}).get("threeMinRecap") or data["game_boxscore"].get("gameVideo", {}).get("condensedGame") or data["game_boxscore"].get("boxscore", {}).get("gameReports"): +${'##'} Game Videos/Summaries +% if data["game_boxscore"].get("gameVideo", {}).get("threeMinRecap"): +* [Three Minute Recap Video](${highlight_url(data["game_boxscore"]["gameVideo"]["threeMinRecap"])}) +% endif +% if data["game_boxscore"].get("gameVideo", {}).get("condensedGame"): +* [Condensed Game Video](${highlight_url(data["game_boxscore"]["gameVideo"]["condensedGame"])}) +% endif +% if data["game_boxscore"].get("boxscore", {}).get("gameReports"): +% if data["game_boxscore"]["boxscore"]["gameReports"].get("gameSummary"): +* [Game Summary](${data["game_boxscore"]["boxscore"]["gameReports"]["gameSummary"]}) +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("eventSummary"): +* [Event Summary](${data["game_boxscore"]["boxscore"]["gameReports"]["eventSummary"]}) +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("playByPlay"): +* [Play by Play](${data["game_boxscore"]["boxscore"]["gameReports"]["playByPlay"]}) +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("faceoffSummary") or data["game_boxscore"]["boxscore"]["gameReports"].get("faceoffComparison"): +* Face Off \ +% if data["game_boxscore"]["boxscore"]["gameReports"].get("faceoffSummary"): +[Summary](${data["game_boxscore"]["boxscore"]["gameReports"]["faceoffSummary"]}) \ +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("faceoffComparison"): +[Comparison](${data["game_boxscore"]["boxscore"]["gameReports"]["faceoffComparison"]}) +% endif +% endif +##% if data["game_boxscore"]["boxscore"]["gameReports"].get("rosters"): +##* [Rosters](${data["game_boxscore"]["boxscore"]["gameReports"]["rosters"]}) +##% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("shotSummary"): +* [Shot Summary](${data["game_boxscore"]["boxscore"]["gameReports"]["shotSummary"]}) +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("shootoutSummary"): +* [Shootout Summary](${data["game_boxscore"]["boxscore"]["gameReports"]["shootoutSummary"]}) +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("shiftChart"): +* [Shift Chart](${data["game_boxscore"]["boxscore"]["gameReports"]["shiftChart"]}) +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("toiAway") or data["game_boxscore"]["boxscore"]["gameReports"].get("toiHome"): +* TOI Report: \ +% if data["game_boxscore"]["boxscore"]["gameReports"].get("toiAway"): +[${awayTeam["commonName"]}](${data["game_boxscore"]["boxscore"]["gameReports"]["toiAway"]}) \ +% endif +% if data["game_boxscore"]["boxscore"]["gameReports"].get("toiHome"): +[${homeTeam["commonName"]}](${data["game_boxscore"]["boxscore"]["gameReports"]["toiHome"]}) +% endif +% endif +% endif +% endif + +%if len(data["game"].get("summary", {}).get("threeStars", {})): <%include file="decisions.mako" /> -%endif +%endif %if result != "postponed": <%include file="linescore.mako" /> diff --git a/bots/nhl_game_threads/templates/post_title.mako b/bots/nhl_game_threads/templates/post_title.mako index a531c29..530a65f 100644 --- a/bots/nhl_game_threads/templates/post_title.mako +++ b/bots/nhl_game_threads/templates/post_title.mako @@ -1,25 +1,27 @@ <% prefix = settings.get("Post Game Thread", {}).get("TITLE_PREFIX","Post Game Thread:") result = ( - "postponed" if data["game"]["gameData"]["status"]["statusCode"] == "9" - else "tie" if data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] == data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + "postponed" if data["game"].get("gameScheduleState") == "PPD" + else "suspended" if data["game"].get("gameScheduleState") == "SUSP" + else "canceled" if data["game"].get("gameScheduleState") == "CNCL" + else "tie" if data["game"].get("awayTeam", {}).get("score") == data["game"].get("homeTeam", {}).get("score") else "win" if ( - data["homeAway"] == "home" and data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] > data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] - or data["homeAway"] == "away" and data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] > data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + data["homeAway"] == "home" and data["game"].get("homeTeam", {}).get("score") > data["game"].get("awayTeam", {}).get("score") + or data["homeAway"] == "away" and data["game"].get("awayTeam", {}).get("score") > data["game"].get("homeTeam", {}).get("score") ) else "loss" if ( - data["homeAway"] == "home" and data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] < data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] - or data["homeAway"] == "away" and data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"] < data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"] + data["homeAway"] == "home" and data["game"].get("homeTeam", {}).get("score") < data["game"].get("awayTeam", {}).get("score") + or data["homeAway"] == "away" and data["game"].get("awayTeam", {}).get("score") < data["game"].get("homeTeam", {}).get("score") ) else "" ) - maxScore = max(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"])) - minScore = min(int(data["game"]["liveData"]["linescore"]["teams"]["away"]["goals"]), int(data["game"]["liveData"]["linescore"]["teams"]["home"]["goals"])) + maxScore = max(int(data["game"].get("awayTeam", {}).get("score")), int(data["game"].get("homeTeam", {}).get("score"))) + minScore = min(int(data["game"].get("awayTeam", {}).get("score")), int(data["game"].get("homeTeam", {}).get("score"))) %>\ ## Prefix ${prefix + (" " if len(prefix) and not prefix.endswith(" ") else "")}\ ## My Team -The ${data["myTeam"]["teamName"]} \ +The ${data["myTeam"]["commonName"]} \ ## Result %if result == "tie": ## TIE @@ -32,20 +34,22 @@ defeated the \ fell to the \ %elif result == "postponed": will have to wait to play the \ +%elif result == "suspended": +will have to wait to finish playing the \ %else: ## EXCEPTION were supposed to play the \ %endif ## Opposing Team -${data["oppTeam"]["teamName"]} \ +${data["oppTeam"]["commonName"]} \ ## Score %if result == "tie": ## TIE with ${minScore} goals each \ %elif result in ["win", "loss"]: -% if data["game"]["liveData"]["linescore"]["currentPeriodOrdinal"] == "OT": -in overtime \ -% elif data["game"]["liveData"]["linescore"]["currentPeriodOrdinal"] == "SO": +% if data["game_pbp"].get("periodDescriptor", {}).get("periodType") == "OT": +in${' double' if data["game_pbp"].get("periodDescriptor", {}).get("otPeriods") == 2 else ' triple' if data["game_pbp"].get("periodDescriptor", {}).get("otPeriods") == 3 else ' quadruple' if data["game_pbp"].get("periodDescriptor", {}).get("otPeriods") == 4 else ' quintuple' if data["game_pbp"].get("periodDescriptor", {}).get("otPeriods") == 5 else ' sextuple' if data["game_pbp"].get("periodDescriptor", {}).get("otPeriods") == 6 else ''} overtime \ +% elif data["game_pbp"].get("periodDescriptor", {}).get("periodType") == "SO": in a shootout \ % endif ## WIN / LOSS @@ -54,9 +58,13 @@ with a final score of ${maxScore} to ${minScore} \ ## EXCEPTION %endif - \ -% if data["game"]["gameData"]["status"]["statusCode"] == "9": +% if data["game"].get("gameScheduleState") == "PPD": ## Postponed POSTPONED +% elif data["game"].get("gameScheduleState") == "SUSP": +SUSPENDED +% elif data["game"].get("gameScheduleState") == "CNCL": +CANCELED % else: ## Date/Time ${data["gameTime"]["myTeam"].strftime(settings.get("Post Game Thread", {}).get("TITLE_DATE_FORMAT","%B %d, %Y @ %I:%M %p %Z"))} diff --git a/bots/nhl_game_threads/templates/scoring_summary.mako b/bots/nhl_game_threads/templates/scoring_summary.mako index 976c058..4c38743 100644 --- a/bots/nhl_game_threads/templates/scoring_summary.mako +++ b/bots/nhl_game_threads/templates/scoring_summary.mako @@ -1,38 +1,42 @@ ## Scoring plays <% - if not len(data["game"]["liveData"]["plays"].get('scoringPlays', [])): + if not data["game"].get("summary", {}).get("scoring", []): return - else: - plays = [] - for i in data["game"]["liveData"]["plays"]["scoringPlays"]: - play = next( - (p for p in data["game"]["liveData"]["plays"]["allPlays"] if p["about"].get("eventIdx") == i and p["result"]["eventTypeId"]=="GOAL"), - None, - ) - if play and play['result'].get('description'): - plays.append(play) + + def highlight_url(clip_id): + return f"https://players.brightcove.net/6415718365001/EXtG1xJ7H_default/index.html?videoId={clip_id}" + ordDict = {1:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},2:{1:'1st',2:'2nd',3:'3rd',4:'OT',5:'SO'},3:{1:'1st',2:'2nd',3:'3rd',4:'OT1',5:'OT2',6:'OT3',7:'OT4',8:'OT5'}} + periodOrd = ordDict[data["game"]["gameType"]] %> -% if len(plays): ${'##'} Scoring Summary |Per./Time|Team|Description & Video Link|Score| |:--|:--|:--|:--| -% for p in plays: +% for per in data["game"].get("summary", {}).get("scoring", []): +% for p in per.get("goals", []): <% - milestone = next((x for x in data["content"].get("media", {}).get("milestones", {}).get("items", []) if x.get("type")=="GOAL" and x.get("highlight", {}).get("type")=="video" and str(x["period"])==str(p["about"]["period"]) and x["periodTime"]==p["about"]["periodTime"]), {}) - hdLink = next((v.get('url') for v in milestone.get('highlight', {}).get('playbacks',[]) if v.get('name')=='FLASH_1800K_896x504'),'') - #hdLink = "" + assists = [] + for a in p.get("assists"): + assists.append(f"{a['firstName']} {a['lastName']} ({a['assistsToDate']})") + if not len(assists): + assists_str = "unassisted" + else: + assists_str = f"assists: {', '.join(assists)}" + desc = "" + desc += f"{p['strength'].upper()} - " if p['strength'] != 'ev' else '' + desc += f"Empty Net - " if p.get('goalModifier', '').upper == 'EN' else '' + desc += f"{p['firstName']} {p['lastName']} ({p.get('goalsToDate', '-')}) {p.get('shotType', 'Unknown Shot Type')}, {assists_str}" + if p.get("highlightClip"): + desc = f"[{desc}]({highlight_url(p['highlightClip'])})" %>\ -|${f"{p['about']['ordinalNum']}{(' ' + p['about']['periodTime']) if p['about']['periodType'] != 'SHOOTOUT' else ''}"}|\ -[${p['team']['triCode']}](${data['teamSubsById'].get(p['team']['id'], '')})|\ -${f"{p['result']['strength']['code']} - " if p['result']['strength']['code'] != 'EVEN' else ''}\ -${f"Empty Net - " if p['result'].get('emptyNet') else ''}\ -[${p['result']['description']}](${hdLink})|\ -% if p['about']['periodType'] != "SHOOTOUT": -${str(max(p['about']['goals']['away'],p['about']['goals']['home']))+'-'+str(min(p['about']['goals']['away'],p['about']['goals']['home']))}${(' ' + data['game']['gameData']['teams']['away']['abbreviation'] if p['about']['goals']['away'] > p['about']['goals']['home'] else ' ' + data['game']['gameData']['teams']['home']['abbreviation']) if p['about']['goals']['away']!=p['about']['goals']['home'] else ''}\ +|${periodOrd[per.get('period')]}\ +${(' ' + p.get('timeInPeriod')) if per.get('periodDescriptor', {}).get('periodType') != 'SO' else ''}|\ +[${p['teamAbbrev']}](${data['teamSubs'].get(p['teamAbbrev'], '')})|\ +${desc}|\ +% if per.get('periodDescriptor', {}).get('periodType') != "SO": +${str(max(p['awayScore'],p['homeScore']))+'-'+str(min(p['awayScore'],p['homeScore']))} ${(data['game']['awayTeam']['abbrev'] if p['awayScore'] > p['homeScore'] else data['game']['homeTeam']['abbrev']) if p['awayScore'] != p['homeScore'] else ''}\ % else: SO\ % endif | % endfor - -% endif \ No newline at end of file +% endfor \ No newline at end of file diff --git a/bots/nhl_game_threads/templates/scratches.mako b/bots/nhl_game_threads/templates/scratches.mako index ae87d0d..3b43486 100644 --- a/bots/nhl_game_threads/templates/scratches.mako +++ b/bots/nhl_game_threads/templates/scratches.mako @@ -1,6 +1,17 @@ -## Skaters +## Scratches <% - if not len(data["game"]["liveData"]["boxscore"]["teams"]["away"]["scratches"]) and not len(data["game"]["liveData"]["boxscore"]["teams"]["home"]["scratches"]): + awayScratches = data["game"].get("matchup", {}).get("gameInfo", {}).get("awayTeam", {}).get("scratches", None) + if not awayScratches: + awayScratches = data["game"].get("summary", {}).get("gameInfo", {}).get("awayTeam", {}).get("scratches", None) + if awayScratches is None: + awayScratches = [] + homeScratches = data["game"].get("matchup", {}).get("gameInfo", {}).get("homeTeam", {}).get("scratches", None) + if not homeScratches: + homeScratches = data["game"].get("summary", {}).get("gameInfo", {}).get("homeTeam", {}).get("scratches", None) + if homeScratches is None: + homeScratches = [] + + if not len(awayScratches) and not len(homeScratches): return awayTeam = ( data["myTeam"] if data["homeAway"] == "away" @@ -10,18 +21,16 @@ data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] ) - awayScratchIds = data["game"]["liveData"]["boxscore"]["teams"]["away"]["scratches"] - homeScratchIds = data["game"]["liveData"]["boxscore"]["teams"]["home"]["scratches"] - awayPlayers = data["game"]["liveData"]["boxscore"]["teams"]["away"]["players"] - homePlayers = data["game"]["liveData"]["boxscore"]["teams"]["home"]["players"] - awayScratches = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in awayPlayers.items() if int(k[2:]) in awayScratchIds] - homeScratches = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in homePlayers.items() if int(k[2:]) in homeScratchIds] + #awayPlayers = data["game_boxscore"][""]["boxscore"]["teams"]["away"]["players"] + #homePlayers = data["game"]["liveData"]["boxscore"]["teams"]["home"]["players"] + #awayScratches = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in awayPlayers.items() if int(k[2:]) in awayScratchIds] + #homeScratches = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in homePlayers.items() if int(k[2:]) in homeScratchIds] def playerLink(p): - return f"[{p['name']}](https://www.nhl.com/player/{p['id']})" + return f"[{p['firstName']} {p['lastName']}](https://www.nhl.com/player/{p['id']})" %> % if len(awayScratches) or len(homeScratches): ${'##'} Scratches -|${awayTeam["teamName"]}|${homeTeam["teamName"]}| +|${awayTeam["commonName"]}|${homeTeam["commonName"]}| |:--|:--| % for i in range(0, max(len(awayScratches), len(homeScratches))): |${playerLink(awayScratches[i]) if len(awayScratches)>i else ""}|\ diff --git a/bots/nhl_game_threads/templates/skaters.mako b/bots/nhl_game_threads/templates/skaters.mako index 1f22315..850eaf4 100644 --- a/bots/nhl_game_threads/templates/skaters.mako +++ b/bots/nhl_game_threads/templates/skaters.mako @@ -1,7 +1,5 @@ ## Skaters <% - if not len(data["game"]["liveData"]["boxscore"]["teams"]["away"]["skaters"]) or not len(data["game"]["liveData"]["boxscore"]["teams"]["home"]["skaters"]): - return awayTeam = ( data["myTeam"] if data["homeAway"] == "away" else data["oppTeam"] @@ -10,45 +8,45 @@ data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] ) - awaySkaterIds = data["game"]["liveData"]["boxscore"]["teams"]["away"]["skaters"] - homeSkaterIds = data["game"]["liveData"]["boxscore"]["teams"]["home"]["skaters"] - awayGoalieIds = data["game"]["liveData"]["boxscore"]["teams"]["away"]["goalies"] - homeGoalieIds = data["game"]["liveData"]["boxscore"]["teams"]["home"]["goalies"] - awayPlayers = data["game"]["liveData"]["boxscore"]["teams"]["away"]["players"] - homePlayers = data["game"]["liveData"]["boxscore"]["teams"]["home"]["players"] - awaySkaters = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in awayPlayers.items() if int(k[2:]) in awaySkaterIds] - homeSkaters = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in homePlayers.items() if int(k[2:]) in homeSkaterIds] - awayGoalies = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in awayPlayers.items() if int(k[2:]) in awayGoalieIds] - homeGoalies = [{"id": s["person"]["id"], "name":s["person"]["fullName"], "position_abbreviation": s["position"]["abbreviation"], "position_name": s["position"]["name"], "position_type": s["position"]["type"]} for k, s in homePlayers.items() if int(k[2:]) in homeGoalieIds] - awayF = [x for x in awaySkaters if x["position_type"] == "Forward"] - awayD = [x for x in awaySkaters if x["position_type"] == "Defenseman"] - homeF = [x for x in homeSkaters if x["position_type"] == "Forward"] - homeD = [x for x in homeSkaters if x["position_type"] == "Defenseman"] - awayOnIce = data["game"]["liveData"]["boxscore"]["teams"]["away"]["onIce"] - homeOnIce = data["game"]["liveData"]["boxscore"]["teams"]["home"]["onIce"] + awayF = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("awayTeam", {}).get("forwards", []) + awayL = [x for x in awayF if x["position"] == "L"] + awayC = [x for x in awayF if x["position"] == "C"] + awayR = [x for x in awayF if x["position"] == "R"] + awayD = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("awayTeam", {}).get("defense", []) + awayG = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("awayTeam", {}).get("goalies", []) + awayOnIce = data["game_pbp"].get("awayTeam", {}).get("onIce", []) + homeF = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("homeTeam", {}).get("forwards", []) + homeL = [x for x in homeF if x["position"] == "L"] + homeC = [x for x in homeF if x["position"] == "C"] + homeR = [x for x in homeF if x["position"] == "R"] + homeD = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("homeTeam", {}).get("defense", []) + homeG = data["game_boxscore"].get("boxscore", {}).get("playerByGameStats", {}).get("homeTeam", {}).get("goalies", []) + homeOnIce = data["game_pbp"].get("homeTeam", {}).get("onIce", []) def playerLink(p): - return f"[{p['name']}](https://www.nhl.com/player/{p['id']})" + return f"[{p['name']}](https://www.nhl.com/player/{p['playerId']})" %> -% if len(awaySkaters): -${'##'} ${awayTeam["teamName"]} Players -|Forwards|Forwards|Defensemen|Goalies| -|:--|:--|:--|:--| -% for i in range(0, min(6, max(len(awayF), len(awayD), len(awayGoalies)))): -|${"**" if len(awayF)>i and awayF[i]["id"] in awayOnIce else ""}${playerLink(awayF[i]) if len(awayF)>i else ""}${"**" if len(awayF)>i and awayF[i]["id"] in awayOnIce else ""}|\ -${"**" if len(awayF)>i+6 and awayF[i+6]["id"] in awayOnIce else ""}${playerLink(awayF[i+6]) if len(awayF)>i+6 else ""}${"**" if len(awayF)>i+6 and awayF[i+6]["id"] in awayOnIce else ""}|\ -${"**" if len(awayD)>i and awayD[i]["id"] in awayOnIce else ""}${playerLink(awayD[i]) if len(awayD)>i else ""}${"**" if len(awayD)>i and awayD[i]["id"] in awayOnIce else ""}|\ -${"**" if len(awayGoalies)>i and awayGoalies[i]["id"] in awayOnIce else ""}${playerLink(awayGoalies[i]) if len(awayGoalies)>i else ""}${"**" if len(awayGoalies)>i and awayGoalies[i]["id"] in awayOnIce else ""}| +% if len(awayF) or len(awayD) or len(awayG): +${'##'} ${awayTeam["commonName"]} Players +|Left|Center|Right|Defensemen|Goalies| +|:--|:--|:--|:--|:--| +% for i in range(0, min(12, max(len(awayL), len(awayC), len(awayR), len(awayD), len(awayG)))): +|${"**" if len(awayL)>i and awayL[i]["playerId"] in awayOnIce else ""}${playerLink(awayL[i]) if len(awayL)>i else ""}${"**" if len(awayL)>i and awayL[i]["playerId"] in awayOnIce else ""}|\ +${"**" if len(awayC)>i and awayC[i]["playerId"] in awayOnIce else ""}${playerLink(awayC[i]) if len(awayC)>i else ""}${"**" if len(awayC)>i and awayC[i]["playerId"] in awayOnIce else ""}|\ +${"**" if len(awayR)>i and awayR[i]["playerId"] in awayOnIce else ""}${playerLink(awayR[i]) if len(awayR)>i else ""}${"**" if len(awayR)>i and awayR[i]["playerId"] in awayOnIce else ""}|\ +${"**" if len(awayD)>i and awayD[i]["playerId"] in awayOnIce else ""}${playerLink(awayD[i]) if len(awayD)>i else ""}${"**" if len(awayD)>i and awayD[i]["playerId"] in awayOnIce else ""}|\ +${"**" if len(awayG)>i and awayG[i]["playerId"] in awayOnIce else ""}${playerLink(awayG[i]) if len(awayG)>i else ""}${"**" if len(awayG)>i and awayG[i]["playerId"] in awayOnIce else ""}| % endfor % endif -% if len(homeSkaters): -${'##'} ${homeTeam["teamName"]} Players -|Forwards|Forwards|Defensemen|Goalies| -|:--|:--|:--|:--| -% for i in range(0, min(6, max(len(homeF), len(homeD), len(homeGoalies)))): -|${"**" if len(homeF)>i and homeF[i]["id"] in homeOnIce else ""}${playerLink(homeF[i]) if len(homeF)>i else ""}${"**" if len(homeF)>i and homeF[i]["id"] in homeOnIce else ""}|\ -${"**" if len(homeF)>i+6 and homeF[i+6]["id"] in homeOnIce else ""}${playerLink(homeF[i+6]) if len(homeF)>i+6 else ""}${"**" if len(homeF)>i+6 and homeF[i+6]["id"] in homeOnIce else ""}|\ -${"**" if len(homeD)>i and homeD[i]["id"] in homeOnIce else ""}${playerLink(homeD[i]) if len(homeD)>i else ""}${"**" if len(homeD)>i and homeD[i]["id"] in homeOnIce else ""}|\ -${"**" if len(homeGoalies)>i and homeGoalies[i]["id"] in homeOnIce else ""}${playerLink(homeGoalies[i]) if len(homeGoalies)>i else ""}${"**" if len(homeGoalies)>i and homeGoalies[i]["id"] in homeOnIce else ""}| +% if len(homeF) or len(homeD) or len(homeG): +${'##'} ${homeTeam["commonName"]} Players +|Left|Center|Right|Defensemen|Goalies| +|:--|:--|:--|:--|:--| +% for i in range(0, min(12, max(len(homeL), len(homeC), len(homeR), len(homeD), len(homeG)))): +|${"**" if len(homeL)>i and homeL[i]["playerId"] in homeOnIce else ""}${playerLink(homeL[i]) if len(homeL)>i else ""}${"**" if len(homeL)>i and homeL[i]["playerId"] in homeOnIce else ""}|\ +${"**" if len(homeC)>i and homeC[i]["playerId"] in homeOnIce else ""}${playerLink(homeC[i]) if len(homeC)>i else ""}${"**" if len(homeC)>i and homeC[i]["playerId"] in homeOnIce else ""}|\ +${"**" if len(homeR)>i and homeR[i]["playerId"] in homeOnIce else ""}${playerLink(homeR[i]) if len(homeR)>i else ""}${"**" if len(homeR)>i and homeR[i]["playerId"] in homeOnIce else ""}|\ +${"**" if len(homeD)>i and homeD[i]["playerId"] in homeOnIce else ""}${playerLink(homeD[i]) if len(homeD)>i else ""}${"**" if len(homeD)>i and homeD[i]["playerId"] in homeOnIce else ""}|\ +${"**" if len(homeG)>i and homeG[i]["playerId"] in homeOnIce else ""}${playerLink(homeG[i]) if len(homeG)>i else ""}${"**" if len(homeG)>i and homeG[i]["playerId"] in homeOnIce else ""}| % endfor % endif diff --git a/bots/nhl_game_threads/templates/standings.mako b/bots/nhl_game_threads/templates/standings.mako index 034487b..571d940 100644 --- a/bots/nhl_game_threads/templates/standings.mako +++ b/bots/nhl_game_threads/templates/standings.mako @@ -1,15 +1,13 @@ <% - if not len(data["standings"]): + if not len(data["standings"]) or data["game"].get("gameType") != 2: return - myDivStandings = next(( - x["teamRecords"] - for x in data["standings"] - if x["division"]["id"] == data["myTeam"]["division"]["id"] - ), []) + myDivStandings = [x for x in data["standings"] if x.get("divisionAbbrev") == data["myTeam"].get("divisionAbbrev", "UNK")] %>\ -${'##'} ${data["myTeam"]["division"]["nameShort"]} Standings +${'##'} ${data["myTeam"]["divisionName"]} Standings |Rank|Team|Wins|Losses|OT|Points| |:--|:--|:--|:--|:--|:--| -${"\n".join([f"|{x['divisionRank']}|\ -[{x['team']['name']}]({data['teamSubsById'][x['team']['id']]})|\ -{x['leagueRecord']['wins']}|{x['leagueRecord']['losses']}|{x['leagueRecord']['ot']}|{x['points']}|" for x in myDivStandings])} \ No newline at end of file +% for x in myDivStandings: +|${x["divisionSequence"]}|\ +[${x["teamName"]["default"]}]({data["teamSubs"][x["teamAbbrev"]]})|\ +${x["wins"]}|${x["losses"]}|${x["otLosses"]}|${x["points"]}| +% endfor \ No newline at end of file diff --git a/bots/nhl_game_threads/templates/tailgate_thread.mako b/bots/nhl_game_threads/templates/tailgate_thread.mako index 77379e1..1724bc2 100644 --- a/bots/nhl_game_threads/templates/tailgate_thread.mako +++ b/bots/nhl_game_threads/templates/tailgate_thread.mako @@ -1,20 +1,22 @@ <% prefix = settings.get("Tailgate Thread", {}).get("TITLE_PREFIX","Tailgate Thread:") oppHomeAway = "away" if data["homeAway"] == "home" else "home" - myLeagueRecord = data["todayGames"][0]["teams"][data["homeAway"]]['leagueRecord'] - oppLeagueRecord = data["todayGames"][0]["teams"][oppHomeAway]['leagueRecord'] - myTeamRecord = ( - f" ({myLeagueRecord['wins']}-{myLeagueRecord['losses']}{'-'+str(myLeagueRecord['ot']) if myLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][data["homeAway"]].get("leagueRecord") else "" - oppTeamRecord = ( - f" ({oppLeagueRecord['wins']}-{oppLeagueRecord['losses']}{'-'+str(oppLeagueRecord['ot']) if oppLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][oppHomeAway].get("leagueRecord") else "" + if data["standings"]: + myTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["myTeam"]["abbrev"]), {}) + myTeamRecord = f" ({myTeamStandingsData.get('wins', 0)}-{myTeamStandingsData.get('losses', 0)}{'-'+str(myTeamStandingsData['otLosses']) if myTeamStandingsData.get('otLosses', 0) > 0 else ''})" if myTeamStandingsData else "" + oppTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["oppTeam"]["abbrev"]), {}) + oppTeamRecord = f" ({oppTeamStandingsData.get('wins', 0)}-{oppTeamStandingsData.get('losses', 0)}{'-'+str(oppTeamStandingsData['otLosses']) if oppTeamStandingsData.get('otLosses', 0) > 0 else ''})" if oppTeamStandingsData else "" + else: + myTeamRecord = "" + oppTeamRecord = "" + homeTeam = data["myTeam"] if data["homeAway"] == "home" else data["oppTeam"] + awayTeam = data["myTeam"] if data["homeAway"] == "away" else data["oppTeam"] %>\ ## Visiting Team -${'##'} [${data["game"]["gameData"]["teams"]["away"]["name"]}](${data["teamSubs"][data["game"]["gameData"]["teams"]["away"]["abbreviation"]]})${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ +${'##'} [${awayTeam["name"]}](${data["teamSubs"][awayTeam["abbrev"]]})${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ @ \ ## Home Team -[${data["game"]["gameData"]["teams"]["home"]["name"]}](${data["teamSubs"][data["game"]["gameData"]["teams"]["home"]["abbreviation"]]})${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} +[${homeTeam["name"]}](${data["teamSubs"][homeTeam["abbrev"]]})${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} <%include file="game_info.mako" /> diff --git a/bots/nhl_game_threads/templates/tailgate_title.mako b/bots/nhl_game_threads/templates/tailgate_title.mako index 8054fd2..8c31819 100644 --- a/bots/nhl_game_threads/templates/tailgate_title.mako +++ b/bots/nhl_game_threads/templates/tailgate_title.mako @@ -1,22 +1,22 @@ <% prefix = settings.get("Tailgate Thread", {}).get("TITLE_PREFIX","Tailgate Thread:") oppHomeAway = "away" if data["homeAway"] == "home" else "home" - myLeagueRecord = data["todayGames"][0]["teams"][data["homeAway"]]['leagueRecord'] - oppLeagueRecord = data["todayGames"][0]["teams"][oppHomeAway]['leagueRecord'] - myTeamRecord = ( - f" ({myLeagueRecord['wins']}-{myLeagueRecord['losses']}{'-'+str(myLeagueRecord['ot']) if myLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][data["homeAway"]].get("leagueRecord") else "" - oppTeamRecord = ( - f" ({oppLeagueRecord['wins']}-{oppLeagueRecord['losses']}{'-'+str(oppLeagueRecord['ot']) if oppLeagueRecord.get('ot', 0) > 0 else ''})" - ) if data["todayGames"][0]["teams"][oppHomeAway].get("leagueRecord") else "" + if data["standings"]: + myTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["myTeam"]["abbrev"]), {}) + myTeamRecord = f" ({myTeamStandingsData.get('wins', 0)}-{myTeamStandingsData.get('losses', 0)}{'-'+str(myTeamStandingsData['otLosses']) if myTeamStandingsData.get('otLosses', 0) > 0 else ''})" if myTeamStandingsData else "" + oppTeamStandingsData = next((x for x in data["standings"] if x["teamAbbrev"].get("default") == data["oppTeam"]["abbrev"]), {}) + oppTeamRecord = f" ({oppTeamStandingsData.get('wins', 0)}-{oppTeamStandingsData.get('losses', 0)}{'-'+str(oppTeamStandingsData['otLosses']) if oppTeamStandingsData.get('otLosses', 0) > 0 else ''})" if oppTeamStandingsData else "" + else: + myTeamRecord = "" + oppTeamRecord = "" %>\ ## Prefix ${prefix + (" " if len(prefix) and not prefix.endswith(" ") else "")}\ ## Visiting Team -${data["game"]["gameData"]["teams"]["away"]["name"]}${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ +${data["myTeam"]["name"] if data["homeAway"] == "away" else data["oppTeam"]["name"]}${myTeamRecord if data["homeAway"] == "away" else oppTeamRecord} \ @ \ ## Home Team -${data["game"]["gameData"]["teams"]["home"]["name"]}${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} \ +${data["myTeam"]["name"] if data["homeAway"] == "home" else data["oppTeam"]["name"]}${myTeamRecord if data["homeAway"] == "home" else oppTeamRecord} \ - \ ## Date/Time ${data["gameTime"]["myTeam"].strftime(settings.get("Tailgate Thread", {}).get("TITLE_DATE_FORMAT","%B %d, %Y @ %I:%M %p %Z"))} \ No newline at end of file diff --git a/redball/version.py b/redball/version.py index cad67b3..be93219 100644 --- a/redball/version.py +++ b/redball/version.py @@ -1,3 +1,3 @@ #!/usr/bin/env python -VERSION = "2023.9.1" +VERSION = "2023.10.1"