Exemplo n.º 1
0
def pitching_everything2019():
    sched = statsapi.schedule(start_date='03/28/2019',
                              end_date='09/29/2019',
                              team=137)
    for i in range(len(sched)):
        gameId = sched[i]["game_id"]
        game_date = sched[i]["game_date"]
        scoredata = statsapi.boxscore_data(gameId)
        if sched[i]["game_type"] == "R":
            if game_date != '2019-05-08':
                for ID in scoredata['playerInfo']:
                    if sched[i]['home_name'] == "San Francisco Giants":
                        if ID in scoredata['home']['players']:
                            if scoredata['home']['players'][ID]['stats'][
                                    'pitching'] != {}:
                                if scoredata['home']['players'][ID][
                                        'position']['abbreviation'] == 'P':
                                    h_add(game_date, scoredata, ID)
                    else:
                        if ID in scoredata['away']['players']:
                            if scoredata['away']['players'][ID]['stats'][
                                    'pitching'] != {}:
                                if scoredata['away']['players'][ID][
                                        'position']['abbreviation'] == 'P':
                                    a_add(game_date, scoredata, ID)
Exemplo n.º 2
0
 def getGameInfo(teamID):
     nextGameData = sa.boxscore_data(sa.next_game(teamID))['teamInfo']
     nextGameDate = sa.schedule(game_id = sa.next_game(teamID))[0]['game_date']
     if (nextGameData['away']['id'] != teamID):
         return [nextGameData['away']['teamName'], nextGameDate]
     else:
         return [nextGameData['home']['teamName'], nextGameDate]
Exemplo n.º 3
0
    def post(self, request):
        data = request.data["action"]
        with open("configure_package/mlb_team_list.json") as schedule:
            mlb_team_list = json.load(schedule)
        request_team = data["parameters"]["team"]["value"]
        team_id = mlb_team_list[request_team]

        time = datetime.now()
        date_and_team = []
        default_start_date = time.strftime("%Y-%m-%d")
        default_end_date = (time + timedelta(days=365)).strftime("%Y-%m-%d")

        team_schedule = statsapi.schedule(start_date=default_start_date,
                                          end_date=default_end_date,
                                          team=team_id)
        date_and_team.append(team_schedule[0]["game_date"])
        date_and_team.append(team_schedule[0]["away_name"])

        with open(
                "configure_package/mlb_i18n_team_list.json") as mlb_i18n_team:
            away_team_list = json.load(mlb_i18n_team)

        response_builder = {
            "version": "2.0",
            "resultCode": "OK",
            "output": {
                "our_team": request_team,
                "return_game_date": date_and_team[0],
                "return_away_name": away_team_list[date_and_team[1]],
            },
        }
        return Response(response_builder)
Exemplo n.º 4
0
def everything():
    year = '2021'
    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=2)
    tomorrow = today + datetime.timedelta(days=1)
    sched = statsapi.schedule(start_date=yesterday, end_date=tomorrow)
    for game in sched:
        gameId = game["game_id"]
        boxscore = statsapi.boxscore_data(gameId)
        gameDate = game["game_date"]
        if game['doubleheader'] != 'N':
            gameDate = game["game_date"] + "(" + str(
                game["game_num"]
            ) + ")"  #adds number to the back of the game date if the game is a part of a doubleheader

        homeId = game["home_id"]
        awayId = game["away_id"]
        homeAbbrev = statsapi.get(
            'team', {'teamId': homeId})['teams'][0]['abbreviation']
        awayAbbrev = statsapi.get(
            'team', {'teamId': awayId})['teams'][0]['abbreviation']

        if game['game_type'] == "R":
            createDir(homeAbbrev, year)  #if needed
            createDir(awayAbbrev, year)  #if needed

            hit(homeAbbrev, awayAbbrev, year, gameDate, game, boxscore)
            pitch(homeAbbrev, awayAbbrev, year, gameDate, game, boxscore)
        else:
            print(game['game_type'])
