def generate_game_preview(game: Game): """Generates and sends the game preview to social media. This function runs when the game is in Preview State and it is not yet game time. Should only run once at the morning scheduled time. Args: game: Game Object Returns: sleep_time: Seconds to sleep until next action """ logging.info("Generating Game Preview images & social media posts.") logging.info("Game Date: Local - %s, UTC - %s", game.game_time_local, game.date_time) # Load our Config # config = utils.load_config() # preview_sleep_time = config["script"]["preview_sleep_time"] # preview_sleep_mins = preview_sleep_time / 60 # Get the preferred team, other teams & homeaway from the Game object pref_team, other_team = game.get_preferred_team() # pref_team_homeaway = game.preferred_team.home_away # Get Team Hashtags pref_hashtag = utils.team_hashtag(pref_team.team_name, game.game_type) other_hashtag = utils.team_hashtag(other_team.team_name, game.game_type) # Generate the propert clock emoji for the game time clock_emoji = utils.clock_emoji(game.game_time_local) # If the game is a playoff game, our preview text changes slightly if GameType(game.game_type) == GameType.PLAYOFFS: preview_text_teams = ( f"Tune in {game.game_time_of_day} for Game #{game.game_id_playoff_game} when the " f"{pref_team.team_name} take on the {other_team.team_name} at {game.venue}." ) else: preview_text_teams = ( f"Tune in {game.game_time_of_day} when the {pref_team.team_name} " f"take on the {other_team.team_name} at {game.venue}.") # Generate clock, channel & hashtag emoji text preview preview_text_emojis = ( f"{clock_emoji} {game.game_time_local}\n" f"\U0001F4FA {pref_team.tv_channel}\n" f"\U00000023\U0000FE0F\U000020E3 {game.game_hashtag}") # Generate final preview tweet text preview_tweet_text = f"{preview_text_teams}\n\n{preview_text_emojis}" game.preview_socials.core_msg = preview_tweet_text # Generate pre-game image pregame_image = images.pregame_image(game) img_filename = os.path.join(IMAGES_PATH, "temp", f"Pregame-{game.game_id}.png") pregame_image.save(img_filename) # Send preview tweet w/ pre-game image to social media handler social_dict = socialhandler.send(msg=preview_tweet_text, media=img_filename, force_send=True) game.pregame_lasttweet = social_dict["twitter"] # Generate Season Series Data season_series = schedule.season_series(game.game_id, pref_team, other_team) season_series_string = season_series[0] if season_series_string is None: # If this is the first game of the season, we can set the 'last_season' flag to enable the # season series function to check last year's season series between the two teams. logging.info( "First game of the season - re-run the season series function with the last_season flag." ) season_series = schedule.season_series(game.game_id, pref_team, other_team, last_season=True) season_series_string = season_series[0] season_series_string = ( f"This is the first meeting of the season between the " f"{pref_team.short_name} & the {other_team.short_name}.\n\n" f"LAST SEASON STATS\n{season_series_string}") # season_series_tweet_text = ( # f"This is the first meeting of the season between the " # f"{pref_team.short_name} & the {other_team.short_name}. " # f"Last season's stats -" # f"\n\n{season_series_string}\n{points_leader_str}\n{toi_leader_str}" # f"\n\n{pref_hashtag} {other_hashtag} {game.game_hashtag}" # ) # Extract strings from returned list / tuple points_leader_str = season_series[1] toi_leader_str = season_series[2] if game.game_type == "P": # season_series_str = season_series_str.replace("season series", "regular season series") season_series_string = f"Regular Season Stats -\n\n{season_series_string}" season_series_tweet_text = ( f"{season_series_string}\n{points_leader_str}\n{toi_leader_str}" f"\n\n{pref_hashtag} {other_hashtag} {game.game_hashtag}") game.preview_socials.season_series_msg = season_series_tweet_text # logging.info(preview_tweet_text) # logging.info(season_series_tweet_text) discord_color = images.discord_color(game.preferred_team.team_name) social_dict = socialhandler.send( msg=season_series_tweet_text, reply=game.pregame_lasttweet, force_send=True, discord_title="PREVIEW: Season Series", discord_color=discord_color, ) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.core_sent = True game.preview_socials.season_series_sent = True
def __init__( self, game_id, game_type, date_time, game_state, game_state_code, venue, home: Team, away: Team, preferred, live_feed, season, ): self.game_id = game_id self.game_type = game_type self.date_time = date_time self.date_time_dt = datetime.strptime(self.date_time, "%Y-%m-%dT%H:%M:%SZ") self.game_state = game_state self.game_state_code = game_state_code self.venue = venue self.live_feed_endpoint = live_feed self.home_team = home self.away_team = away self.season = season # Not passed in at object creation time if preferred == "home": self.preferred_team = home self.other_team = away else: self.preferred_team = away self.other_team = home self.tz_id = dateutil.tz.gettz(self.preferred_team.tz_id) self.tz_offset = self.tz_id.utcoffset(datetime.now(self.tz_id)) self.past_start_time = False self.last_event_idx = 0 self.power_play_strength = "Even" self.penalty_killed_flag = False self.penalty_situation = PenaltySituation() self.req_session = None self.assists_check = 0 # Attributes holding other models / objects self.shootout = Shootout() self.period = Period() self.events = [] self.pref_goals = [] self.other_goals = [] self.all_goals = [] self.live_loop_counter = 0 # Initialize Pregame Tweets dictionary self.pregame_lasttweet = None self.pregametweets = { "core": False, "lines": False, "officials": False, "goalies_pref": False, "goalies_other": False, } # Initialize Final Tweets dictionary self.finaltweets = { "finalscore": False, "stars": False, "opposition": False, "advstats": False, "shotmap": False, } self.last_goalie_pull_text = None self.preview_socials = StartOfGameSocial() self.final_socials = EndOfGameSocial() self.nst_charts = NSTChartSocial() self.finaltweets_retry = 0 # Parse Game ID to get attributes game_id_string = str(self.game_id) self.game_id_season = game_id_string[0:4] self.game_id_gametype_id = game_id_string[4:6] self.game_id_gametype_shortid = game_id_string[5:6] self.game_id_shortid = game_id_string[6:] self.game_id_html = game_id_string[4:] if self.game_id_gametype_id == "01": self.game_id_gametype = "Preseason" elif self.game_id_gametype_id == "02": self.game_id_gametype = "Regular" elif self.game_id_gametype_id == "03": self.game_id_gametype = "Playoff" self.game_id_playoff_round = self.game_id_shortid[1] self.game_id_playoff_matchup = self.game_id_shortid[2] self.game_id_playoff_game = self.game_id_shortid[3] elif self.game_id_gametype_id == "04": self.game_id_gametype = "All-Star" else: self.game_id_gametype = "Unknown" # Set the hashtags in the Hashtag class Hashtag.game_hashtag = f"#{self.away_team.tri_code}vs{self.home_team.tri_code}" Hashtag.pref_hashtag = utils.team_hashtag( self.preferred_team.team_name, self.game_type) Hashtag.other_hashtag = utils.team_hashtag(self.other_team.team_name, self.game_type) Hashtag.home_hashtag = utils.team_hashtag(self.home_team.team_name, self.game_type) Hashtag.away_hashtag = utils.team_hashtag(self.away_team.team_name, self.game_type) if self.other_team.team_name == "Washington Capitals": Hashtag.game_hashtag = Hashtag.game_hashtag.lower() Hashtag.pref_hashtag = Hashtag.pref_hashtag.lower() Hashtag.other_hashtag = Hashtag.other_hashtag.lower() Hashtag.home_hashtag = Hashtag.home_hashtag.lower() Hashtag.away_hashtag = Hashtag.away_hashtag.lower()
def game_preview_others(game: Game): """Other game preview information (excluding our core game preview). This includes things like goalies, lines, referees, etc. This function runs when the game is in Preview State and it is not yet game time. Runs every xxx minutes (configured in config.yaml file). Args: game: Game Object Returns: sleep_time: Seconds to sleep until next action """ # All of the below functions containg information from non-NHL API sites # Each one is wrapped in a try / except just in case. # Load our Config config = utils.load_config() preview_sleep_time = config["script"]["preview_sleep_time"] preview_sleep_mins = preview_sleep_time / 60 # Get the preferred team, other teams & homeaway from the Game object pref_team, other_team = game.get_preferred_team() pref_team_homeaway = game.preferred_team.home_away # Get Team Hashtags pref_hashtag = utils.team_hashtag(pref_team.team_name, game.game_type) other_hashtag = utils.team_hashtag(other_team.team_name, game.game_type) # Process the pre-game information for the starting goalies if not game.preview_socials.goalies_pref_sent or not game.preview_socials.goalies_other_sent: logging.info( "One of the two goalies is not yet confirmed - getting their info now." ) # goalies_confirmed_values = ("Confirmed", "Likely", "Unconfirmed") goalies_confirmed_values = ("Confirmed", "Likely") try: df_date = game.custom_game_date("%m-%d-%Y") goalies_df = thirdparty.dailyfaceoff_goalies( pref_team, other_team, pref_team_homeaway, df_date) logging.info(goalies_df) goalie_confirm_pref = bool( goalies_df.get("pref").get("confirm") in goalies_confirmed_values) goalie_confirm_other = bool( goalies_df.get("other").get("confirm") in goalies_confirmed_values) logging.info("Goalie Confirmed PREF : %s", goalie_confirm_pref) logging.info("Goalie Confirmed OTHER : %s", goalie_confirm_other) if goalie_confirm_pref and not game.preview_socials.goalies_pref_sent: try: goalie_pref = goalies_df.get("pref") goalie_pref_name = goalie_pref.get("name") goalie_pref_confirm = goalie_pref.get("confirm") goalie_pref_season = goalie_pref.get("season") if goalie_pref_season == "-- W-L | GAA | SV% | SO": goalie_pref_season = "None (Season Debut)" goalie_hr_pref = thirdparty.hockeyref_goalie_against_team( goalie_pref_name, game.other_team.team_name) logging.info("Hockey Reference Goalie PREF : %s", goalie_hr_pref) pref_goalie_tweet_text = ( f"{goalie_pref_confirm} goalie for the {pref_team.short_name} -\n" f"(via @DailyFaceoff)\n\n{goalie_pref_name}\n" f"Season Stats: {goalie_pref_season}\n" f"Career (vs. {other_team.short_name}): {goalie_hr_pref}\n\n" f"{pref_hashtag} {game.game_hashtag}") discord_color = images.discord_color( game.preferred_team.team_name) social_dict = socialhandler.send( msg=pref_goalie_tweet_text, reply=game.pregame_lasttweet, force_send=True, discord_title="PREVIEW: Goalie Start", discord_color=discord_color, ) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.goalies_pref_sent = True except Exception as e: logging.error( "Exception getting PREFERRED Hockey Reference splits - try again next loop." ) logging.error(e) else: logging.info( "Preferred goalie not yet confirmed - try again next loop." ) if goalie_confirm_other and not game.preview_socials.goalies_other_sent: try: goalie_other = goalies_df.get("other") goalie_other_name = goalie_other.get("name") goalie_other_confirm = goalie_other.get("confirm") goalie_other_season = goalie_other.get("season") if goalie_other_season == "-- W-L | GAA | SV% | SO": goalie_other_season = "None (Season Debut)" goalie_hr_other = thirdparty.hockeyref_goalie_against_team( goalie_other_name, game.preferred_team.team_name) logging.info("Hockey Reference Goalie OTHER : %s", goalie_hr_other) other_goalie_tweet_text = ( f"{goalie_other_confirm} goalie for the {other_team.short_name} -\n" f"(via @DailyFaceoff)\n\n{goalie_other_name}\n" f"Season Stats: {goalie_other_season}\n" f"Career (vs. {pref_team.short_name}): {goalie_hr_other}\n\n" f"{other_hashtag} {game.game_hashtag}") discord_color = images.discord_color( game.preferred_team.team_name) social_dict = socialhandler.send( msg=other_goalie_tweet_text, reply=game.pregame_lasttweet, force_send=True, discord_title="PREVIEW: Goalie Start", discord_color=discord_color, ) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.goalies_other_sent = True except Exception as e: logging.error( "Exception getting OTHER Hockey Reference splits - try again next loop." ) logging.error(e) else: logging.info( "Other goalie not yet confirmed - try again next loop.") except Exception as e: logging.error( "Exception getting Daily Faceoff goalies - try again next loop." ) logging.error(e) # Process the pre-game information for the game officials if not game.preview_socials.officials_sent: try: officials = thirdparty.scouting_the_refs(game, pref_team) logging.info(officials) officials_confirmed = officials.get("confirmed") if officials_confirmed: officials_tweet_text = f"The officials (via @ScoutingTheRefs) for {game.game_hashtag} are -\n" for key, attrs in officials.items(): if key == "confirmed": continue officials_tweet_text = f"{officials_tweet_text}\n\n{key.title()}:" for official in attrs: official_name = official.get("name") official_season = official.get("seasongames") official_career = official.get("careergames") official_games = official.get("totalgames", 0) official_penalty_game = official.get("penaltygame") if official_penalty_game: official_detail = ( f"{official_name} (Games: {official_games} | P/GM: {official_penalty_game})" ) # official_detail = f"{official_name} (Gms: {official_season} / {official_career} | P/GM: {official_penalty_game})" else: official_detail = f"{official_name} (Games: {official_games})" # official_detail = f"{official_name} (Games: {official_season} / {official_career})" officials_tweet_text = f"{officials_tweet_text}\n- {official_detail}" social_dict = socialhandler.send(msg=officials_tweet_text, reply=game.pregame_lasttweet, force_send=True) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.officials_sent = True else: logging.info( "Officials not yet confirmed - try again next loop.") except Exception as e: logging.error( "Exception getting Scouting the Refs information - try again next loop." ) logging.error(e) # Process the pre-game information for the preferred team lines if not game.preview_socials.pref_lines_sent or game.preview_socials.check_for_changed_lines( "preferred"): try: pref_lines = thirdparty.dailyfaceoff_lines(game, pref_team) if not pref_lines.get("confirmed"): raise AttributeError( "Preferred team lines are not yet confirmed yet - try again next loop." ) fwd_string = pref_lines.get("fwd_string") def_string = pref_lines.get("def_string") lines_tweet_text = (f"Lines for the {pref_hashtag} -\n" f"(via @DailyFaceoff)\n\n" f"Forwards:\n{fwd_string}\n\n" f"Defense:\n{def_string}") # If we have not sent the lines out at all, force send them if not game.preview_socials.pref_lines_sent: social_dict = socialhandler.send(msg=lines_tweet_text, reply=game.pregame_lasttweet, force_send=True) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.pref_lines_msg = lines_tweet_text game.preview_socials.pref_lines_sent = True else: lines_changed, lines_tweet_text = game.preview_socials.did_lines_change( "preferred", lines_tweet_text) if lines_changed: social_dict = socialhandler.send( msg=lines_tweet_text, reply=game.pregame_lasttweet, force_send=True) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.pref_lines_msg = lines_tweet_text game.preview_socials.pref_lines_resent = True else: logging.info( "The preferred team lines have not changed - check again in an hour." ) except AttributeError as e: logging.info(e) except Exception as e: logging.error( "Exception getting Daily Faceoff lines information - try again next loop." ) logging.error(e) # Process the pre-game information for the preferred team lines if not game.preview_socials.other_lines_sent or game.preview_socials.check_for_changed_lines( "other"): try: other_lines = thirdparty.dailyfaceoff_lines(game, other_team) if not other_lines.get("confirmed"): raise AttributeError( "Other team lines are not yet confirmed yet - try again next loop." ) fwd_string = other_lines.get("fwd_string") def_string = other_lines.get("def_string") lines_tweet_text = (f"Lines for the {other_hashtag} -\n" f"(via @DailyFaceoff)\n\n" f"Forwards:\n{fwd_string}\n\n" f"Defense:\n{def_string}") # If we have not sent the lines out at all, force send them if not game.preview_socials.other_lines_sent: social_dict = socialhandler.send(msg=lines_tweet_text, reply=game.pregame_lasttweet, force_send=True) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.other_lines_msg = lines_tweet_text game.preview_socials.other_lines_sent = True else: lines_changed, lines_tweet_text = game.preview_socials.did_lines_change( "other", lines_tweet_text) if lines_changed: social_dict = socialhandler.send( msg=lines_tweet_text, reply=game.pregame_lasttweet, force_send=True) game.pregame_lasttweet = social_dict["twitter"] game.preview_socials.other_lines_msg = lines_tweet_text game.preview_socials.other_lines_resent = True else: logging.info( "The preferred team lines have not changed - check again in an hour." ) except AttributeError as e: logging.info(e) except Exception as e: logging.error( "Exception getting Daily Faceoff lines information - try again next loop." ) logging.error(e) # Check if all pre-game tweets are sent # And return time to sleep all_pregametweets = all(value is True for value in game.pregametweets.values()) if not all_pregametweets and game.game_time_countdown > preview_sleep_time: logging.info( "Game State is Preview & all pre-game tweets are not sent. " "Sleep for 30 minutes & check again.") return preview_sleep_time, False elif not all_pregametweets and game.game_time_countdown < preview_sleep_time: logging.warning( "Game State is Preview & all pre-game tweets are not sent. " "Less than %s minutes until game time so we skip these today." "If needed, we try to get lines at the end of the game for advanced stats.", preview_sleep_mins, ) return game.game_time_countdown, True else: logging.info( "Game State is Preview & all tweets are sent. Sleep for %s seconds until game time.", game.game_time_countdown, ) # We need to subtract 5-minutes from this return game.game_time_countdown, True
def run(): """ The main script runner - everything starts here! """ config = utils.load_config() args = arguments.get_arguments() # Setup the logging for this script run (console, file, etc) utils.setup_logging() # Get the team name the bot is running as team_name = args.team if args.team else config["default"]["team_name"] # ------------------------------------------------------------------------------ # PRE-SCRIPT STARTS PROCESSING BELOW # ------------------------------------------------------------------------------ # Log script start lines logging.info("#" * 80) logging.info("New instance of the Hockey Twitter Bot (V%s) started.", VERSION) if args.docker: logging.info( "Running in a Docker container - environment variables parsed.") logging.info("TIME: %s", datetime.now()) logging.info("ARGS - notweets: %s, console: %s, teamoverride: %s", args.notweets, args.console, args.team) logging.info( "ARGS - debug: %s, debugsocial: %s, overridelines: %s", args.debug, args.debugsocial, args.overridelines, ) logging.info("ARGS - date: %s, split: %s, localdata: %s", args.date, args.split, args.localdata) logging.info( "SOCIAL - twitter: %s, discord: %s, slack: %s", config["socials"]["twitter"], config["socials"]["discord"], config["socials"]["slack"], ) logging.info("%s\n", "#" * 80) # Check if there is a game scheduled for today - # If there is no game, exit the script. date = utils.date_parser(args.date) if args.date else datetime.now() team_id = schedule.get_team_id(team_name) game_today, game_info = schedule.is_game_today(team_id, date) if not game_today: game_yesterday, prev_game = schedule.was_game_yesterday(team_id, date) if game_yesterday: logging.info( "There was a game yesterday - send recap, condensed game " "and generate new season overview stats chart, tweet it & exit." ) # Get Team Information home_team = prev_game["teams"]["home"] home_team_name = home_team["team"]["name"] away_team = prev_game["teams"]["away"] away_team_name = away_team["team"]["name"] pref_team = home_team if home_team["team"][ "name"] == team_name else away_team other_team = away_team if home_team["team"][ "name"] == team_name else home_team pref_team_name = pref_team["team"]["name"] pref_score = pref_team["score"] pref_hashtag = utils.team_hashtag(pref_team_name) other_team_name = other_team["team"]["name"] other_score = other_team["score"] # Get the Recap & Condensed Game game_id = prev_game["gamePk"] content_feed = contentfeed.get_content_feed(game_id) # Send Recap Tweet try: recap, recap_video_url = contentfeed.get_game_recap( content_feed) recap_description = recap["items"][0]["description"] recap_msg = f"📺 {recap_description}.\n\n{recap_video_url}" socialhandler.send(recap_msg) except Exception as e: logging.error("Error getting Game Recap. %s", e) # Send Condensed Game / Extended Highlights Tweet try: condensed_game, condensed_video_url = contentfeed.get_condensed_game( content_feed) condensed_blurb = condensed_game["items"][0]["blurb"] condensed_msg = f"📺 {condensed_blurb}.\n\n{condensed_video_url}" socialhandler.send(condensed_msg) except Exception as e: logging.error( "Error getting Condensed Game from NHL - trying YouTube. %s", e) try: condensed_game = youtube.youtube_condensed( away_team_name, home_team_name) condensed_blurb = condensed_game["title"] condensed_video_url = condensed_game["yt_link"] condensed_msg = f"📺 {condensed_blurb}.\n\n{condensed_video_url}" socialhandler.send(condensed_msg) except Exception as e: logging.error( "Error getting Condensed Game from NHL & YouTube - skip this today. %s", e) # Generate the Season Overview charts game_result_str = "defeat" if pref_score > other_score else "lose to" team_season_msg = ( f"Updated season overview & last 10 game stats after the {pref_team_name} " f"{game_result_str} the {other_team_name} by a score of {pref_score} to {other_score}." f"\n\n{pref_hashtag}") team_season_fig = nst.generate_team_season_charts(team_name, "sva") team_season_fig_last10 = nst.generate_team_season_charts( team_name, "sva", lastgames=10) team_season_fig_all = nst.generate_team_season_charts( team_name, "all") team_season_fig_last10_all = nst.generate_team_season_charts( team_name, "all", lastgames=10) team_season_charts = [ team_season_fig, team_season_fig_last10, team_season_fig_all, team_season_fig_last10_all, ] socialhandler.send(team_season_msg, media=team_season_charts) else: logging.info("There was no game yesterday - exiting!") sys.exit() # For debugging purposes, print all game_info logging.debug("%s", game_info) # Create the Home & Away Team objects away_team = Team.from_json(game_info, "away") home_team = Team.from_json(game_info, "home") # If lines are being overriden by a local lineup file, # set the overrlide lines property to True if args.overridelines: home_team.overridelines = True away_team.overridelines = True # The preferred team is the team the bot is running as # This allows us to track if the preferred team is home / away home_team.preferred = bool(home_team.team_name == team_name) away_team.preferred = bool(away_team.team_name == team_name) # Create the Game Object! game = Game.from_json_and_teams(game_info, home_team, away_team) GlobalGame.game = game # Override Game State for localdata testing game.game_state = "Live" if args.localdata else game.game_state # Update the Team Objects with the gameday rosters roster.gameday_roster_update(game) # print(vars(game)) # print(vars(away_team)) # print(vars(home_team)) # If the codedGameState is set to 9 originally, game is postponed (exit immediately) if game.game_state_code == GameStateCode.POSTPONED.value: logging.warning( "This game is marked as postponed during our first run - exit silently." ) end_game_loop(game) # Return the game object to use in the game loop function return game