Ejemplo n.º 1
0
	async def final_Game_Embed(self, game, message):
		# If for some reason we get a list, take the first object
		if type(game) == list:
			game = game[0]


		# Get the UTC datetime string
		gameTimeLocal = self.commonFunctions.get_Local_Time(game['game_datetime'])

		# List of status that indicate the game is over
		final_status_list = ["Final", "Game Over", "Completed Early"]
		# Game is over
		if any(game_status in game['status'] for game_status in final_status_list):

			# Create the final game embed object
			finalGameEmbed = discord.Embed()
			finalGameEmbed.type = 'rich'
			finalGameEmbed.color = discord.Color.dark_blue()

			# Add the fields with game info
			finalGameEmbed.add_field(name='**' + game['away_name'] + '** vs **' + game['home_name'] + '**\n',
									 value='```js\n' + statsapi.linescore(game['game_id']) + '```', inline=False)
			# Check for a valid key and value
			if 'winning_pitcher' in game and game['winning_pitcher'] != None:
				finalGameEmbed.add_field(name='Winning Pitcher:', value=game['winning_pitcher'], inline=True)
			if 'losing_pitcher' in game and game['losing_pitcher'] != None:
				finalGameEmbed.add_field(name='Losing Pitcher:', value=game['losing_pitcher'], inline=True)
			if 'save_pitcher' in game and game['save_pitcher'] != None:
				finalGameEmbed.add_field(name='Save:', value=game['save_pitcher'], inline=False)

			await message.channel.send(content='Final score from ' + gameTimeLocal.strftime('%m/%d/%Y'),
									   embed=finalGameEmbed, tts=False)

			# A special message if the Yankees lost
			# First check if the Yankees were playing
			if 'New York Yankees' in game['home_name'] or 'New York Yankees' in game['away_name']:
				yakeesLose = False
				# Get the scores
				homeScore = game['home_score']
				awayScore = game['away_score']
				if 'New York Yankees' in game['home_name']:
					if homeScore < awayScore:
						yakeesLose = True
				else:
					if awayScore < homeScore:
						yakeesLose = True

				if yakeesLose:
					await message.channel.send('https://youtu.be/BFD46s_JRNI')
				else:
					print('DEBUG: Boo the yankees won')


		else:
			finalScoreString = '**' + game['home_name'] + '** vs **' + game['away_name'] + '**\n'

			finalScoreString = finalScoreString + 'Game on ' + gameTimeLocal.strftime('%m/%d/%Y') + ' **' + game[
				'status'] + '**'

			await message.channel.send(content=finalScoreString, tts=False)
Ejemplo n.º 2
0
def get_score(team):
    games_today = game_list()

    # returns list of linescores from todays games
    game_scores = [statsapi.linescore(game) for game in games_today]

    # returns todays linescore, prints message if no score
    line = "The {} did not play today".format(team.title())
    for i in game_scores:
        if team.title() in i:
            line = i
    return line
Ejemplo n.º 3
0
def box_scores():
    """ Use MLB Stats API to extract daily MLB box scores for use in Live Game Watchability Index calculation

    Returns:
        {Date: {Home-Away First Code: (Home Score, Away Score), ..., Home-Away Last Code: (Home Score, Away Score)}}
    """
    # Create dynamic variable to get yesterday's box scores
    yesterday = (datetime.datetime.today() -
                 timedelta(days=1)).strftime('%Y-%m-%d')
    schedule = statsapi.schedule(yesterday)

    # Retrieve values from schedule dictionary
    game_info = [list(schedule[i].values()) for i in range(len(schedule))]

    # Extract game codes from schedule dictionary values
    game_codes = [game_info[i][0] for i in range(len(game_info))]

    # Use game codes to retrieve all info for correct games
    home_away = []
    for i in range(len(game_codes)):
        home_away.append(statsapi.boxscore_data(game_codes[i]))

    # Use game codes to retrieve box scores for correct games
    boxes = []
    for i in range(len(game_codes)):
        home_box = (statsapi.linescore(game_codes[i]).splitlines()[2])
        away_box = (statsapi.linescore(game_codes[i]).splitlines()[1])
        boxes.extend([home_box, away_box])

    # Create dictionary with Home-Away concatenation as key and scores as values
    box_score = {}
    for i in range(len(home_away)):
        home_away_codes = (list(home_away[i]['teamInfo']['home'].values())[1] +
                           list(home_away[i]['teamInfo']['away'].values())[1])
        box_score.update({home_away_codes: (boxes[i * 2], boxes[(i * 2) + 1])})

    # Create main dictionary with date as key and box score dictionary as value
    score_dict = {yesterday: box_score}

    return score_dict