Exemplo n.º 5
0
    def on_enter_todayGame(self, event):
        print("I'm entering todayGame")
        reply_token = event.reply_token
        #games = statsapi.schedule(date = "09/15/2020")
        games = statsapi.schedule()
        message = []
        #for game in games:
        #    message.append(game)
        #value_now =
        print(message)
        message = message_template.now_table
        print(games)

        if (len(message["body"]["contents"][0]["contents"][0]["contents"]) !=
                1):
            message["body"]["contents"][0]["contents"][0]["contents"] = []
            data = {
                "type": "text",
                "text": "今日賽程\n",
                "size": "lg",
                "margin": "lg",
                "color": "#555555",
                "align": "center",
                "wrap": True,
            }
            message["body"]["contents"][0]["contents"][0]["contents"].append(
                data)
        if games == []:
            #print(message["body"]["contents"][0]["contents"][0]["contents"])
            if (len(message["body"]["contents"][0]["contents"][0]["contents"])
                    == 1):
                data = {
                    "type": "text",
                    "text": f"今日無比賽",
                    "wrap": True,
                }
                message["body"]["contents"][0]["contents"][0][
                    "contents"].append(data)
            else:
                message["body"]["contents"][0]["contents"][0]["contents"] = []
                message["body"]["contents"][0]["contents"][0][
                    "contents"].append(data)
        for game in games:
            home = game['home_name']
            away = game['away_name']
            home_score = game['home_score']
            away_score = game['away_score']
            data = {
                "type": "text",
                "text": f"{home}({home_score}) vs\n{away}({away_score})\n",
                "wrap": True,
            }
            message["body"]["contents"][0]["contents"][0]["contents"].append(
                data)
        message_to_reply = FlexSendMessage("賽程", message)
        line_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)
        print("abc")
        line_bot_api.reply_message(reply_token, message_to_reply)
        print("ggggggggggg")
        self.go_back()
Exemplo n.º 6
0
def exhibition_hitting():
    sched = statsapi.schedule(start_date='07/20/2020',
                              end_date='07/21/2020',
                              team=137)
    print(sched)
    for i in range(len(sched)):
        gameId = sched[i]["game_id"]
        game_date = sched[i]["game_date"]
        scoredata = statsapi.boxscore_data(gameId)
        if sched[i]['status'] == "Final: Tied":
            print("Final: Tied on", game_date)
        if sched[i]["game_type"] == "S":
            if sched[i]['status'] == "Final" or sched[i][
                    'status'] == "Game Over" or sched[i][
                        'status'] == "Final: Tied":
                for ID in scoredata['playerInfo']:
                    if sched[i]['home_name'] == "San Francisco Giants":
                        if ID in scoredata['home']['players']:
                            if scoredata['home']['players'][ID]['stats'][
                                    'batting'] != {}:
                                h_add(game_date, scoredata, ID)
                    else:
                        if ID in scoredata['away']['players']:
                            if scoredata['away']['players'][ID]['stats'][
                                    'batting'] != {}:
                                a_add(game_date, scoredata, ID)
Exemplo n.º 7
0
def lookup_games(d):
    games_dict = {}
    games = statsapi.schedule(date='%d/%d/%d' % (d.month, d.day, d.year))
    for game in games:
        games_dict[game['game_id']] = '%s @ %s' % (game['away_name'],
                                                   game['home_name'])
    return games_dict
Exemplo n.º 8
0
def gamethread_details(request, pk):
    this_thread = GameThread.objects.get(pk=pk)
    comments = Comment.objects.filter(thread=this_thread)[:30]
    comment_count = Comment.objects.filter(thread=this_thread).count()
    this_game = statsapi.schedule(date=this_thread, team=135)

    if request.method == 'POST':
        form = CommentForm(data=request.POST)

        if form.is_valid():
            if 'comment_body' in request.POST:
                comment_form = form.save(commit=False)
                comment_form.by = request.user
                comment_form.thread = this_thread

                comment_form.save()
                form = CommentForm()

        else:
            print(form.errors)

    else:
        form = CommentForm()

    context = {
        'this_game': this_game,
        'comments': comments,
        'comment_count': comment_count,
        'comment_form': form,
        'this_thread': this_thread,
    }
    return render(request, 'thread/gamethread_detail.html', context=context)
