def print_team_schedule(team, num, forward=True): """print next/previous <num> days for a team""" teamid = mymlbstats.get_teamid(team) if teamid is None: return "Could not find team" today = mymlbstats._get_date_from_delta("+0") plus = "+" if forward else "-" date2 = mymlbstats._get_date_from_delta(plus + str(int(num) + 3)) if forward: dates = get_schedule(today, endDate=date2, teamid=teamid) else: dates = get_schedule(date2, endDate=today, teamid=teamid) output = "" games = list() for date in dates: for game in date['games']: if 'status' in game: code = game['status']['abstractGameCode'] if forward and code in ['F']: continue elif forward and code == 'L' and game['status']['codedGameState'] != 'U': # suspended continue elif not forward and code in ['L', 'P']: continue games.append(game) if forward: games = games[:num] else: games = games[-num:] for game in games: date = game['officialDate'][:10] dt = datetime.strptime(date, "%Y-%m-%d") if today.day-dt.day == 0: day = "Today" elif not forward: if today.day-dt.day == 1: day = "Yesterday" else: day = calendar.day_name[dt.weekday()] else: if dt.day-today.day == 1: day = "Tomorrow" else: day = calendar.day_name[dt.weekday()] output = output + date + " (%s):\n" % (day) output += mymlbstats.get_single_game_info(game['gamePk'], gamejson=game) + "\n" if len(output) == 0: return "no games found" else: return output
def find_gamepks(team, delta=None, teamid=None): if teamid is None: teamid = mymlbstats.get_teamid(team) s = mymlbstats.get_day_schedule(delta=delta, teamid=teamid) gamepks = [] games = s['dates'][0]['games'] for game in games: gamepks.append(game['gamePk']) return gamepks
def print_stat_leaders(statquery_list, season=None): league = None if 'al' in statquery_list: league = 'al' statquery_list.remove('al') elif 'nl' in statquery_list: league = 'nl' statquery_list.remove('nl') want_group = None groups = ['hitting', 'pitching', 'fielding', 'catching'] for i in statquery_list: if i in groups: want_group = i statquery_list.remove(i) break positions = ['c','1b','2b','3b','ss','lf','cf','rf','of','p','dh'] pos = None for i in statquery_list: if i.lower() in positions: pos = i.upper() statquery_list.remove(i) stat = statquery_list.pop() team = None if len(statquery_list) > 0: team = mymlbstats.get_teamid(' '.join(statquery_list)) print(stat) leaders = get_stat_leaders(stat, season=season, league=league, position=pos, teamid=team) if leaders is None: return "Stat not found" group = None for statgroup in leaders: if statgroup['statGroup'] == want_group or want_group is None: group = (statgroup['statGroup'], list()) for leader in statgroup['leaders'][:10]: player = dict() player['team'] = leader['team']['abbreviation'] player['name'] = leader['person']['fullName'] player[stat] = leader['value'] group[1].append(player) break if group is not None: output = "" output += "%s:\n```python\n" % group[0] labels = ['team', 'name', 'gamesPlayed', stat] left = ['team', 'name'] output += utils.format_table(labels, group[1], left_list=left) output += "```\n" return output else: return "problem finding leaders"
def print_player_or_team(query, delta=None): teamid = mymlbstats.get_teamid(query) if teamid is None: p = mymlbstats._get_player_search(query) if p is None: return "Query did not match team or player" teamid = int(p['team_id']) return get_player( get_game(find_gamepks(None, teamid=teamid, delta=delta)[0]), int(p['player_id'])) else: return get_five( get_game(find_gamepks(None, teamid=teamid, delta=delta)[0]))
async def milb(self, ctx): """Get info on minor leagues !milb [team] [date or delta] - print scoreboard for [team] affiliates, defaults to Nats date/delta optional - date is MM/DD/[YY]YY format, delta is +days or -days """ if ctx.invoked_subcommand is None: args = ctx.message.system_content[6:].split(' ') delta, args = self._find_delta(args) if args[0] == '': await self.bot.say("```python\n%s```" % mymlbstats.get_milb_aff_scores(delta=delta)) else: teamid = mymlbstats.get_teamid(' '.join(args)) if teamid is None: await self.bot.say('Invalid subcommand passed') else: await self.bot.say("```python\n%s```" % mymlbstats.get_milb_aff_scores(teamid=teamid, delta=delta))
def print_birthdays(team, delta=None, reddit=False): birthdays = list() if delta is None: today = datetime.today() todayyear = 2021 # use this until it's actually updated to 2021 i guess else: today = mymlbstats._get_date_from_delta(delta, offset=False) todaystr = "%02d-%02d" % (today.month, today.day) if len(team) == 0: url = API_LINK + "sports/1/players?fields=id,people,person,firstLastName,birthDate,currentTeam&season=%d" % todayyear players = utils.get_json(url)['people'] teams = dict() for player in players: if 'birthDate' in player: p = dict() if player['birthDate'][5:] == todaystr: p['age'] = today.year - int(player['birthDate'][:4]) p['name'] = player['firstLastName'] curteamid = player['currentTeam']['id'] if curteamid in teams: p['team'] = teams[curteamid]['abbreviation'] if reddit: p['team'] = "[](/%s)%s" % (p['team'], p['team']) else: teaminfo = get_team_info(curteamid) teams[curteamid] = teaminfo p['team'] = teaminfo['abbreviation'] if reddit: p['team'] = "[](/%s)%s" % (p['team'], p['team']) birthdays.append(p) else: teamid, teamdata = mymlbstats.get_teamid(team, extradata=True) if teamid is None: return "could not find team" roster = get_40man(teamid) + get_coaches(teamid) for player in roster: if 'birthDate' in player['person']: p = dict() player = player['person'] if player['birthDate'][5:] == todaystr: p['age'] = today.year - int(player['birthDate'][:4]) p['name'] = player['firstLastName'] birthdays.append(p) if delta is None: todaystr = "today" else: todaystr = 'on ' + todaystr.replace('-','/') if len(birthdays) > 0: if len(team) > 0: return "%s birthdays %s:\n\n" % (teamdata['teamName'], todaystr) + utils.format_table(['name', 'age'], birthdays, left_list=['name'], reddit=reddit) else: return "All player birthdays %s:\n\n%s" % (todaystr, utils.format_table(['team','name','age'], birthdays, left_list=['team','name'], reddit=reddit)) # return "All player birthdays %s:\n\n%s" % (todaystr, utils.format_table(['name','age'], birthdays, left_list=['name'], reddit=reddit)) else: if len(team) > 0: return "No %s birthdays on %s" % (teamdata['teamName'], todaystr) else: return "No birthdays %s" % todaystr
def _get_stats_query_params(statquery_list, delta=None): date1, date2 = None, None if delta is not None: date1 = mymlbstats._get_date_from_delta(delta) date2 = date1 stattype = "season" if 'today' in statquery_list: stattype = 'byDateRange' statquery_list.remove('today') if 'date' in statquery_list or 'dates' in statquery_list: stattype = 'byDateRange' if 'date' in statquery_list: statquery_list.remove('date') elif 'dates' in statquery_list: statquery_list.remove('dates') dates = 0 for item in statquery_list: if '-' in item: sp = item.split('-') if '/' in sp[0] and '/' in sp[1]: date1, date2 = sp[0], sp[1] statquery_list.remove(item) break elif len(item.split('/')) == 2 or len(item.split('/')) == 3: if dates == 0: date1 = item dates += 1 elif dates == 1: date2 = item statquery_list.remove(date1) statquery_list.remove(date2) break pool = None if "all" in statquery_list: pool = "all" statquery_list.remove('all') elif "rookies" in statquery_list: pool = "qualified_rookies" statquery_list.remove('rookies') elif "qualified" in statquery_list: pool = "qualified" statquery_list.remove('qualified') league = None if 'al' in statquery_list: league = 'al' statquery_list.remove('al') elif 'nl' in statquery_list: league = 'nl' statquery_list.remove('nl') want_group = None groups = ['hitting', 'pitching', 'fielding', 'catching'] for i in statquery_list: if i in groups: want_group = i statquery_list.remove(i) break positions = ['c','1b','2b','3b','ss','if','lf','cf','rf','of','p','dh'] pos = None for i in statquery_list: if i.lower() in positions: pos = i.upper() statquery_list.remove(i) stat = statquery_list.pop() team = None if len(statquery_list) > 0: team = mymlbstats.get_teamid(' '.join(statquery_list)) return (league, want_group, pos, team, stat, stattype, date1, date2, pool)
def print_player_stats(name, group=None, stattype=None, startDate=None, endDate=None, lastgames=None, reddit=False): if stattype is not None: if startDate is not None and endDate is None: endDate = mymlbstats._timedelta_to_mlb(datetime.today()) roster = None team = None players = list() if '/' not in name: teamid, team = mymlbstats.get_teamid(name, extradata=True) if teamid is not None: roster = mymlbstats.get_team_info(teamid)['roster'] if group is None: group = 'hitting' for player in roster: if group == 'hitting' and player['person']['primaryPosition']['code'] != '1': p = get_player_stats("", playerid=player['person']['id'], group=group, stattype=stattype, startDate=startDate, endDate=endDate, lastgames=lastgames) if 'stats' in p: if len(p['stats'][0]['splits']) == 0: d = {'stat':{'plateAppearances':0}} p['stats'][0]['splits'].append(d) players.append(p) elif group == 'pitching' and player['person']['primaryPosition']['code'] == '1': p = get_player_stats("", playerid=player['person']['id'], group=group, stattype=stattype, startDate=startDate, endDate=endDate, lastgames=lastgames) if 'stats' in p and len(p['stats'][0]['splits']) > 0: if 'inningsPitched' not in p['stats'][0]['splits'][0]['stat']: p['stats'][0]['splits'][0]['stat']['inningsPitched'] = 0 players.append(p) if group == 'hitting': players = sorted(players, key = lambda k: k['stats'][0]['splits'][0]['stat']['plateAppearances'], reverse=True) elif group == 'pitching': players = sorted(players, key = lambda k: k['stats'][0]['splits'][0]['stat']['inningsPitched'], reverse=True) if roster is None: names = name.split('/') for name in names: player = get_player_stats(name, group=group, stattype=stattype, startDate=startDate, endDate=endDate, lastgames=lastgames) if player != "Couldn't find player": players.append(player) else: return player statsstr = _get_multiple_stats_string(players, group=group, include_gp=True, reddit=reddit) output = "" namesliststr = "" if roster is None: for player in players: namesliststr += "%s, " % player['fullName'] namesliststr = namesliststr[:-2] else: print(team) namesliststr = team['abbreviation'] if stattype == "byDateRange": print(startDate, endDate) output = "%s to %s for %s:\n\n" % (startDate, endDate, namesliststr) start = _convert_mlb_date_to_datetime(startDate) end = _convert_mlb_date_to_datetime(endDate) if len(players) > 1 and start.year != end.year: output += "These stats only show the first season in the date range. To get all seasons, search each player individually.\n\n" elif stattype == "lastXGames": output = "Last %s games for %s:\n\n" % (lastgames, namesliststr) output += statsstr return output
def print_games(args, delta=None): lgs = {'alwc':103,'nlwc':104} divs = {'nle':204,'nlc':205,'nlw':203,'ale':201,'alc':202,'alw':200} if isinstance(args, list): args = ' '.join(args) all_games = get_schedule(delta)[0]['games'] games = list() add_last_play = False if 'close' in args: for game in all_games: if game['status']['abstractGameCode'] == "L" : awayruns = game['linescore']['teams']['away']['runs'] homeruns = game['linescore']['teams']['home']['runs'] if game['linescore']['currentInning'] >= 7 and abs(awayruns-homeruns) <= 2: games.append(game) if len(games) == 0: return "No close (7th inning or later within 2 runs) games at the moment." elif 'live' in args: for game in all_games: if game['status']['abstractGameCode'] == "L": games.append(game) if len(games) == 0: return "No live games at the moment." elif args in lgs: standings = mymlbstats.get_lg_standings(lgs[args],wc=True)['records'][0]['teamRecords'] wcteams = [] for i in range(5): wcteams.append(standings[i]['team']['id']) for game in all_games: away = game['teams']['away']['team']['id'] home = game['teams']['home']['team']['id'] if away in wcteams or home in wcteams: games.append(game) elif args in divs: for game in all_games: awaydiv = game['teams']['away']['team']['division']['id'] homediv = game['teams']['home']['team']['division']['id'] if awaydiv == divs[args] or homediv == divs[args]: games.append(game) if len(games) == 0: return "No games for division found" elif len(args) > 0: add_last_play = True teamid = mymlbstats.get_teamid(args) if teamid is None: return "Could not find team", 0 else: for game in all_games: away = game['teams']['away']['team']['id'] home = game['teams']['home']['team']['id'] if away == teamid or home == teamid: games.append(game) if len(games) == 0: return "No games found for %s" % args, 0 # check doubleheader is_dh_live = False for game in games: if game['doubleHeader'] == "Y" and game['status']['abstractGameCode'] == 'L': is_dh_live = True if is_dh_live: for game in games: if game['doubleHeader'] == "Y" and game['status']['abstractGameCode'] != 'L': games.remove(game) output = "" show_on_deck = False if len(games) == 0: games = all_games elif len(games) == 1: show_on_deck = True for game in games: output += mymlbstats.get_single_game_info(game['gamePk'], gamejson=game, show_on_deck=show_on_deck) + "\n" if add_last_play: output += _add_last_play_info(game) return output, len(games)