Beispiel #1
0
def test_valid_date():
    dt = datetime(2019, 10, 4, 0, 0)
    args = arguments.parse_arguments(["--date", "2019-10-04"])
    date = utils.date_parser(args.date)

    assert args.date
    assert date == dt
def test_schedule_one_game():
    """Performs a test to verify a schedule with 1 game is parsed correctly."""
    config = utils.load_config()
    date = utils.date_parser("2019-10-04")
    resp_file = os.path.join(TESTS_RESOURCES_PATH, "schedule_one_game.json")
    with open(resp_file, encoding="utf-8") as json_file:
        json_response = json.load(json_file)

    url = "https://statsapi.web.nhl.com/api/v1/schedule"
    responses.add(
        responses.GET,
        url,
        json=json_response,
        match_querystring=False,
        content_type="application/json",
    )

    game_today, game_info = schedule.is_game_today(1, date)
    assert game_today
    assert game_info == json_response["dates"][0]["games"][0]
Beispiel #3
0
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
Beispiel #4
0
def test_invalid_date():
    args = arguments.parse_arguments(["--date", "2019-42-69"])
    with pytest.raises(ValueError):
        assert utils.date_parser(args.date)