Exemplo n.º 9
0
def twoStrikeStats():
    sched = statsapi.schedule(start_date='07/23/2020',
                              end_date='09/27/2020',
                              team=137)
    twoStrikeHits = 0
    for i in range(len(sched)):
        gameId = sched[i]["game_id"]
        game_date = sched[i]["game_date"]
        game_result = sched[i]["summary"]
        game_status = sched[i]["status"]
        game = statsapi.get('game', {'gamePk': gameId})

        allPlays = game['liveData']['plays']['allPlays']
        if game_status != 'Postponed':
            for pa in allPlays:
                atTwoStrikes = False
                pitcherName = pa['matchup']['pitcher']['fullName']
                hitterName = pa['matchup']['batter']['fullName']
                playEvents = pa['playEvents']
                if hitterName == 'Mike Yastrzemski':
                    resultOfPlay = pa['result']['event']
                    resultOfPlayDescription = pa['result']['description']
                    lastPitch = playEvents[-1]
                    lastPitchStrikesInCount = lastPitch['count']['strikes']
                    if 'Caught' not in resultOfPlay and 'Pickoff' not in resultOfPlay:
                        if lastPitchStrikesInCount >= 2:
                            if resultOfPlay == 'Single' or resultOfPlay == 'Double' or resultOfPlay == 'Triple' or resultOfPlay == 'Home Run':
                                print(resultOfPlayDescription)
                                twoStrikeHits += 1
                    else:
                        input(pa)
    print(twoStrikeHits)
Exemplo n.º 10
0
def getSchedule(year):
    x = 1

    os.chdir('C:\\Users\\delevan\\PycharmProjects\\Senior-Project\\games')

    for month in range(4, 11):
        for day in range(1, monthrange(year, month)[1] + 1):

            date = str(month) + "/" + str(day) + "/" + str(year)
            games = mlb.schedule(start_date=date, end_date=date)
            print(games)

            schedule = pd.DataFrame(
                columns=['Home Team', 'Away Team', 'Game Date', 'Game Time'])
            for game in games:
                game_id = game['game_id']
                homeTeamAbbr = game['home_name']
                if (homeTeamAbbr == "American League All-Stars"
                        or homeTeamAbbr == "National League All-Stars"):
                    homeTeamAbbr = "New York Yankees"
                homeTeamAbbr = convertName(homeTeamAbbr)
                awayTeamAbbr = game['away_name']
                if (awayTeamAbbr == "American League All-Stars"
                        or awayTeamAbbr == "National League All-Stars"):
                    awayTeamAbbr = "New York Mets"
                awayTeamAbbr = convertName(awayTeamAbbr)
                time = game['game_datetime']

                scheduledTime = time[time.find('T') + 1:time.find('Z')]
                splitTime = scheduledTime.split(":")
                hours = int(splitTime[0])
                hours = hours - 4
                if (hours < 0):
                    hours = hours + 12
                minutes = splitTime[1]
                setting = "PM"
                if hours > 12:
                    hours -= 12

                monthName = convertMonth(month)
                gameTime = str(hours) + ":" + minutes + setting
                homeActualScore = game['home_score']
                awayActualScore = game['away_score']

                actualHomeWin = 0
                if (homeActualScore > awayActualScore):
                    actualHomeWin = 1

                actualAwayWin = 1 - actualHomeWin

                insertVariblesIntoTable(game_id, homeTeamAbbr, awayTeamAbbr,
                                        game['game_date'], gameTime,
                                        homeActualScore, awayActualScore,
                                        actualHomeWin, actualAwayWin)
                #schedule.loc[x] = [homeTeam,awayTeam,monthName+" "+str(day)+" @ "+str(hours)+":"+minutes+setting]
                x = x + 1

            #schedule.to_csv('games_'+str(month)+'_'+str(day)+'_'+str(year)+'.csv', index=False)
            x = 1
Exemplo n.º 11
0
def get_game_id(team_id: int, game_date: datetime) -> int:
    game_date = game_date.strftime("%Y-%m-%d")
    try:
        game_id = statsapi.schedule(date=game_date, team=team_id,
                                    sportId=1)[0].get("game_id")
    except IndexError:
        game_id = None
    return game_id
Exemplo n.º 12
0
def getGame():
    sched = statsapi.schedule(start_date='07/01/2018',
                              end_date='07/31/2018',
                              team=143,
                              opponent=121)
    gameId = sched[0]["game_id"]
    scoredata = statsapi.boxscore_data(gameId)
    return scoredata
Exemplo n.º 13
0
def generateGamePksFromDates(startDate, endDate):
    sched = statsapi.schedule(
        start_date=startDate,
        end_date=endDate)  #call to the mlb website to scrape the raw data
    gamePks = [
        x['game_id'] for x in sched
    ]  #list comp to pull the gamePk from each game scraped (come through in JSON format)
    return gamePks