Ejemplo n.º 4
0
    async def run(self, client, channel):
        error_msg = self.read_settings()
        if error_msg != 0:
            print(error_msg)
            return

        print('in BaseballUpdaterBotV2.run()')

        while True:
            idsOfPrevEvents = self.getEventIdsFromLog()
            todaysGame = (datetime.now() - timedelta(hours=5))
            how_long_to_wait_in_sec = 300

            sched = statsapi.schedule(date=todaysGame.strftime("%m/%d/%Y"),
                                      team=self.TEAM_ID)
            if not sched:
                noGameId = ''.join(
                    ["NoGameToday",
                     todaysGame.strftime("%m/%d/%Y")])
                if noGameId not in idsOfPrevEvents:
                    await self.postNoGameStatusOnDiscord(channel)
                    self.printNoGameToLog(noGameId)
                print("[{}] No game today".format(self.getTime()))
                how_long_to_wait_in_sec = 1000
            for game in sched:
                homeTeamNames = self.lookupTeamInfo(game['home_id'])
                awayTeamNames = self.lookupTeamInfo(game['away_id'])

                # First, check if the game status has changed
                gameStatus = game['status']
                gameStatusId = ''.join(
                    [gameStatus.replace(" ", ""), ';',
                     str(game['game_id'])])
                if gameStatusId not in idsOfPrevEvents:
                    await self.postGameStatusOnDiscord(channel, game)
                    self.printStatusToLog(gameStatusId, gameStatus)
                print("[{}] Game is {}".format(self.getTime(), gameStatus))

                # Change the update period based on the gameStatus
                if gameStatus == 'Scheduled':
                    how_long_to_wait_in_sec = 300
                if gameStatus == 'Pre-Game':
                    how_long_to_wait_in_sec = 60
                if gameStatus == 'Warmup':
                    how_long_to_wait_in_sec = 60
                if gameStatus == 'Game Over':
                    how_long_to_wait_in_sec = 60
                if gameStatus == 'Postponed':
                    how_long_to_wait_in_sec = 300
                if gameStatus == 'Final':
                    how_long_to_wait_in_sec = 300
                if gameStatus == 'Delayed: Rain':
                    how_long_to_wait_in_sec = 300
                if gameStatus == 'Completed Early: Rain':
                    how_long_to_wait_in_sec = 300
                if gameStatus == 'Game Over: Tied':
                    how_long_to_wait_in_sec = 300
                if gameStatus == 'Final: Tied':
                    how_long_to_wait_in_sec = 300

                if gameStatus == 'In Progress':
                    how_long_to_wait_in_sec = 10

                    # Game Event logic
                    gameInfo = statsapi.get('game',
                                            {'gamePk': game['game_id']})
                    liveData = gameInfo['liveData']
                    plays = liveData['plays']['allPlays']
                    linescore = liveData['linescore']
                    fullLinescoreString = statsapi.linescore(game['game_id'])
                    strikeoutTracker = {
                        'home': [],
                        'away': []
                    }  # Boolean list, true = swinging, false = looking
                    for play in plays:
                        # If the item is not full yet (as in the atbat is finished) skip
                        if not 'description' in play['result'].keys():
                            continue

                        # Get info from plays
                        info = {}
                        info['homeTeamFullName'] = homeTeamNames['name']
                        info['homeTeamName'] = homeTeamNames['teamName']
                        info['homeTeamShortFullName'] = homeTeamNames[
                            'shortName']
                        info['homeTeamAbbv'] = homeTeamNames['fileCode']
                        info['awayTeamFullName'] = awayTeamNames['name']
                        info['awayTeamName'] = awayTeamNames['teamName']
                        info['awayTeamShortFullName'] = awayTeamNames[
                            'shortName']
                        info['awayTeamAbbv'] = awayTeamNames['fileCode']
                        # added batterID to info, in order to lookup teamid if needed #
                        info['batterID'] = play['matchup']['batter']['id']
                        #################################################
                        info['startTime'] = play['about']['startTime']
                        info['inning'] = str(play['about']['inning'])
                        info['inningHalf'] = play['about']['halfInning']
                        info['balls'] = str(play['count']['balls'])
                        info['strikes'] = str(play['count']['strikes'])
                        info['outs'] = str(play['count']['outs'])
                        info['homeScore'] = str(play['result']['homeScore'])
                        info['awayScore'] = str(play['result']['awayScore'])
                        info['description'] = play['result']['description']
                        info['event'] = play['result']['event']
                        info['rbi'] = play['result']['rbi']
                        info['playType'] = play['result']['type']
                        info['manOnFirst'] = True if 'postOnFirst' in play[
                            'matchup'] else False
                        info['manOnSecond'] = True if 'postOnSecond' in play[
                            'matchup'] else False
                        info['manOnThird'] = True if 'postOnThird' in play[
                            'matchup'] else False
                        info['runsScored'] = 0
                        info['rbis'] = 0
                        info['runsEarned'] = 0
                        for runner in play['runners']:
                            info['runsScored'] += 1 if runner['details'][
                                'isScoringEvent'] else 0
                            info[
                                'rbis'] += 1 if runner['details']['rbi'] else 0
                            info['runsEarned'] += 1 if runner['details'][
                                'earned'] else 0

                        # Get info from linescore
                        info['outs_linescore'] = linescore['outs']
                        info['homeStats_linescore'] = linescore['teams'][
                            'home']  #runs, hits, errors, lefOnBase
                        info['awayStats_linescore'] = linescore['teams'][
                            'away']
                        info['currentInning_linescore'] = linescore[
                            'currentInning']
                        info['inningState_linescore'] = linescore[
                            'inningState']  # Middle or End
                        info['inningHalf_linescore'] = linescore['inningHalf']

                        # Get full linescore summary
                        info['fullLinescoreString'] = fullLinescoreString

                        # playType isn't working, do it yourself
                        info['playTypeActual'] = self.getPlayType(
                            info['description'])

                        # Update strikeout tracker
                        if info['event'] == 'Strikeout':
                            if self.homeTeamBatting(info):
                                currentStrikeouts = strikeoutTracker['away']
                                if "strikes out" in info['description']:
                                    currentStrikeouts.append(True)
                                if "called out on strikes" in info[
                                        'description']:
                                    currentStrikeouts.append(False)
                                strikeoutTracker['away'] = currentStrikeouts
                            else:
                                currentStrikeouts = strikeoutTracker['home']
                                if "strikes out" in info['description']:
                                    currentStrikeouts.append(True)
                                if "called out on strikes" in info[
                                        'description']:
                                    currentStrikeouts.append(False)
                                strikeoutTracker['home'] = currentStrikeouts
                        info['strikeoutTracker'] = strikeoutTracker

                        # Generate ID unique for each play
                        info['id'] = ''.join([
                            info['startTime'], ';', info['outs'], ';',
                            info['inning'], ';', info['homeScore'], ';',
                            info['awayScore'], ';',
                            info['description'].replace(" ", "")
                        ])

                        # if ID is not in log, add it to log and then post update on Discord
                        if info['id'] not in idsOfPrevEvents:
                            self.printToLog(info)
                            await channel.send(self.commentOnDiscordEvent(info)
                                               )

            await asyncio.sleep(how_long_to_wait_in_sec)

        # Should never reach here
        print("/*------------- End of Bot.run() -------------*/")
