def main(): cst = tz.gettz('America/Chicago') today = datetime.datetime.now(cst) daySox = mlbgame.day(today.year, today.month, today.day, home='White Sox', away='White Sox') dayCubs = mlbgame.day(today.year, today.month, today.day, home='Cubs', away='Cubs') soxWin = 0 cubsLose = 0 if daySox and dayCubs: soxWin = 1 cubsLose = 1 for game in daySox: if game.game_status != 'FINAL' or game.w_team != 'White Sox': soxWin = 0 for game in dayCubs: if game.game_status != 'FINAL' or game.w_team == 'Cubs': cubsLose = 0 if soxWin == 1 and cubsLose == 1: tweet = "Today was a good day, the Sox won and the Cubs lost" twApi.update_status(tweet)
def before_game() : if(debug) : print("Before the game") #reset the total score. inning = 1 for inning_score in OVERALL_GAME_SCORE_AWAY : OVERALL_GAME_SCORE_AWAY[inning] = ' ' inning += 1 inning = 1 for inning_score in OVERALL_GAME_SCORE_HOME : OVERALL_GAME_SCORE_HOME[inning] = ' ' inning += 1 game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) already_displayed = False #so we dont have to keep refreshing the matrix while(game_info[0].game_status == "PRE_GAME") : #display pregame message on LED board if(not already_displayed) : init_pre_game_board(game_info[0].game_start_time) #turn on board to display start time already_displayed = True if(debug) : print("1st time if(debug) : printing") if(debug) : print("GAME STARTS AT: " + game_info[0].game_start_time) game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) time.sleep(30) #Game is either starting/in_progress, init the board with team names, inning numbers, and "R H E" init_board(game_info[0].home_team, game_info[0].away_team)
def getSchedule(year, month, day, cursor): addDate = "INSERT INTO dates (date) VALUES(%s)" dateData = (date(year, month, day), ) cursor.execute(addDate, dateData) gameID = cursor.lastrowid games = mlbgame.day(year, month, day) for game in games: awayTeam = game.away_team homeTeam = game.home_team # select fangraphs abbrev awayTeamQ = "SELECT FANGRAPHSABBR FROM teammap WHERE MLBAPI = %s" awayTeamD = (awayTeam, ) cursor.execute(awayTeamQ, awayTeamD) awayTeamAbbr = "" for team in cursor: awayTeamAbbr = team[0] homeTeamQ = "SELECT FANGRAPHSABBR FROM teammap WHERE MLBAPI = %s" homeTeamD = (homeTeam, ) cursor.execute(homeTeamQ, homeTeamD) homeTeamAbbr = "" for team in cursor: homeTeamAbbr = team[0] # insert into games addGame = "INSERT INTO games (home, away, date) VALUES (%s, %s, %s)" gameData = (homeTeamAbbr, awayTeamAbbr, gameID) cursor.execute(addGame, gameData) print "Loaded Games for %s/%s/%s" % (month, day, year)
def get_all_game_scores(): games = mlbgame.day(year, month, day) games_list = [] for game in games: games_list.append(str(game)) return (" ".join(games_list))
def crawl_xmls(self, browser): xmls_to_fetch = [ "boxscore.xml", "rawboxscore.xml", "game_events.xml", "linescore.xml", "players.xml", "inning/inning_all.xml", "game.xml" ] event_dates = mlbgame.important_dates(year=self.year) last_date = event_dates.last_date_seas first_date = event_dates.first_date_seas if self.start_date is None else self.start_date dates = date_range(first_date, last_date) for date in dates: game_scoreboards = mlbgame.day(date.year, date.month, date.day) game_scoreboards = [[match] for match in game_scoreboards] games = mlbgame.combine_games(game_scoreboards) year = date.year month = "{0:02d}".format(date.month) day = "{0:02d}".format(date.day) for game in games: gameid = game.game_id if not os.path.exists("xml/" + gameid): os.makedirs("xml/" + gameid) dir_path = "http://gd2.mlb.com/components/game/mlb/year_%s/month_%s/day_%s/gid_%s/" % \ (year, month, day, gameid) for xml in xmls_to_fetch: url_fetch = dir_path + xml path_write = "xml/" + gameid + "/" + xml self.fetch_xml(url_fetch, path_write)
def get_todays_game(team_name): team = teams_dictionary[team_name] game = mlbgame.day(year, month, day, home=team, away=team) if game: return (game[0]) else: return None
def refresh_games(self): debug.log("Updating games for {}/{}/{}".format(self.month, self.day, self.year)) urllib.urlcleanup() attempts_remaining = 5 while attempts_remaining > 0: try: current_day = self.day self.set_current_date() all_games = mlbgame.day(self.year, self.month, self.day) if self.config.rotation_only_preferred: self.games = self.__filter_list_of_games(all_games, self.config.preferred_teams) else: self.games = all_games if current_day != self.day: self.current_game_index = self.game_index_for_preferred_team() self.games_refresh_time = time.time() break except URLError, e: debug.error("URLError: {}".format(e.reason)) attempts_remaining -= 1 time.sleep(NETWORK_RETRY_SLEEP_TIME) except ValueError: debug.error("ValueError: Failed to refresh list of games") attempts_remaining -= 1 time.sleep(NETWORK_RETRY_SLEEP_TIME)
def games_on_date(month, day, year): specified_date_games = f'MLB Games on ({month}/{day}/{year}):\n' games = mlbgame.day(year, month, day) # No games for specified date if not games: specified_date_games += f'No Games on {month}/{day}/{year}. How unfortunate...' return specified_date_games for game in games: game_status = game.game_status away_team = game.away_team home_team = game.home_team start_time = game.game_start_time # Game has not started if game_status == 'PRE_GAME': specified_date_games += f'{away_team} at {home_team} - {start_time}\n' # Game has ended elif game_status == 'FINAL': specified_date_games += f'{str(game)} - {game_status}\n' # elif # TODO: Game has been delayed or postponed # Game is in progress else: pass return specified_date_games
def refresh_games(self): debug.log("Updating games for {}/{}/{}".format(self.month, self.day, self.year)) urllib.urlcleanup() attempts_remaining = 5 while attempts_remaining > 0: try: current_day = self.day self.set_current_date() all_games = mlbgame.day(self.year, self.month, self.day) if self.config.rotation_only_preferred: self.games = self.__filter_list_of_games( all_games, self.config.preferred_teams) else: self.games = all_games if current_day != self.day: self.current_game_index = self.game_index_for_preferred_team( ) self.games_refresh_time = time.time() break except URLError, e: debug.error("URLError: {}".format(e.reason)) attempts_remaining -= 1 time.sleep(NETWORK_RETRY_SLEEP_TIME) except ValueError: debug.error("ValueError: Failed to refresh list of games") attempts_remaining -= 1 time.sleep(NETWORK_RETRY_SLEEP_TIME)
def real_time_game(team_query): team_plural = get_team_plural(team_query) #print(team_plural) # debug now = datetime.datetime.now() year = now.year month = now.month day = now.day try: game_id = mlb.day(year, month, day, home=team_plural, away=team_plural)[0].game_id except: game_is_null_msg() return #game_id = "2019_05_13_oakmlb_seamlb_1" # For debugging # Get team abbreviations correctly formatted game_id_split = game_id.split("_") away_abbreviation = game_id_split[3][0:3].upper() away_score_str = "| " + away_abbreviation + " |" home_abbreviation = game_id_split[4][0:3].upper() home_score_str = "| " + home_abbreviation + " |" inningIndex = 0 prev_box_score_str = None is_top = True last_event = "NONE" # Continuously loop until game is over, user exits, or error while True: try: # API can be buggy innings_list = mlb.box_score(game_id).__dict__[ "innings"] # Get list of innings. Each inning is a dict e.g. `{'inning': 1, 'home': 1, 'away': 0}` except Exception as e: print(e) game_is_null_msg() return cur_box_score_str = get_box_score_str(innings_list, away_score_str, home_score_str) if cur_box_score_str != prev_box_score_str: print(cur_box_score_str) prev_box_score_str = cur_box_score_str game_events = mlb.game_events( game_id) # List of lists, each indice is a full inning's events cur_inning_num = len(game_events) # Get current inning num for inning_events in game_events: # Loop through all innings because API gives them out of order if inning_events.num == cur_inning_num: # If current inning inning if len(inning_events.bottom) > 0: # if bottom inning # for ev in inning_events.bottom: # print(ev.des) cur_event = inning_events.bottom[len(inning_events.bottom) - 1].des if cur_event != last_event and cur_event != "": print(cur_event) last_event = cur_event elif len(inning_events.top) > 0: # if top inning # for ev in inning_events.bottom: # print(ev.des) cur_event = inning_events.top[len(inning_events.top) - 1].des if cur_event != last_event and cur_event != "": print(cur_event) last_event = cur_event
def get_day_games_info(month: int, day: int, year: int) -> List[Dict[str, Any]]: """ Get basic info for games on a particular day. Args: month (int): Month of day day (int): The day year (int): Year of day Returns: List[Dict[str, Any]]: Basic game info in JSON format """ # Get basic info for games on the day. games = mlbgame.day(year, month, day) # Format the info into JSON and return. return [{ 'game_id': game.game_id, 'date': game.date.isoformat(), 'game_start_time': game.game_start_time, 'game_status': game.game_status, 'home_team': game.home_team, 'away_team': game.away_team } for game in games]
def looper(): #os.system('cls') threading.Timer(10.0, looper).start() gameday = datetime.datetime.now() # tomorrow = gameday - datetime.timedelta(1) noGameFound = True while noGameFound: #check for game gameday if len( mlbgame.day(gameday.year, gameday.month, gameday.day, home='Red Sox', away='Red Sox')) != 0: game = mlbgame.day(gameday.year, gameday.month, gameday.day, home='Red Sox', away='Red Sox')[0] noGameFound = False #if no game on the current day check on the next day else: gameday += datatime.timedelta(1) home_team = game.home_team away_team = game.away_team standings = mlbgame.standings() alEast = standings.divisions[3] #game is over, display final score if (game.game_status == "FINAL"): printStandings(alEast) printFinalScore(game) printTweets() #display upcoming game info + standings elif (game.game_status == "PRE_GAME"): printStandings(alEast) printUpcomingGame(game) printTweets() #game is on, display live game info else: printCurrentGame(game)
def stack_main(): day = mlbgame.day(2017, 6, 7) stack_info = [] for game in day: stack_info = stack_stats(stack_info, game) calculated_stacks = sort_stacks(stack_info) s = 0
def get_game(year, month, day, team): try: games = mlbgame.day(year, month, day, home=team) except: return None, None if len(games) > 0: return games[0], True try: games = mlbgame.day(year, month, day, away=team) except: return None, None if len(games) > 0: return games[0], False return None, None
def test_day(self): games = mlbgame.day(2016, 8, 2) for game in games: if game.home_team == 'Mets': g = game self.assertIsInstance(game.away_team, str) self.assertIsInstance(game.away_team_errors, int) self.assertIsInstance(game.away_team_hits, int) self.assertIsInstance(game.away_team_runs, int) self.assertIsInstance(game.date, datetime) self.assertIsInstance(game.game_id, str) self.assertIsInstance(game.game_league, str) self.assertIsInstance(game.game_start_time, str) self.assertIsInstance(game.game_status, str) self.assertIsInstance(game.game_tag, str) self.assertIsInstance(game.home_team, str) self.assertIsInstance(game.home_team_errors, int) self.assertIsInstance(game.home_team_hits, int) self.assertIsInstance(game.home_team_runs, int) self.assertIsInstance(game.l_pitcher, str) self.assertIsInstance(game.l_pitcher_losses, int) self.assertIsInstance(game.l_pitcher_wins, int) self.assertIsInstance(game.l_team, str) self.assertIsInstance(game.sv_pitcher, str) self.assertIsInstance(game.sv_pitcher_saves, int) self.assertIsInstance(game.w_pitcher, str) self.assertIsInstance(game.w_pitcher_losses, int) self.assertIsInstance(game.w_pitcher_wins, int) self.assertIsInstance(game.w_team, str) self.assertIsInstance(game.nice_score(), str) game = g self.assertEqual(game.away_team, 'Yankees') self.assertEqual(game.away_team_errors, 2) self.assertEqual(game.away_team_hits, 6) self.assertEqual(game.away_team_runs, 1) self.assertEqual(game.date, datetime(2016, 8, 2, 19, 10)) self.assertEqual(game.game_id, '2016_08_02_nyamlb_nynmlb_1') self.assertEqual(game.game_league, 'AN') self.assertEqual(game.game_start_time, '7:10PM') self.assertEqual(game.game_status, 'FINAL') self.assertEqual(game.game_tag, 'go_game') self.assertEqual(game.home_team, 'Mets') self.assertEqual(game.home_team_errors, 0) self.assertEqual(game.home_team_hits, 10) self.assertEqual(game.home_team_runs, 7) self.assertEqual(game.l_pitcher, 'M. Tanaka') self.assertEqual(game.l_pitcher_losses, 4) self.assertEqual(game.l_pitcher_wins, 7) self.assertEqual(game.l_team, 'Yankees') self.assertEqual(game.sv_pitcher, '. ') self.assertEqual(game.sv_pitcher_saves, 0) self.assertEqual(game.w_pitcher, 'J. deGrom') self.assertEqual(game.w_pitcher_losses, 5) self.assertEqual(game.w_pitcher_wins, 7) self.assertEqual(game.w_team, 'Mets') self.assertEqual(game.__str__(), 'Yankees (1) at Mets (7)')
def scoreCheck(user_date, team): if team == 'diamondbacks': team = 'd-backs' if len(str(user_date)) == 0: '''Captures missing date requests''' bad_date = render_template('bad_date') return question(bad_date) if isinstance(user_date, datetime.date) is not True: '''Tests whether the user_date is a valid date''' bad_date = render_template('bad_date') return question(bad_date) if team.capitalize() not in team_list: '''Tests whether an accurate team name was given''' bad_team = render_template('bad_team') return question(bad_team) if user_date < datetime.datetime.strptime('2005-04-03', "%Y-%m-%d").date(): out_of_date = render_template('out_of_date') return question(out_of_date) try: '''The scoreCheck() function accepts a team name and spoken date from the user, converts the month name to a number (because mlbgame requires integer dates), and returns the game score.''' _year = user_date.year _month = user_date.month _day = user_date.day global games games = mlbgame.day(_year, _month, _day, away=team.capitalize(), home=team.capitalize()) win_team = games[0].w_team win_pitcher = 'The winning pitcher was %s of the %s.' % (games[0].w_pitcher, games[0].w_team) for game in games: if len(games) == 0: '''mlbgame() returns data in a dictionary. If there is no game, the dictionary will be empty.''' no_game_look_up = render_template('no_game_look_up') return question(no_game_look_up) elif win_team == team.capitalize(): game_info = 'The ' + team.capitalize() + ' won. The final score was ' + str(game) + '. The winning pitcher was ' + str(games[0].w_pitcher) + ' of the ' + str(games[0].w_team) + '. Please CHECK another team and date, or say STOP to stop.' return question(game_info) elif win_team != team.capitalize(): game_info = 'The ' + team.capitalize() + ' lost. The final score was ' + str(game) + '. The winning pitcher was ' + str(games[0].w_pitcher) + ' of the ' + str(games[0].w_team) + '. Please CHECK another team and date, or say STOP to stop.' return question(game_info) except OSError: '''Returned if the user asked for a date before 2005''' out_of_date = render_template('out_of_date') return question(out_of_date) except IndexError: '''Rarely returned if the user asked for a date before 2005''' out_of_date = render_template('no_game_look_up') return question(out_of_date)
def curr_batter_status() : game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) curr_game_id = game_info[0].game_id CURR_BATTING_STATUS[Balls] = str(status_of_game.balls) CURR_BATTING_STATUS[Strikes] = str(status_of_game.strikes) CURR_OUTS = status_of_game.outs if(debug) : print("current info: ["+curr_balls+"]["+curr_strikes+"]["+curr_outs+"]:[" + curr_inning + "]")
def get_games_cache(year_range=range(2017, 2019), months=(3, 4, 5, 6, 7, 8, 9, 10), days=range(1, 32)): list_games = list() for year, month, day in tqdm.tqdm( itertools.product(year_range, months, days)): games = mlb.day(year, month, day) for game in games: list_games.append(game) return list_games
def today_stats(bot, update): today = datetime.date.today() year = today.year month = today.month day = today.day games = mlbgame.day(year, month, day) msg = "" for game in games: game_txt = "{}\n".format(game) msg += game_txt bot.send_message(chat_id=update.message.chat_id, text=msg)
async def scores_team(*, team): team = team.title() today = datetime.datetime.now() games = mlbgame.day(today.year, today.month, today.day, home=team, away=team) if not games: await bot.say("No games today") for game in games: await bot.say(game)
def populate_data(): divisions = mlbgame.standings().divisions todays_games = mlbgame.day(datetime.now().year, datetime.now().month, datetime.now().day) for division in divisions: for team in division.teams: t = TeamMapper(divisions, todays_games, abbreviation=team.team_abbrev) t.find_team() teams.append(t.team) return teams
def get_game(self): """Gets the last valid (not pre_game) game, so IN_PROGRESS or FINAL""" # CHECK to see what happens to game[0].game_status on rain outs/cancelled games... they are 'FINAL' self.get_date() # Gets todays date socket.setdefaulttimeout(100) self.game = mlbgame.day(self.year, self.month, self.day, home=self.team, away=self.team) adjust = -1 while self.game == [] or self.game[ -1].game_status == 'PRE_GAME': # If the game today hasn't started yet or there is no game at all today, look back each day to find one self.get_date(adjust) self.game = mlbgame.day(self.year, self.month, self.day, home=self.team, away=self.team) adjust -= 1 self.game = self.game[ -1] # Sets the game attribute to the actual game instead of a list containing a single game (this may mess up on days with doube-headers...)
def post_game() : game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) curr_game_id = game_info[0].game_id status_of_game = mlbgame.overview(curr_game_id) if(debug) : print("In the post_game state: ") #game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) if(debug) : print("FINAL SCORE: [" + str(status_of_game.home_team_runs) + "][" + str(status_of_game.away_team_runs) + "]") init_post_game_board(str(status_of_game.home_team_runs), str(status_of_game.away_team_runs), team_abrev[status_of_game.home_team_name], team_abrev[status_of_game.away_team_name]) time.sleep(1800) #check every 30 mins
def looper(): #os.system('cls') threading.Timer(10.0, looper).start() gameday = datetime.datetime.now() # tomorrow = gameday - datetime.timedelta(1) noGameFound = True while noGameFound: #check for game gameday if len(mlbgame.day(gameday.year, gameday.month, gameday.day, home='Red Sox', away = 'Red Sox')) != 0: game = mlbgame.day(gameday.year, gameday.month, gameday.day, home='Red Sox', away = 'Red Sox')[0] noGameFound = False #if no game on the current day check on the next day else: gameday += datatime.timedelta(1) home_team = game.home_team away_team = game.away_team standings = mlbgame.standings() alEast = standings.divisions[3] #game is over, display final score if(game.game_status == "FINAL"): printStandings(alEast) printFinalScore(game) printTweets() #display upcoming game info + standings elif(game.game_status == "PRE_GAME"): printStandings(alEast) printUpcomingGame(game) printTweets() #game is on, display live game info else: printCurrentGame(game)
async def scores(ctx): """ !scores or !scores team_name, for daily scores """ if ctx.invoked_subcommand is None: today = datetime.datetime.now() games = mlbgame.day(today.year, today.month, today.day, home=None, away=None) if not games: await bot.say("No games today") for game in games: await bot.say(game)
def game_in_progress() : if(debug) : print("Game is in Progress") game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) curr_game_id = game_info[0].game_id global CURR_INNING_INFO status_of_game = mlbgame.overview(curr_game_id) #if(debug) : print("status: " + status_of_game.status) while(status_of_game.status == "In Progress") : #game_info[0].game_status == IN_PROGRESS #status_of_game = mlbgame.overview(curr_game_id) ##################################################### ##################################################### #Check status of batter (balls and strikes) check_batter_status(status_of_game) ##################################################### ##################################################### #check if anyones one base check_bases_status(status_of_game) ##################################################### ##################################################### #Check status of inning (balls and strikes) check_inning_status(status_of_game) ##################################################### ##################################################### #check the current inning scores check_inning_scores(curr_game_id) ##################################################### ##################################################### check_RHE_status(status_of_game) #hold the updates until "MID or END of inning" is over midOrEnd = str(status_of_game.inning_state) while(midOrEnd == 'Middle' or midOrEnd == 'End') : #if(debug) : print("mid or end of inning") #time.sleep(10) status_of_game = mlbgame.overview(curr_game_id) midOrEnd = str(status_of_game.inning_state) time.sleep(10) #update scores every 30s #game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) status_of_game = mlbgame.overview(curr_game_id)
def refresh_games(self): attempts_remaining = 5 while attempts_remaining > 0: try: self.games = mlbgame.day(self.year, self.month, self.day) self.games_refresh_time = time.time() break except URLError, e: debug.error("URLError: {}".format(e.reason)) attempts_remaining -= 1 time.sleep(NETWORK_RETRY_SLEEP_TIME) except ValueError: debug.error("ValueError: Failed to refresh list of games") attempts_remaining -= 1 time.sleep(NETWORK_RETRY_SLEEP_TIME)
def main(): #while(True) : # init_board('H0U', 'TEX') # time.sleep(30) #check if any games today game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) if not game_info : # if there are no games today no_game() new_game_status() before_game() #initialize the board new_game_status()
def get_pirates(): returned_data = "time, game\n" for year in range(2016, 2017, 1): for month in range(1, 13, 1): for day in range(1, 32, 1): game = mlbgame.day(year, month, day, home="Pirates") if len(game) != 0: today = "%s/%s/%s" % (month, day, year) returned_data += "%s, %s\n" % (today, game[0]) pprint.pprint(returned_data) file_path = strftime("pirates%d%H%M%S.csv", gmtime()) output = open(file_path, "w+") output.write(returned_data) output.close()
def play_ball(): run_history = 0 while True: now = datetime.datetime.now() current_year = now.year current_month = now.month current_day = now.day current_hour = now.hour current_minute = now.minute datestr = "{0}-{1}-{2}-{3}:{4}".format(current_year, current_month, current_day, current_hour, current_minute) day = mlbgame.day(current_year, current_month, current_day, away='Blue Jays', home='Blue Jays') if len(day) > 0: game = day[0] if 'Blue Jays' in game.away_team: if int(game.away_team_runs) > run_history: logger(datestr, game.away_team_runs) run_history = game.away_team_runs try: goal_light(0, 0, 255, 5) except main.BulbException: time.sleep(5) goal_light(0, 0, 255, 5) check_winning(game.home_team_runs, game.away_team_runs, datestr) else: if int(game.home_team_runs) > run_history: logger(datestr, game.home_team_runs) run_history = game.home_team_runs try: goal_light(0, 0, 255, 5) except main.BulbException: time.sleep(5) goal_light(0, 0, 255, 5) check_winning(game.away_team_runs, game.home_team_runs, datestr) if int(current_hour) == 10 and int(run_history) != 0: print("hello") run_history = 0 logger(datestr, "reset") print("{0},{1}\n".format("reset", run_history)) time.sleep(1)
def _process_mlb_day_stats(self, yday): ''' Process the mlbgame data for a single day :param int yday: The day of the year to grab the stats for ''' # get the month and day from the yday number date = datetime(self.YEAR, 1, 1) + timedelta(yday - 1) #print("Adding stats for {} {}".format(date.strftime("%B"), date.day)) # walk through all games for this day for gamenumber in range(0, 16): try: game = mlbgame.day(2016, date.month, date.day)[gamenumber] stats = mlbgame.player_stats(game.game_id) # do pitchers first p_stats = stats['home_pitching'] + stats['away_pitching'] for pitcher in p_stats: if pitcher.id in self._pitcher_stats: pitcher_record = self._pitcher_stats[pitcher.id] else: pitcher_record = Pitcher( pitcher.name, pitcher.name_display_first_last, pitcher.id) self._pitcher_stats[pitcher.id] = pitcher_record #print('Added pitcher stats for {}'.format(pitcher_record)) pitcher_record.update_mlb_stats(pitcher) # now do batters, but don't add pitchers into batter_stats{} b_stats = stats['home_batting'] + stats['away_batting'] for batter in filter(lambda b: b.id not in self._pitcher_stats, b_stats): if batter.id in self._batter_stats: batter_record = self._batter_stats[batter.id] else: batter_record = Batter(batter.name, batter.name_display_first_last, batter.id) self._batter_stats[batter.id] = batter_record #print('Added batter stats for {}'.format(batter_record)) batter_record.update_mlb_stats(batter) except Exception as e: #print(e.message) pass
def new_game_status() : if(debug) : print("determining where to start: ") while(True) : refresh_day_time() game_info = mlbgame.day(today_year,today_month,today_day, HOME_TEAM, AWAY_TEAM) if not game_info : no_game() #if there are no games today global OVERALL_GAME_SCORE_AWAY global OVERALL_GAME_SCORE_HOME if(game_info[0].game_status == "PRE_GAME") : before_game() elif(game_info[0].game_status == "IN_PROGRESS") :game_in_progress() elif(game_info[0].game_status == "FINAL" ) : post_game() else : if(debug) : print("Can't understand status")
def _process_mlb_day_stats(self, yday): ''' Process the mlbgame data for a single day :param int yday: The day of the year to grab the stats for ''' # get the month and day from the yday number date = datetime(self.YEAR, 1, 1) + timedelta(yday - 1) #print("Adding stats for {} {}".format(date.strftime("%B"), date.day)) # walk through all games for this day for gamenumber in range(0, 16): try: game = mlbgame.day(2016, date.month, date.day)[gamenumber] stats = mlbgame.player_stats(game.game_id) # do pitchers first p_stats = stats['home_pitching'] + stats['away_pitching'] for pitcher in p_stats: if pitcher.id in self._pitcher_stats: pitcher_record = self._pitcher_stats[pitcher.id] else: pitcher_record = Pitcher(pitcher.name, pitcher.name_display_first_last, pitcher.id) self._pitcher_stats[pitcher.id] = pitcher_record #print('Added pitcher stats for {}'.format(pitcher_record)) pitcher_record.update_mlb_stats(pitcher) # now do batters, but don't add pitchers into batter_stats{} b_stats = stats['home_batting'] + stats['away_batting'] for batter in filter (lambda b: b.id not in self._pitcher_stats, b_stats): if batter.id in self._batter_stats: batter_record = self._batter_stats[batter.id] else: batter_record = Batter(batter.name, batter.name_display_first_last, batter.id) self._batter_stats[batter.id] = batter_record #print('Added batter stats for {}'.format(batter_record)) batter_record.update_mlb_stats(batter) except Exception as e: #print(e.message) pass
def run(hide=False, stats=False, events=False, overview=False, start=date(2012, 1, 12), end=None): """Update local game data.""" # set end to be the day before today at maximum today = date.today() if end == None or end >= today: end = today - timedelta(days=1) # check if the dates are in correct chronological order if start > end: date_usage() sys.exit(2) # print a message becuase sometimes it seems like the program is not doing anything if not hide: print("Checking local data...") # get information for loop d = start delta = timedelta(days=1) # calculate the days between the start and the end difference = float((end - start).days + .0) # loop through the dates while d <= end: i = d.year x = d.month y = d.day monthstr = str(x).zfill(2) daystr = str(y).zfill(2) # file information filename = "gameday-data/year_%i/month_%s/day_%s/scoreboard.xml.gz" % (i, monthstr, daystr) f = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename) dirn = "gameday-data/year_%i/month_%s/day_%s" % (i, monthstr, daystr) dirname = os.path.join(os.path.dirname(os.path.abspath(__file__)), dirn) # check if file exists # aka is the data saved if not os.path.isfile(f): # try becuase some dates may not have a file on the mlb.com server try: # get data from url data = urlopen("http://gd2.mlb.com/components/game/mlb/year_%i/month_%s/day_%s/scoreboard.xml" % (i, monthstr, daystr)) response = data.read() # check if the path exists where the file should go if not os.path.exists(dirname): try: # try to make the folder if permissions allow os.makedirs(dirname) except OSError: access_error(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gameday-data/')) try: # try to create the file if permissions allow with gzip.open(f, "w") as fi: fi.write(response) except OSError: access_error(dirname) # do nothing if the file is not on mlb.com except HTTPError: pass # get stats if specified if stats: try: # get the data for games on this day games = mlbgame.day(i, x, y) for z in games: # get the game id which is used to fetch data game_id = z.game_id # file information filename2 = "gameday-data/year_%i/month_%s/day_%s/gid_%s/boxscore.xml.gz" % (i, monthstr, daystr, game_id) f2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename2) dirn2 = "gameday-data/year_%i/month_%s/day_%s/gid_%s" % (i, monthstr, daystr, game_id) dirname2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), dirn2) # check if file exists # aka is the information saved if not os.path.isfile(f2): # try because some dates may not have a file on the mlb.com server # or some months don't have a 31st day try: # get data data2 = urlopen("http://gd2.mlb.com/components/game/mlb/year_%i/month_%s/day_%s/gid_%s/boxscore.xml" % (i, monthstr, daystr, game_id)) response2 = data2.read() # checking if files exist and writing new files if not os.path.exists(dirname2): try: os.makedirs(dirname2) except OSError: access_error(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gameday-data/')) # try to write file try: with gzip.open(f2, "w") as fi: fi.write(response2) except OSError: access_error(dirname2) except HTTPError: pass except: pass # get events if specified if events: try: # get the data for games on this day games = mlbgame.day(i, x, y) for z in games: # get the game id which is used to fetch data game_id = z.game_id # file information filename3 = "gameday-data/year_%i/month_%s/day_%s/gid_%s/game_events.xml.gz" % (i, monthstr, daystr, game_id) f3 = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename3) dirn3 = "gameday-data/year_%i/month_%s/day_%s/gid_%s" % (i, monthstr, daystr, game_id) dirname3 = os.path.join(os.path.dirname(os.path.abspath(__file__)), dirn3) if not os.path.isfile(f3): # try because some dates may not have a file on the mlb.com server # or some months don't have a 31st day try: # get data data3 = urlopen("http://gd2.mlb.com/components/game/mlb/year_%i/month_%s/day_%s/gid_%s/game_events.xml" % (i, monthstr, daystr, game_id)) response3 = data3.read() # checking if files exist and writing new files if not os.path.exists(dirname3): try: os.makedirs(dirname3) except OSError: access_error(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gameday-data/')) # try to write file try: with gzip.open(f3, "w") as fi: fi.write(response3) except OSError: access_error(dirname3) except HTTPError: pass except: pass # get overview if specified if overview: try: # get the data for games on this day games = mlbgame.day(i, x, y) for z in games: # get the game id which is used to fetch data game_id = z.game_id # file information filename4 = "gameday-data/year_%i/month_%s/day_%s/gid_%s/linescore.xml.gz" % (i, monthstr, daystr, game_id) f4 = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename4) dirn4 = "gameday-data/year_%i/month_%s/day_%s/gid_%s" % (i, monthstr, daystr, game_id) dirname4 = os.path.join(os.path.dirname(os.path.abspath(__file__)), dirn4) # check if file exists # aka is the information saved if not os.path.isfile(f4): # try because some dates may not have a file on the mlb.com server # or some months don't have a 31st day try: # get data data4 = urlopen("http://gd2.mlb.com/components/game/mlb/year_%i/month_%s/day_%s/gid_%s/linescore.xml" % (i, monthstr, daystr, game_id)) response4 = data4.read() # checking if files exist and writing new files if not os.path.exists(dirname4): try: os.makedirs(dirname4) except OSError: access_error(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gameday-data/')) # try to write file try: with gzip.open(f4, "w") as fi: fi.write(response4) except OSError: access_error(dirname4) except HTTPError: pass except: pass # loading message to show something is actually happening if not hide: sys.stdout.write('Loading games (%00.2f%%) \r' % ((1-((end - d).days/difference))*100)) sys.stdout.flush() # increment the date counter d += delta if not hide: # make sure loading ends at 100% sys.stdout.write('Loading games (100.00%).\n') sys.stdout.flush() # show finished message print("Complete.")
def run(hide=False, more=False, start="01-01-2012", end=None): """Update local game data.""" # get today's information year = date.today().year month = date.today().month day = date.today().day # get ending date information if end != None: end_month, end_day, end_year = end.split("-") end_month, end_day, end_year = [int(end_month), int(end_day), int(end_year)] else: end_year = year end_month = month end_day = day # get starting date information start_month, start_day, start_year = start.split("-") first_day, first_month, last_month = [True, True, False] # print a message becuase sometimes it seems like the program is not doing anything if not hide: print("Checking local data...") # looping years for i in range(int(start_year), end_year+1): # checking if starting month value needs to be used if first_month: ms = int(start_month) first_month = False else: ms = 1 # looping months me = 13 if i == end_year: me = end_month+1 last_month = True for x in range(ms, me): monthstr = str(x).zfill(2) loading = False if i == year and x > month: break # checking if starting day value needs to be used if first_day: ds = int(start_day) first_day = False else: ds = 1 # looping days de = 32 if last_month: de = end_day+1 for y in range(ds, de): if i == year and x >= month and y >= day: break daystr = str(y).zfill(2) # file information filename = "gameday-data/year_%i/month_%s/day_%s/scoreboard.xml.gz" % (i, monthstr, daystr) f = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename) dirn = "gameday-data/year_%i/month_%s/day_%s" % (i, monthstr, daystr) dirname = os.path.join(os.path.dirname(os.path.abspath(__file__)), dirn) # check if file exists # aka is the data saved if not os.path.isfile(f): # try becuase some dates may not have a file on the mlb.com server # or some months don't have a 31st day try: # get data from url data = urlopen("http://gd2.mlb.com/components/game/mlb/year_%i/month_%s/day_%s/scoreboard.xml" % (i, monthstr, daystr)) # loding bar to show something is actually happening if not hide: sys.stdout.write('Loading games for %s-%d (%00.2f%%) \r' % (monthstr, i, y/31.0*100)) sys.stdout.flush() loading = True response = data.read() # check if the path exists where the file should go if not os.path.exists(dirname): try: # try to make the folder if permissions allow os.makedirs(dirname) except OSError: access_error(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gameday-data/')) try: # try to create the file if permissions allow with gzip.open(f, "w") as fi: fi.write(response) except OSError: access_error(dirname) # do nothing if the file is not on mlb.com except HTTPError: pass # get extra data if specified if more: try: # get the data for games on this day games = mlbgame.day(i, x, y) for z in games: # get the game id which is used to fetch data game_id = z.game_id # file information filename2 = "gameday-data/year_%i/month_%s/day_%s/gid_%s/boxscore.xml.gz" % (i, monthstr, daystr, game_id) f2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename2) dirn2 = "gameday-data/year_%i/month_%s/day_%s/gid_%s" % (i, monthstr, daystr, game_id) dirname2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), dirn2) # check if file exists # aka is the information saved if not os.path.isfile(f2): # try becuase some dates may not have a file on the mlb.com server # or some months don't have a 31st day try: # get data data2 = urlopen("http://gd2.mlb.com/components/game/mlb/year_%i/month_%s/day_%s/gid_%s/boxscore.xml" % (i, monthstr, daystr, game_id)) if not hide: # progress sys.stdout.write('Loading games for %s-%d (%00.2f%%). \r' % (monthstr, i, y/31.0*100)) sys.stdout.flush() loading = True response2 = data2.read() # checking if files exist and writing new files if not os.path.exists(dirname2): try: os.makedirs(dirname2) except OSError: access_error(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gameday-data/')) # try to write file try: with gzip.open(f2, "w") as fi: fi.write(response2) except OSError: access_error(dirname2) except HTTPError: pass except: pass if loading and not hide: # make sure loading ends at 100% sys.stdout.write('Loading games for %s-%d (100.00%%).\n' % (monthstr, i)) sys.stdout.flush() # print finished message if not hide: print("Complete.")