Exemplo n.º 14
0
def hitting_everything2020():
    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=2)
    tomorrow = today + datetime.timedelta(days=1)
    team = 137
    info = statsapi.get('team', {'teamId': team})
    name = info['teams'][0]['name']
    abbrev = info['teams'][0]['abbreviation']
    sched = statsapi.schedule(start_date='07/23/2020',
                              end_date='9/27/2020',
                              team=team)
    for i in range(len(sched)):
        gameId = sched[i]["game_id"]
        scoredata = statsapi.boxscore_data(gameId)
        game_date = sched[i]["game_date"]
        if sched[i]['doubleheader'] == 'Y':
            game_date = sched[i]["game_date"] + "(" + str(
                sched[i]["game_num"]) + ")"
        if path.exists("Teams/" + abbrev + "/2020/h_dates.txt"):
            with open("Teams/" + abbrev + "/2020/h_dates.txt", "r") as FILE:
                content = FILE.read()
                try:
                    content_dict = eval(content)
                except Exception as e:
                    print("we got an error ", e)
                    print("Database Error ")
        else:
            with open("Teams/" + abbrev + "/2020/h_dates.txt", "w") as FILE:
                FILE.write("{'dates':[]}")
            with open("Teams/" + abbrev + "/2020/h_dates.txt", "r") as FILE:
                content = FILE.read()
                try:
                    content_dict = eval(content)
                except Exception as e:
                    print("we got an error ", e)
                    print("Database Error ")
        if game_date not in content_dict['dates'] and (
                sched[i]['status'] == "Final"
                or sched[i]['status'] == "Game Over"):
            if sched[i]["game_type"] == "R":
                for ID in scoredata['playerInfo']:
                    if sched[i]['home_name'] == name:
                        if ID in scoredata['home']['players']:
                            if scoredata['home']['players'][ID]['stats'][
                                    'batting'] != {}:
                                h_add(game_date, scoredata, ID, abbrev)
                    else:
                        if ID in scoredata['away']['players']:
                            if scoredata['away']['players'][ID]['stats'][
                                    'batting'] != {}:
                                a_add(game_date, scoredata, ID, abbrev)
                with open("Teams/" + abbrev + "/2020/h_dates.txt", "w") as f:
                    try:
                        content_dict['dates'].append(game_date)
                        f.write(str(content_dict))
                    except Exception as e:
                        print("we got an error ", e)
                        print("Database Error ")
Exemplo n.º 15
0
def team_schedule():
    """ Use MLB Stats API to extract daily MLB Team Schedules for use in Game Watchability Index calculation

    Returns:
        {Date: {H1: Team_Name, A1: Team_Name, ..., H8: Team_Name, A8: Team_Name}}
    """
    # Retrieve schedule of today's games
    today = datetime.datetime.today().strftime('%Y-%m-%d')
    schedule = statsapi.schedule(today)

    # Team Codes:
    # 108	LAA	Angels
    # 109	ARI	D-backs
    # 110	BAL	Orioles
    # 111	BOS Red Sox
    # 112	CHC Cubs
    # 113	CIN	Reds
    # 114	CLE	Indians
    # 115	COL	Rockies
    # 116	DET	Tigers
    # 117	HOU Astros
    # 118	KC	Royals
    # 119	LAD	Dodgers
    # 120	WSH Nationals
    # 121	NYM Mets
    # 133	OAK Athletics
    # 134	PIT	Pirates
    # 135	SD	Padres
    # 136	SEA	Mariners
    # 137	SF	Giants
    # 138	STL	Cardinals
    # 139	TB	Rays
    # 140	TEX	Rangers
    # 141	TOR	Blue Jays
    # 142	MIN Twins
    # 143	PHI	Phillies
    # 144	ATL	Braves
    # 145	CWS White Sox
    # 146	MIA	Marlins
    # 147	NYY	Yankees
    # 158	MIL	Brewers

    # Convert Team Codes into Abbreviations and use as new dictionary values
    daily_schedule = {}
    for team in range(len(schedule)):
        home_team = statsapi.lookup_team(
            schedule[team]['home_id'])[0]['fileCode'].upper()
        away_team = statsapi.lookup_team(
            schedule[team]['away_id'])[0]['fileCode'].upper()
        daily_schedule.update({
            'H' + str(team): home_team,
            'A' + str(team): away_team
        })

    # Append previous dictionary to main dictionary
    team_schedules = {today: daily_schedule}

    return team_schedules