Ejemplo n.º 5
0
 def get_linescore(self, gamePk):
     """gets a formatted linescore"""
     return statsapi.linescore(gamePk)
Ejemplo n.º 6
0
def linescore(game_id):
    linescore = statsapi.linescore(game_id)
    return linescore
Ejemplo n.º 7
0
import statsapi
from teams_info import teams_info

if __name__ == '__main__':
    teams_dict = teams_info()
    for teamId in teams_dict.keys():
        most_recent_game_id = statsapi.last_game(teamId)
        print(statsapi.boxscore(most_recent_game_id))
        print(statsapi.linescore(most_recent_game_id))


    statsapi.linescore(gamePk, timecode=None)
    params = {
        "gamePk": gamePk,
        "fields": "gameData,teams,teamName,shortName,status,abstractGameState,liveData,linescore,innings,num,home,away,runs,hits,errors",
    }
Ejemplo n.º 8
0
	async def live_Game_Embed(self, game, message):
		# If for some reason we get a list, take the first object
		if type(game) == list:
			game = game[0]

		homeTeam = statsapi.lookup_team(game['home_name'])
		awayTeam = statsapi.lookup_team(game['away_name'])

		homeTeamShort = homeTeam[0]['fileCode'].upper()
		awayTeamShort = awayTeam[0]['fileCode'].upper()
		# print(game['game_id'])
		'''
		homeScore = game['home_score']
		homeScoreString = str(homeScore)
		awayScore = game['away_score']
		awayScoreString = str(awayScore)
		
		if homeScore > awayScore:
			homeScoreString = '**' + homeScoreString + '**'
		elif awayScore > homeScore:
			awayScoreString = '**' + awayScoreString + '**'
		
		'''
		# Build the content string
		# liveScoreString = '**' +  game['home_name'] + '** vs **' + game['away_name'] + '**\n'

		# liveScoreString = liveScoreString + game['inning_state'] + ' ' + str(game['current_inning']) + '\n'

		# liveScoreString = liveScoreString + '```js\n' + statsapi.linescore(game['game_id']) + '```'

		contextParams = {'gamePk': game['game_id']}
		game_contextMetrics = statsapi.get(endpoint='game_contextMetrics', params=contextParams)
		gameType = game_contextMetrics['game']['gameType']

		# Create the embed object
		scoreEmbed = discord.Embed()

		# Regular Season
		if gameType == 'R':
			scoreEmbed.title = '**' + game['away_name'] + '** vs **' + game['home_name'] + '**'
		# Wildcard
		elif gameType == 'F':
			# Check if the game is a tiebreaker
			if game_contextMetrics['game']['tiebreaker'] == 'N':
				scoreEmbed.title = '**Wildcard Game**\n\n**' + game['away_name'] + '** vs **' + game['home_name'] + '**'
			else:
				scoreEmbed.title = '**Wildcard Tiebreaker Game**\n\n**' + game['away_name'] + '** vs **' + game[
					'home_name'] + '**'
		# Division Series
		elif gameType == 'D':
			homeRecordString = str(game_contextMetrics['game']['teams']['home']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['home']['leagueRecord']['losses'])
			awayRecordString = str(game_contextMetrics['game']['teams']['away']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['away']['leagueRecord']['losses'])
			scoreEmbed.title = '**Division Series Game ' + str(
				game_contextMetrics['game']['seriesGameNumber']) + '**\n\n**' + game[
								   'away_name'] + '**(' + awayRecordString + ') vs ' + '**' + game[
								   'home_name'] + '**(' + homeRecordString + ')'
		# League Championship Series
		elif gameType == 'L':
			homeRecordString = str(game_contextMetrics['game']['teams']['home']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['home']['leagueRecord']['losses'])
			awayRecordString = str(game_contextMetrics['game']['teams']['away']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['away']['leagueRecord']['losses'])
			scoreEmbed.title = '**League Championship Series Game ' + str(
				game_contextMetrics['game']['seriesGameNumber']) + '**\n\n**' + game[
								   'away_name'] + '**(' + awayRecordString + ') vs ' + '**' + game[
								   'home_name'] + '**(' + homeRecordString + ')'
		# World Series
		elif gameType == 'W':
			homeRecordString = str(game_contextMetrics['game']['teams']['home']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['home']['leagueRecord']['losses'])
			awayRecordString = str(game_contextMetrics['game']['teams']['away']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['away']['leagueRecord']['losses'])
			scoreEmbed.title = '**World Series Game ' + str(
				game_contextMetrics['game']['seriesGameNumber']) + '**\n\n**' + game[
								   'away_name'] + '**(' + awayRecordString + ') vs ' + '**' + game[
								   'home_name'] + '**(' + homeRecordString + ')'
		# Spring Training
		elif gameType == 'S':
			homeRecordString = str(game_contextMetrics['game']['teams']['home']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['home']['leagueRecord']['losses'])
			awayRecordString = str(game_contextMetrics['game']['teams']['away']['leagueRecord']['wins']) + '-' + str(
				game_contextMetrics['game']['teams']['away']['leagueRecord']['losses'])
			scoreEmbed.title = '**Spring Training**\n\n**' + game['away_name'] + '** vs **' + game['home_name'] + '**'
		else:
			scoreEmbed.title = '**' + game['away_name'] + '** vs **' + game['home_name'] + '**'

		scoreEmbed.type = 'rich'
		scoreEmbed.color = discord.Color.dark_blue()

		scoreEmbed.add_field(name='**' + game['inning_state'] + ' ' + str(game['current_inning']) + '**',
							 value='```js\n' + statsapi.linescore(game['game_id']) + '```', inline=False)
		# scoreEmbed.add_field(name=awayTeamShort , value=awayScoreString, inline=True)
		# scoreEmbed.add_field(name='Linescore', value='```' + statsapi.linescore(game['game_id']) + '```')

		homeWinProb = '{:.1f}'.format(game_contextMetrics['homeWinProbability'])
		awayWinProb = '{:.1f}'.format(game_contextMetrics['awayWinProbability'])

		# Show the win %
		scoreEmbed.add_field(name='**Win Probability**',
							 value=awayTeamShort + ' ' + awayWinProb + ' - ' + homeTeamShort + ' ' + homeWinProb + '%')
		# scoreEmbed.add_field(name=homeTeamShort + ' win %', value=game_contextMetrics['homeWinProbability'].format(1), inline=True)
		# scoreEmbed.add_field(name=awayTeamShort + ' win %', value=game_contextMetrics['awayWinProbability'].format(1), inline=True)

		'''
		DEBUG: game_contextMetrics
		DEBUG: %s {'game': {'gamePk': 55555, 'link': '/api/v1/game/55555/feed/live', 'gameType': 'R', 'season': '2006', 
		'gameDate': '2006-06-10T03:33:00Z', 'status': {'abstractGameState': 'Final', 'codedGameState': 'F', 
		'detailedState': 'Final', 'statusCode': 'F', 'startTimeTBD': True, 'abstractGameCode': 'F'}, 
		'teams': {'away': {'leagueRecord': {'wins': 7, 'losses': 0, 'pct': '1.000'}, 'score': 5, 
		'team': {'id': 604, 'name': 'DSL Blue Jays', 'link': '/api/v1/teams/604'}, 'isWinner': True, 
		'splitSquad': False, 'seriesNumber': 7}, 'home': {'leagueRecord': {'wins': 2, 'losses': 4, 'pct': '.333'}, 
		'score': 3, 'team': {'id': 616, 'name': 'DSL Indians', 'link': '/api/v1/teams/616'}, 'isWinner': False, 
		'splitSquad': False, 'seriesNumber': 6}}, 'venue': {'id': 401, 'name': 'Generic', 
		'link': '/api/v1/venues/401'}, 'content': {'link': '/api/v1/game/55555/content'}, 'isTie': False, 
		'gameNumber': 1, 'publicFacing': True, 'doubleHeader': 'N', 'gamedayType': 'N', 'tiebreaker': 'N', 
		'calendarEventID': '44-55555-2006-06-10', 'seasonDisplay': '2006', 'dayNight': 'day', 'scheduledInnings': 9, 
		'inningBreakLength': 0, 'gamesInSeries': 1, 'seriesGameNumber': 1, 'seriesDescription': 'Regular Season', 
		'recordSource': 'S', 'ifNecessary': 'N', 'ifNecessaryDescription': 'Normal Game', 
		'gameId': '2006/06/10/dblrok-dinrok-1'}, 'expectedStatisticsData': {}, 'leftFieldSacFlyProbability': {}, 
		'centerFieldSacFlyProbability': {}, 'rightFieldSacFlyProbability': {}, 'awayWinProbability': 100.0, 
		'homeWinProbability': 0.0}
		'''

		# If the game is not a spring training game, pull the scoring plays
		if gameType != 'S':

			scoringPlaysList = statsapi.game_scoring_play_data(game['game_id'])
			scoringPlays = scoringPlaysList['plays']
			#print(*scoringPlays)

			'''
			{'result': {'description': 'Mike Yastrzemski homers (8) on a fly ball to right field.  ', 
			'awayScore': 1, 'homeScore': 0}, 'about': {'atBatIndex': 1, 'halfInning': 'top', 'inning': 1, 
			'endTime': '2020-09-02T19:14:09.256Z'}, 'atBatIndex': 1} 
			'''

			if len(scoringPlays) > 0:
				# scoringPlaysList = scoringPlays.split('\n\n')
				# for plays in scoringPlaysList:
				#	scoreEmbed.add_field(name=str(scoringPlaysList.index(plays) + 1), value=plays, inline=False)

				# Display only the latest scoring play
				scoreEmbed.add_field(name='**Latest scoring play**', value=scoringPlays[len(scoringPlays) - 1]['result']['description'],
									 inline=False)
				if len(scoringPlays) > 1:
					# Set the footer to inform the user about additional plays
					scoreEmbed.set_footer(text='Reply with \'more\' in 30 seconds to see all scoring plays')

			# Send the message
			await message.channel.send(embed=scoreEmbed, tts=False)

			if len(scoringPlays) > 1:
				# Wait for the user response
				if await self.commonFunctions.wait_for_response(message, 'more', 30):
					# Create a new embed object to contain all scoring plays
					allPlaysEmbed = discord.Embed()
					# allPlaysEmbed.title = '**All scoring plays**'
					allPlaysEmbed.type = 'rich'
					allPlaysEmbed.color = discord.Color.dark_blue()
					scoring_plays_string = ""
					for index, plays in enumerate(scoringPlays):
						scoring_plays_string = scoring_plays_string + str(index + 1) + '. ' + plays['result']['description'] + '\n\n'
					allPlaysEmbed.add_field(name='**All scoring plays**',
											value=scoring_plays_string, inline=False)

					# for plays in scoringPlays:
					# 	allPlaysEmbed.add_field(name=str(scoringPlays.index(plays) + 1),
					# 							value=plays['result']['description'], inline=False)
					await message.channel.send(embed=allPlaysEmbed, tts=False)
					return
				else:
					return
			return
		else:
			# Send the message
			await message.channel.send(embed=scoreEmbed, tts=False)
			return
Ejemplo n.º 9
0
 def printBoxScore(game):
     os.system('cls' if os.name == 'nt' else 'clear')
     print(sa.linescore(game['game_id']))