def collect_game_data(start_date, end_date):
    '''Calls StatsApi to collect game IDs for games played during defined period'''
    schedule = statsapi.schedule(start_date=start_date, end_date=end_date)
    full = json_normalize(schedule)
    gamepks = full['game_id']
    '''Iterates through play-by-play data, normalizes nested .json, and adds data back to columns defined below.'''
    list_for_final_df = []
    for game in gamepks:
        curr_game = statsapi.get('game_playByPlay', {'gamePk': game})
        curr_plays = curr_game.get('allPlays')
        curr_plays_df = pd.DataFrame(curr_plays)
        curr_plays_norm = json_normalize(curr_plays)

        all_plays_cols = [
            'about.atBatIndex', 'about.halfInning', 'about.inning',
            'count.balls', 'count.strikes', 'matchup.batSide.code',
            'matchup.batter.fullName', 'matchup.batter.id',
            'matchup.pitchHand.code', 'matchup.splits.menOnBase',
            'matchup.pitcher.fullName', 'matchup.pitcher.id',
            'result.eventType'
        ]

        play_events_cols = [
            'count.balls', 'count.strikes', 'details.ballColor',
            'details.call.code', 'details.call.description',
            'details.type.description', 'details.call.code',
            'details.description', 'details.code', 'details.type.code',
            'index', 'pitchData.nastyFactor', 'pitchData.zone', 'pitchNumber',
            'type'
        ]
        i = 1
        for index, row in curr_plays_norm.iterrows():
            play_events = json_normalize(row['playEvents'])

            for play_events_idx, play_events_row in play_events.iterrows():

                game_dict = {}
                game_dict['gamepk'] = game
                game_dict['pitch_id'] = str(game) + '_' + str(
                    row['about.atBatIndex']) + '_' + str(i)
                game_dict['prior_pitch'] = str(game) + '_' + (
                    str(row['about.atBatIndex']) + '_' + str(i - 1))

                for col_all_plays in all_plays_cols:
                    if col_all_plays in curr_plays_norm.columns:
                        game_dict[col_all_plays] = row[col_all_plays]
                    else:
                        game_dict[col_all_plays] = np.nan
                for col_play_events in play_events_cols:
                    if col_play_events in play_events.columns:
                        game_dict[col_play_events] = play_events_row[
                            col_play_events]
                    else:
                        game_dict[col_play_events] = np.nan

                list_for_final_df.append(game_dict)
                i += 1
    return pd.DataFrame(list_for_final_df)
Exemplo n.º 17
0
    def handle(self, *args, **options):

        sched = statsapi.schedule(start_date='01/01/2020',
                                  end_date='12/31/2020')

        for game in sched:

            try:
                game_id = game['game_id']
                home_team = Team.objects.get(team_id=game['home_id'])
                away_team = Team.objects.get(team_id=game['away_id'])
                # print("teams gotten")
                home_score = game['home_score']
                away_score = game['away_score']
                current_inning = game['current_inning']
                if (('Final' in game['status'])
                        or ('Completed' in game['status'])):
                    finished = True
                else:
                    finished = False
                if not (away_score):
                    away_score = 0
                if not (home_score):
                    home_score = 0
                if not (current_inning):
                    current_inning = " "
                game_datetime = game['game_datetime']

                try:
                    db_game = Game.objects.get(game_id=game_id)

                    # if not(finished):
                    db_game.home_team = home_team
                    db_game.away_team = away_team
                    db_game.home_score = home_score
                    db_game.away_score = away_score
                    db_game.current_inning = current_inning
                    db_game.save(update_fields=[
                        'home_team', 'away_team', 'home_score', 'away_score',
                        'current_inning'
                    ])
                    print("updated successfully")
                except:
                    db_game = Game(game_id=game_id,
                                   home_team=home_team,
                                   away_team=away_team,
                                   home_score=home_score,
                                   away_score=away_score,
                                   current_inning=current_inning,
                                   finished=finished,
                                   game_datetime=game_datetime)
                    db_game.save()
                    print("saved succesfully")

            # Error or team not in db
            except Team.DoesNotExist:
                print("team not in db")
                pass
Exemplo n.º 18
0
def get_game(gid=None):
    try:
        date_str = statsapi.schedule(game_id=gid)[0]['game_date']
        date = datetime.date.fromisoformat(date_str)
        games = lookup_games(date)
        return render_template('index.html',
                               date=f'{date.year}-{date.month}-{date.day}',
                               games=games, current_game=gid)
    except (ValueError, urllib.error.HTTPError):
        return abort(404)
Exemplo n.º 19
0
def pbp():
    sched = statsapi.schedule(start_date='09/01/2019', team=137)
    gameId = sched[0]["game_id"]
    game_date = sched[0]["game_date"]
    game_result = sched[0]["summary"]
    test = []
    play = statsapi.get('game_playByPlay', {'gamePk': gameId})
    for i in range(len(play['allPlays'])):
        test.append(play['allPlays'][i]['result']['description'])
    return play['allPlays'][8]
Exemplo n.º 20
0
def get_gamePks(seasons):
    """
    uses the 'season' endpoint of the mlb api to get gamePks and write them to csvs for each season.
    """
    import statsapi as mlb
    import csv
    import time
    import sys

    gamePks_path = "/Users/schlinkertc/code/mlb_predictions/gamePks"

    from os import walk
    import re

    # walk the gamePks directory to find the seasons that we've already added
    f = []
    for (dirpath, dirnames, filenames) in walk(gamePks_path):
        f.extend(filenames)
        break
    years = [re.findall('[^.csv]+', x) for x in f]
    already_added = [
        int(item) for sublist in years for item in sublist
        if item[0] in ['1', '2']
    ]

    seasons = list(set(seasons) - set(already_added))

    gamePks = {}
    for season in seasons:
        mlb.get('season', {'sportId': 1, 'seasonId': str(season)})
        try:
            games = mlb.schedule(start_date=f'02/01/{season}',
                                 end_date=f'11/30/{season}',
                                 sportId=1)
            pks = [x['game_id'] for x in games]
            print(pks[0])

            gamePks[season] = pks
            print(len(gamePks))
            with open(gamePks_path + f'/{season}.csv', 'w',
                      newline='') as myfile:
                wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
                wr.writerow(gamePks[season])
        except ValueError as err:
            print(
                f'{season} failed. Error: {err} Waiting 10 seconds before resuming'
            )
            time.sleep(10)
            #seasons.append(season)
        except:
            print("Unexpected error:", sys.exc_info()[0])
            raise

    return gamePks
Exemplo n.º 21
0
def mlb_data_current(preferred_team):
    now = datetime.datetime.now()
    game_data_set = {}

    # Read scoreboard options from config.json if it exists
    #config = get_config("config")

    #teamData = statsapi.lookup_team(config['preferred']['teams'][0])
    for team in statsapi.lookup_team(preferred_team):

        now = datetime.datetime.now().strftime('%m/%d/%Y')
        todays_gameData = statsapi.schedule(
            date=datetime.datetime.now().strftime('%m/%d/%Y'),
            start_date=None,
            end_date=None,
            team=team['id'],
            opponent="",
            sportId=1,
            game_id=None)
        #todays_boxscore = statsapi.boxscore_data(todays_gameData[0]['game_id'], timecode=None)
        if len(todays_gameData) > 0:
            response = requests.get('https://statsapi.mlb.com/api/v1.1/game/' +
                                    str(todays_gameData[0]['game_id']) +
                                    '/feed/live')
            mlb_game_json_data = response.json(
            ) if response and response.status_code == 200 else None

            game_data_set['home_id'] = todays_gameData[0]['home_id']
            game_data_set['away_id'] = todays_gameData[0]['away_id']
            game_data_set['status'] = todays_gameData[0]['status']
            game_data_set['home_score'] = todays_gameData[0]['home_score']
            #game_data_set['home_hits'] = todays_boxscore['home']['teamStats']['batting']['hits'] #use live game data
            game_data_set['home_hits'] = mlb_game_json_data['liveData'][
                'boxscore']['teams']['home']['teamStats']['batting']['hits']
            game_data_set['away_score'] = todays_gameData[0]['away_score']
            #game_data_set['away_hits'] = todays_boxscore['away']['teamStats']['batting']['hits'] #use live game data
            game_data_set['away_hits'] = mlb_game_json_data['liveData'][
                'boxscore']['teams']['away']['teamStats']['batting']['hits']
            game_data_set['current_inning'] = todays_gameData[0][
                'current_inning']
            game_data_set['inning_state'] = todays_gameData[0]['inning_state']
            game_data_set['game_datetime'] = mlb_game_json_data['gameData'][
                'datetime']['time'] + ' ' + mlb_game_json_data['gameData'][
                    'datetime']['ampm']

            if game_data_set['status'] != "Scheduled" or game_data_set[
                    'status'] != "Pre-Game":
                game_data_set['outs_count'] = mlb_game_json_data['liveData'][
                    'linescore']['outs']

            break

    return game_data_set
Exemplo n.º 22
0
def get_games(start_year, end_year):
    years = range(start_year, end_year + 1)
    games = []
    for y in years:
        try:
            games.append(
                mlb.schedule(start_date='{}-01-01'.format(y),
                             end_date='{}-12-29'.format(y),
                             sportId='1'))
        except:
            get_games(y, y)

    return [item for sublist in games for item in sublist]
Exemplo n.º 23
0
 def boxscores(self):
     schedule = statsapi.schedule(start_date=convert_date(self.date))
     gamePks = [s["game_id"] for s in schedule]
     for gamePk in gamePks:
         game_json = statsapi.boxscore_data(gamePk)
         player_teams = self._player_metadata(gamePk=gamePk)
         for p in ["Batters", "Pitchers"]:
             self._stack_results(
                 player_type=p,
                 game_json=game_json,
                 gamePk=gamePk,
                 player_teams=player_teams,
             )
Exemplo n.º 24
0
def getplayerid():

    lastname = input("Player Last Name: ")

    sched = statsapi.schedule(start_date='02/22/2020',
                              end_date='03/11/2020',
                              team=137)
    for i in range(len(sched)):
        gameId = sched[i]["game_id"]
        scoredata = statsapi.boxscore_data(gameId)
        length_b_home = len(scoredata['homeBatters'])
        length_b_away = len(scoredata['awayBatters'])
        length_p_home = len(scoredata['homePitchers'])
        length_p_away = len(scoredata['awayPitchers'])
        if sched[i]['home_name'] == 'San Francisco Giants':
            for i in range(1, length_p_home):
                pitcher_name = scoredata['homePitchers'][i]['name']
                player_id = 'ID' + str(
                    scoredata['homePitchers'][i]['personId'])
                fullname = scoredata['playerInfo'][player_id]['fullName']
                if lastname == pitcher_name:
                    print(str(pitcher_name), ": " + str(player_id))
                    to_txtp(fullname, player_id)
                    input()
            for i in range(1, length_b_home):
                batter_name = scoredata['homeBatters'][i]['name']
                player_id = 'ID' + str(scoredata['homeBatters'][i]['personId'])
                fullname = scoredata['playerInfo'][player_id]['fullName']
                if lastname == batter_name:
                    print(str(batter_name), ": " + str(player_id))
                    to_txtb(fullname, player_id)
                    input()
        else:
            for i in range(1, length_p_away):
                pitcher_name = scoredata['awayPitchers'][i]['name']
                player_id = 'ID' + str(
                    scoredata['awayPitchers'][i]['personId'])
                fullname = scoredata['playerInfo'][player_id]['fullName']
                if lastname == pitcher_name:
                    print(str(pitcher_name), ": " + str(player_id))
                    to_txtp(fullname, player_id)
                    input()
            for i in range(1, length_b_away):
                batter_name = scoredata['awayBatters'][i]['name']
                player_id = 'ID' + str(scoredata['awayBatters'][i]['personId'])
                fullname = scoredata['playerInfo'][player_id]['fullName']
                if lastname == batter_name:
                    print(str(batter_name), ": " + str(player_id))
                    to_txtb(fullname, player_id)
                    input()
Exemplo n.º 25
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        year = datetime.datetime.now().year
        month = datetime.datetime.now().month
        day = datetime.datetime.now().day
        today = datetime.datetime.now()

        game_thread, created = GameThread.objects.get_or_create(date=today)
        game_thread.value = self.request.POST.get(today)
        game_thread.save()
        context['next_game'] = statsapi.schedule(date=str(year) + "-" +
                                                 str(month) + "-" + str(day),
                                                 team=135)
        return context
Exemplo n.º 26
0
def getDailyMetsGameDetails():
    try:
        gameDetails = statsapi.schedule(date=None, start_date=datetime.today().strftime('%Y-%m-%d'), end_date=None, team=metsId, opponent="", sportId=1, game_id=None)[0]
    except IndexError as e:
        return "There's no Mets game today."

    metsAreHome = True if gameDetails['home_name'] == "New York Mets" else False

    opposingTeam = gameDetails['away_name'] if metsAreHome else gameDetails['home_name']
    # Get start time
    startTime = getStartTime(gameDetails['game_datetime'])

    # Mets starting pitcher
    metsStartingPitcher = gameDetails['home_probable_pitcher'] if (metsAreHome) else gameDetails['away_probable_pitcher']

    return f"\nStart time is {startTime}. The Mets are playing the {opposingTeam}. Today's pitcher is {metsStartingPitcher}."
Exemplo n.º 27
0
    def getPlayerStats(self):
        date = self.data.lastDateChecked
        self.data.lastDateChecked = datetime.date.today().strftime('%m/%d/%Y')
        if (self.data.endDate and datetime.datetime.strptime(date, '%m/%d/%Y')
                > datetime.datetime.strptime(self.data.endDate, '%m/%d/%Y')):
            date = self.data.endDate

        games = statsapi.schedule(start_date=date,
                                  end_date=self.data.lastDateChecked)
        gameIdsToGet = set(self.data.ongoingGames)
        # clear now, repop later
        self.data.ongoingGames = set()
        for game in games:
            if game['status'] not in ('Cancelled', 'Final'):
                self.data.ongoingGames.add(game['game_id'])
            gameIdsToGet.add(game['game_id'])
        for gameId in gameIdsToGet:
            self._getPlayerStatsForGame(gameId)

        self.saveData()
Exemplo n.º 28
0
def handle_message(event, get_name):
    print(get_name)
    try:
        team_name = TEAM_MAP[get_name]
    except:
        error_message = TextSendMessage(text=f"{get_name} is not found")
        line_bot_api.reply_message(
            event.reply_token,
            error_message,
        )
        return
    games = statsapi.schedule(date="09/15/2020")
    #print(games)
    for game in games:
        message = TextSendMessage(text=game['summary'])
        line_bot_api.reply_message(
            event.reply_token,
            message,
        )
    return
Exemplo n.º 29
0
def main():
    #0 - No State
    #1 - Before Game
    #2 - During Game
    #3 - After Game
    gameState = 0
    inningState = -1
    homeRun = False
    states = [gameState, inningState, homeRun]
    teamName = input("Enter the team you would like to listen to: ")

    TeamData = sa.lookup_team(teamName)

    teamID = TeamData[0]['id']

    printed = False

    os.system('cls' if os.name == 'nt' else 'clear')

    while 1:
        oldScoring = []
        schedule = sa.schedule(datetime.date.today(), team=teamID)
        try:
            game = schedule[0]
        except:
            if not printed:
                print(
                    "The " + teamName +
                    " do not have a game today, their next game will be against the "
                    + FSM.getGameInfo(teamID)[0] + " on " +
                    FSM.getGameInfo(teamID)[1])
                printed = True
            continue

        #try:
        states = FSM.stateMachine(FSM, game, states[0], states[1], teamName,
                                  oldScoring, teamID, states[2])
        #except:
        #	continue

        time.sleep(120)
def game_info(gameid):
    statsapi.schedule(game_id=gameid)
    get_wrong_game_time = dateutil.parser.parse(
        statsapi.schedule(
            game_id=gameid)[0]['game_datetime'])  # change datetime format
    # statsapi's time is 7 hours later, so I used timedelta
    adjust_game_time = get_wrong_game_time - timedelta(hours=7)
    game_time = adjust_game_time.strftime('%H:%M:%S')

    game_date = statsapi.schedule(game_id=gameid)[0]['game_date']
    home_team = statsapi.schedule(game_id=gameid)[0]['home_name']
    away_team = statsapi.schedule(game_id=gameid)[0]['away_name']
    home_probable_pitcher = statsapi.schedule(
        game_id=gameid)[0]['home_probable_pitcher']
    away_probable_pitcher = statsapi.schedule(
        game_id=gameid)[0]['away_probable_pitcher']

    game_time_string = 'Next game will be at {} on {}'
    home_team_string = 'Home team, Probable Pitcher: {} // {}'
    away_team_string = 'Away team, Probable Pitcher: {} // {}'
    print(game_time_string.format(game_time, game_date))
    print(home_team_string.format(home_team, home_probable_pitcher))
    print(away_team_string.format(away_team, away_probable_pitcher))