def setPitcher(self, teamName, pitcher):
     res = statsapi.lookup_player(pitcher)
     if len(res) > 1:
         # WILL SMITH
         res = [
             r for r in res if r['primaryPosition']['abbreviation'] == 'P'
         ]
     self.teams[teamName].pitchers = {res[0]['id']: pitcher}
     self.saveTeams()
 def setPlayers(self, teamName, players):
     agg = OrderedDict({})
     for player in players:
         res = statsapi.lookup_player(player)
         if len(res) > 1:
             # WILL SMITH
             res = [
                 r for r in res
                 if r['primaryPosition']['abbreviation'] != 'P'
             ]
         agg[res[0]['id']] = res[0]['fullName']
     self.teams[teamName].posPlayers = agg
     self.saveTeams()
Exemple #3
0
def get_player_data(name, group="hitting", lookupyear=None):
    if lookupyear is not None:
        players = statsapi.lookup_player(name, season=lookupyear)
    else:
        for year in range(2020, 1900, -1):
            players = statsapi.lookup_player(name, season=year)
            if len(players) > 0:
                break
    if len(players) > 1:
        print("Results are not unique")
        return None
    elif len(players) == 0:
        print("No results")
        return None

    pid = players[0]["id"]
    data = statsapi.player_stat_data(pid, group, type="yearByYear")

    df = pd.DataFrame(buildyears(data))
    df = df.rename(columns=trans)

    return df
Exemple #4
0
def get_player_id_from_name(player_name: str, season=CURR_SEASON) -> int:
    """
    A function that gets the player ID for a name entered in any 
    format (Last, First; First Last; Last, etc.).
    
    Parameters 
    -----–-----------
    player_name: str
        The name of a player as a string (i.e. "Buster Posey")
    """
    try:
        return statsapi.lookup_player(player_name, season=season)[0]['id']
    except IndexError:
        return False
Exemple #5
0
def check_pos_player(player_name: str, season=CURR_SEASON) -> bool:
    """
    A function that returns a bool indicating whether or not the player
    is a position player (as opposed to a pitcher).
    
    Parameters 
    -----–-----------
    player_name: str
        The name of a player as a string (i.e. "Buster Posey")
    """
    try:
        return statsapi.lookup_player(player_name, season=season)[0]['primaryPosition']['abbreviation'] != "P"
    except IndexError:
        return False
Exemple #6
0
    def post(self, request, *args, **kwargs):
        search_text = request.POST.get('search_text')
        print('bananas')

        #change the graph data here
        labels = [search_text]
        default_items = [
            statsapi.lookup_player(search_text)[0]['primaryNumber']
        ]

        data = {
            "labels": labels,
            "default": default_items,
        }
        return Response(data)
def get_current_season_stats(player_name):
    """
    One of the main data retrieval functions. Returns a dictionary 
    mapping the names of different statistics to the values of those
    statistics. Only includes overall season statistics for the player
    passed in. 
    
    Parameters 
    -----–-----------
    player_name: str
        The name of a player as a string (i.e. "Buster Posey")
    """

    if not check_pos_player(player_name):
        raise ValueError("Player name entered is not a position player")

    player_id = get_player_id_from_name(player_name)
    stats_dict = OrderedDict({
        "Name":
        player_name,
        "ID":
        player_id,
        "Team":
        statsapi.lookup_player(player_id)[0]['currentTeam']['id']
    })

    # Look up the player's current season hitting stats
    get_player_stats = statsapi.player_stats(player_id, 'hitting')

    # Get the stats for the most recent season
    curr_season_stats = get_player_stats.split("Season Hitting")[-1]

    #Break up the stats into a list
    stats_list = curr_season_stats.split("\n")[1:-2]
    for stat in stats_list:
        stat_name = re.search("[A-Za-z]+", stat).group()

        # Temporary fix for a bug that appeared 8/20/2019.
        if stat_name == 'flyOuts':
            continue

        stat_val = re.search("[^:A-Za-z]+", stat).group()
        try:
            stats_dict[stat_name] = float(stat_val)
        except ValueError:
            stats_dict[stat_name] = 0.0
    return stats_dict
Exemple #8
0
    def post(self, request, *args, **kwargs):
        search_text = request.POST.get('search_text')
        print('bananas')

        #change the graph data here
        labels = [search_text]
        default_items = [
            statsapi.lookup_player(search_text)[0]['primaryNumber']
        ]

        print(default_items[0])
        data = {
            "labels": labels,
            "default": default_items,
        }
        # return Response(data,  template_name='sports/home.html')
        return render(request, 'sports/home.html', data)
Exemple #9
0
 def lookup_player(self, keyword):
     """Check statsapi.lookup_player() and if no results, try other MLB source.
     Stats API only returns active players.
     """
     players = statsapi.lookup_player(keyword)
     if len(players): return players[0]['id']
     else:
         r = requests.get(
             'http://lookup-service-prod.mlb.com/json/named.search_player_all.bam?sport_code=%27mlb%27&name_part=%27{}%25%27'
             .format(keyword))
         if r.status_code not in [200, 201]:
             print(
                 'Error looking up player from alternate MLB source. Status code: {}.'
                 .format(r.status_code))
             return ''
         else:
             return r.json()['search_player_all']['queryResults']['row'][
                 'player_id'] if r.json()['search_player_all'][
                     'queryResults']['totalSize'] == '1' else r.json(
                     )['search_player_all']['queryResults']['row'][0][
                         'player_id']
Exemple #10
0
def lambda_handler(event, context):
    player_name = event['queryStringParameters']['player_name']
    year = event['queryStringParameters']['year']
    stat_group = event['queryStringParameters']['stat_group']

    print('Started to retrieve player data for player {} in year {}'.format(player_name, year))
    updated_year = 'career' if ('~' == year) else 'yearByYear'
    formatted_stat_group = '[{0}]'.format(stat_group)
    last_year = datetime.now().year - 1 # Cant use current year until season starts

    person_id = statsapi.lookup_player(player_name, season=last_year)[0].get('id')
    player_data = statsapi.player_stat_data(person_id, group=formatted_stat_group, type=updated_year)

    if updated_year == 'yearByYear':
        filtered_year_list = [stat_year for stat_year in player_data.get('stats') if stat_year.get('season') == year]
        player_data['stats'] = filtered_year_list

    print('Successfully Returning player data for player {}'.format(player_name))
    return {
        'statusCode': 200,
        'body': json.dumps(player_data)
    }
Exemple #11
0
    def lookup_player(self, keyword):
        """Check statsapi.lookup_player() and if no results, try other MLB source.
        Stats API only returns active players.
        """
        players = statsapi.lookup_player(keyword)
        if len(players):
            return players[0]["id"]

        else:
            r = requests.get(
                "http://lookup-service-prod.mlb.com/json/named.search_player_all.bam?sport_code=%27mlb%27&name_part=%27{}%25%27"
                .format(keyword))
            if r.status_code not in [200, 201]:
                log.error(
                    "Error looking up player from alternate MLB source. Status code: {}."
                    .format(r.status_code))
                return ""
            else:
                return (
                    r.json()["search_player_all"]["queryResults"]["row"]
                    ["player_id"] if
                    r.json()["search_player_all"]["queryResults"]["totalSize"]
                    == "1" else r.json()["search_player_all"]["queryResults"]
                    ["row"][0]["player_id"])
Exemple #12
0
    if __name__ == '__main__':
        setup_logger('teams', 'c:/Temp', logging.DEBUG)
        team_dict = team_info()
        buffer = []
        for team_id in team_dict.keys():
            buffer.append(team_dict[team_id].summary_info())
        buffer.sort()
        for buf in buffer:
            print(buf)
        logging.info("normal termination")
        sys.exit(0)
    import statsapi
    from util_logger import setup_logger
    import logging
    from Team import Team
    import sys

    def team_info():
        # teams = statsapi.get('teams',{'sportIds':1,'activeStatus':'Yes','fields':'teams,name,id,division,league'})
        team_dict = {}
        teams = statsapi.get('teams', {'sportIds': 1, 'activeStatus': 'Yes'})
        for team in teams['teams']:
            team_dict[team['id']] = Team(team)

        return team_dict

    if __name__ == '__main__':
        setup_logger('teams', 'c:/Temp', logging.DEBUG)

    statsapi.lookup_player()
Exemple #13
0
    def run(self, bot=None):
        if not self.sub:
            log.error("No subreddit specified!")
            bot.STOP = True
            return

        self.dbc.execute(
            "SELECT comment_id, date, reply, errors, removed FROM {} ORDER BY date DESC LIMIT 500;"
            .format(self.dbTable))
        comment_ids = self.dbc.fetchall()
        for cid in comment_ids:
            self.comments.update({
                cid[0]: {
                    "date": cid[1],
                    "reply": self.r.comment(cid[2]) if cid[2] else None,
                    "errors": cid[3],
                    "removed": cid[4],
                    "historical": True,
                }
            })

        log.debug("Loaded {} comments from db.".format(len(self.comments)))
        log.info(
            "Monitoring comments in the following subreddit(s): {}...".format(
                self.sub))
        while True:
            if bot and bot.STOP:
                log.info("Received stop signal...")
                return

            try:
                for comment in self.r.subreddit(
                        self.sub).stream.comments(pause_after=self.pauseAfter):
                    if bot and bot.STOP:
                        log.info("Received stop signal...")
                        return

                    if not comment:
                        break  # Take a break to delete downvoted replies

                    replyText = ""
                    if (str(self.r.user.me()).lower() in comment.body.lower()
                            and comment.author != self.r.user.me()):
                        if comment.id in self.comments.keys():
                            log.debug("Already processed comment {}".format(
                                comment.id))
                            continue
                        elif (
                                comment.created_utc <= time.time() -
                                60 * 60 * 24 * self.historicalDays - 3600
                        ):  # Add 1 hour buffer to ensure recent comments are processed
                            log.debug(
                                "Stream returned comment {} which is older than the HISTORICAL_DAYS setting ({}), ignoring..."
                                .format(comment.id, self.historicalDays))
                            self.comments.update({
                                comment.id: {
                                    "sub": comment.subreddit,
                                    "author": comment.author,
                                    "post": comment.submission,
                                    "date": time.time(),
                                    "cmd": [],
                                    "errors": [],
                                }
                            })
                            continue

                        self.comments.update({
                            comment.id: {
                                "sub": comment.subreddit,
                                "author": comment.author,
                                "post": comment.submission,
                                "date": time.time(),
                                "cmd": [],
                                "errors": [],
                            }
                        })
                        self.dbc.execute(
                            "insert or ignore into {} (comment_id, sub, author, post, date) values (?, ?, ?, ?, ?);"
                            .format(self.dbTable),
                            (
                                str(comment.id),
                                str(comment.subreddit),
                                str(comment.author),
                                str(comment.submission),
                                str(comment.created_utc),
                            ),
                        )
                        log.debug("({}) {} - {}: {}".format(
                            comment.subreddit,
                            comment.id,
                            comment.author,
                            comment.body,
                        ))
                        if "help" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append("help")
                            replyText += "I am a bot that can provide MLB data, but I am not affiliated with MLB or any team.\n\n"
                            replyText += "Invoke me by including my name anywhere in your comment.\n\n"
                            replyText += "Include an available command in your comment: [help, score, careerstats, lastgame, nextgame, seasonstats, standings, winprob, rundiff], "
                            replyText += "along with the subject in curly brackets.\n\n"
                            replyText += "For stats commands, you can also include the type: [hitting, pitching, fielding].\n\n"
                            replyText += "For example, `careerstats {hamels} pitching` or `score {phillies}` or `standings {nle}` "
                            replyText += "(try including the word wildcard when asking for standings).\n\n"
                            replyText += (
                                "I am currently monitoring the following subreddit(s): "
                                + self.sub.replace("+", ", ") + ".")

                        if "seasonstats" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append(
                                "seasonstats")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                who = statsapi.lookup_player(
                                    comment.body[comment.body.find("{") +
                                                 1:comment.body.find("}")]
                                )[0]["id"]
                                what = []
                                if ("hitting" in comment.body.lower()
                                        or "batting" in comment.body.lower()):
                                    what.append("hitting")

                                if "pitching" in comment.body.lower():
                                    what.append("pitching")

                                if "fielding" in comment.body.lower():
                                    what.append("fielding")

                                if len(what):
                                    stats = statsapi.player_stats(
                                        who,
                                        str(what).replace("'",
                                                          "").replace(" ", ""),
                                        "season",
                                    )
                                else:
                                    stats = statsapi.player_stats(
                                        who, type="season")

                                replyText += "\n    " + stats.replace(
                                    "\n", "\n    ")
                            except Exception as e:
                                log.error(
                                    "Error generating response for seasonstats: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for seasonstats: {}"
                                    .format(e))

                        if "careerstats" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append(
                                "careerstats")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                who = self.lookup_player(
                                    comment.body[comment.body.find("{") +
                                                 1:comment.body.find("}")])
                                what = []
                                if ("hitting" in comment.body.lower()
                                        or "batting" in comment.body.lower()):
                                    what.append("hitting")

                                if "pitching" in comment.body.lower():
                                    what.append("pitching")

                                if "fielding" in comment.body.lower():
                                    what.append("fielding")

                                if len(what):
                                    stats = statsapi.player_stats(
                                        who,
                                        str(what).replace("'",
                                                          "").replace(" ", ""),
                                        "career",
                                    )
                                else:
                                    stats = statsapi.player_stats(
                                        who, type="career")

                                replyText += "\n    " + stats.replace(
                                    "\n", "\n    ")
                            except Exception as e:
                                log.error(
                                    "Error generating response for careerstats: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for careerstats: {}"
                                    .format(e))

                        if "nextgame" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append("nextgame")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                who = statsapi.lookup_team(
                                    comment.body[comment.body.find("{") +
                                                 1:comment.body.find("}")]
                                )[0]["id"]
                                next = statsapi.next_game(who)
                                game = statsapi.schedule(game_id=next)
                                replyText += game[0]["summary"]
                            except Exception as e:
                                log.error(
                                    "Error generating response for nextgame: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for nextgame: {}"
                                    .format(e))

                        if "lastgame" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append("lastgame")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                who = statsapi.lookup_team(
                                    comment.body[comment.body.find("{") +
                                                 1:comment.body.find("}")]
                                )[0]["id"]
                                last = statsapi.last_game(who)
                                game = statsapi.schedule(game_id=last)
                                replyText += game[0]["summary"]
                            except Exception as e:
                                log.error(
                                    "Error generating response for lastgame: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for lastgame: {}"
                                    .format(e))

                        if "winprob" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append("winprob")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                who = statsapi.lookup_team(
                                    comment.body[comment.body.find("{") +
                                                 1:comment.body.find("}")]
                                )[0]["id"]
                                game = statsapi.schedule(team=who)[0]
                                contextMetrics = statsapi.get(
                                    "game_contextMetrics",
                                    {"gamePk": game["game_id"]})
                                away_win_prob = contextMetrics.get(
                                    "awayWinProbability", "-")
                                home_win_prob = contextMetrics.get(
                                    "homeWinProbability", "-")
                                replyText += "\n    " + game["summary"] + "\n"
                                replyText += (
                                    "    Current win probabilities: " +
                                    game["away_name"] + " " +
                                    str(away_win_prob) + "%, " +
                                    game["home_name"] + " " +
                                    str(home_win_prob) + "%")
                            except Exception as e:
                                log.error(
                                    "Error generating response for winprob: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for winprob: {}"
                                    .format(e))

                        if ("score" in comment.body.lower() and
                                "Current win probabilities" not in replyText):
                            self.comments[comment.id]["cmd"].append("score")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                who = comment.body[comment.body.find("{") +
                                                   1:comment.body.
                                                   find("}")].lower()
                                if who in [
                                        "nle",
                                        "nlw",
                                        "nlc",
                                        "ale",
                                        "alw",
                                        "alc",
                                        "all",
                                ]:
                                    todaysGames = statsapi.get(
                                        "schedule",
                                        {
                                            "fields":
                                            "dates,date,games,gamePk,teams,away,team,division,abbreviation",
                                            "sportId": 1,
                                            "hydrate": "team(division)",
                                        },
                                    )
                                    gamePks = ""
                                    for i in (x["gamePk"] for x in
                                              todaysGames["dates"][0]["games"]
                                              if who == "all" or x["teams"]
                                              ["away"]["team"]["division"]
                                              ["abbreviation"].lower() == who
                                              or x["teams"]["home"]["team"]
                                              ["division"]
                                              ["abbreviation"].lower() == who):
                                        gamePks += "{},".format(i)

                                    if len(gamePks):
                                        if gamePks[-1] == ",":
                                            gamePks = gamePks[:-1]

                                    games = statsapi.schedule(game_id=gamePks)
                                    for game in games:
                                        replyText += "\n    " + game["summary"]
                                else:
                                    who = statsapi.lookup_team(
                                        comment.body[comment.body.find("{") +
                                                     1:comment.body.find("}")]
                                    )[0]["id"]
                                    game = statsapi.schedule(team=who)
                                    replyText += game[0]["summary"]
                            except Exception as e:
                                log.error(
                                    "Error generating response for score: {}".
                                    format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for score: {}".
                                    format(e))

                        if "standings" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append(
                                "standings")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                if comment.body.find("{") != -1:
                                    who = comment.body[comment.body.find("{") +
                                                       1:comment.body.
                                                       find("}")].lower()
                                else:
                                    who = "all"

                                wc = (True if any(
                                    True
                                    for x in ["wc", "wildcard", "wild card"]
                                    if x in comment.body) else False)
                                if who == "all":
                                    standings = statsapi.standings(
                                        date=datetime.today().strftime(
                                            "%m/%d/%Y"),
                                        include_wildcard=wc,
                                    )
                                elif who in [
                                        "nle", "nlw", "nlc", "ale", "alw",
                                        "alc"
                                ]:
                                    standings = statsapi.standings(
                                        date=datetime.today().strftime(
                                            "%m/%d/%Y"),
                                        division=who,
                                        include_wildcard=wc,
                                    )
                                elif who in ["nl", "al"]:
                                    leagueId = 103 if who == "al" else 104
                                    standings = statsapi.standings(
                                        leagueId=leagueId,
                                        date=datetime.today().strftime(
                                            "%m/%d/%Y"),
                                        include_wildcard=wc,
                                    )

                                replyText += "\n    {}".format(
                                    standings.replace("\n", "\n    "))
                            except Exception as e:
                                log.error(
                                    "Error generating response for standings: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for standings: {}"
                                    .format(e))

                        if "rundiff" in comment.body.lower():
                            self.comments[comment.id]["cmd"].append("rundiff")
                            if replyText != "":
                                replyText += "\n\n*****\n\n"

                            try:
                                whoTeamId = None
                                if comment.body.find("{") != -1:
                                    who = comment.body[comment.body.find("{") +
                                                       1:comment.body.
                                                       find("}")].lower()
                                else:
                                    who = None

                                params = {
                                    "hydrate":
                                    "team(division)",
                                    "fields":
                                    "records,standingsType,teamRecords,team,name,division,id,nameShort,abbreviation,runDifferential",
                                }
                                if who in [
                                        "all",
                                        "nle",
                                        "nlw",
                                        "nlc",
                                        "ale",
                                        "alw",
                                        "alc",
                                        "nl",
                                        "al",
                                ]:
                                    if who == "all":
                                        params.update({"leagueId": "103,104"})
                                    elif who in [
                                            "nle",
                                            "nlw",
                                            "nlc",
                                            "ale",
                                            "alw",
                                            "alc",
                                    ]:
                                        params.update({
                                            "leagueId":
                                            "103" if who[0] == "a" else "104"
                                        })
                                    elif who in ["nl", "al"]:
                                        params.update({
                                            "leagueId":
                                            "103" if who == "al" else "104"
                                        })
                                else:
                                    whoTeamId = statsapi.lookup_team(
                                        who)[0]["id"]
                                    teamInfo = statsapi.get(
                                        "team", {"teamId": whoTeamId})
                                    whoDivId = teamInfo["teams"][0][
                                        "division"]["id"]
                                    whoLeagueId = teamInfo["teams"][0][
                                        "league"]["id"]
                                    params.update({"leagueId": whoLeagueId})

                                r = statsapi.get("standings", params)

                                rundiff = ""
                                divisions = {}

                                for y in r["records"]:
                                    for x in (
                                            x for x in y["teamRecords"]
                                            if who == "all" or who == x["team"]
                                        ["division"]["abbreviation"].lower() or
                                        (whoTeamId and whoDivId == x["team"]
                                         ["division"]["id"])
                                            or who in ["al", "nl"]):
                                        if (x["team"]["division"]["id"]
                                                not in divisions.keys()):
                                            divisions.update({
                                                x["team"]["division"]["id"]: {
                                                    "div_name":
                                                    x["team"]["division"]
                                                    ["name"],
                                                    "teams": [],
                                                }
                                            })

                                        team = {
                                            "name": x["team"]["name"],
                                            "run_diff": x["runDifferential"],
                                        }
                                        if (whoTeamId == x["team"]["id"]
                                                or not whoTeamId):
                                            divisions[x["team"]["division"][
                                                "id"]]["teams"].append(team)

                                for div in divisions.values():
                                    if not whoTeamId:
                                        rundiff += div["div_name"] + "\n"

                                    for t in div["teams"]:
                                        rundiff += "{name:<21}: {run_diff:^5} run(s)\n".format(
                                            **t)

                                    rundiff += "\n"

                                replyText += "\n    {}".format(
                                    rundiff.replace("\n", "\n    "))
                            except Exception as e:
                                log.error(
                                    "Error generating response for rundiff: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error generating response for rundiff: {}"
                                    .format(e))

                        if replyText != "":
                            try:
                                latest_reply = comment.reply(
                                    replyText + "\n\n" + self.replyFooter
                                    if len(self.replyFooter) > 0 else "")
                                self.comments[comment.id].update(
                                    {"reply": latest_reply})
                                latest_reply.disable_inbox_replies()
                                log.info(
                                    "Replied with comment id {} and disabled inbox replies."
                                    .format(latest_reply))
                                self.dbc.execute(
                                    "update {} set cmd=?,reply=? where comment_id=?;"
                                    .format(self.dbTable),
                                    (
                                        str(self.comments[comment.id]["cmd"]),
                                        str(latest_reply),
                                        str(comment.id),
                                    ),
                                )
                            except Exception as e:
                                log.error(
                                    "Error replying to comment or disabling inbox replies: {}"
                                    .format(e))
                                self.comments[comment.id]["errors"].append(
                                    "Error submitting comment or disabling inbox replies: {}"
                                    .format(e))

                        if len(self.comments[comment.id].get("errors")):
                            self.dbc.execute(
                                "update {} set errors=? where comment_id=?;".
                                format(self.dbTable),
                                (
                                    str(self.comments[comment.id].get(
                                        "errors")),
                                    str(comment.id),
                                ),
                            )

                        self.db.commit()
            except Exception as e:
                log.exception("Caught exception: {}".format(e))
                raise

            log.debug("Checking for downvotes on {} replies...".format(
                sum(1 for x in self.comments if self.comments[x].get("reply")
                    and not self.comments[x].get("removed")
                    and float(self.comments[x].get("date")) >= time.time() -
                    60 * 60 * 24 * self.historicalDays)))
            for x in (x for x in self.comments if self.comments[x].get("reply")
                      and not self.comments[x].get("removed")
                      and float(self.comments[x].get("date")) >= time.time() -
                      60 * 60 * 24 * self.historicalDays):
                # print('Submission: {}, reply: {}'.format(self.r.comment(x).submission, self.comments[x]['reply']))
                try:
                    self.comments[x]["reply"].refresh()
                except praw.exceptions.ClientException as e:
                    print(
                        "Error refreshing attributes for comment reply {}: {}".
                        format(self.comments[x]["reply"], e))
                    if "comment does not appear to be in the comment tree" in str(
                            e):
                        self.comments[x].update({"removed": time.time()})
                        self.dbc.execute(
                            "update {} set removed=? where comment_id=?;".
                            format(self.dbTable),
                            (str(self.comments[x].get("removed")), str(x)),
                        )

                if (not self.comments[x].get("removed") and
                        self.comments[x]["reply"].score <= self.delThreshold):
                    log.info(
                        "Deleting comment {} with score ({}) at or below threshold ({})..."
                        .format(
                            self.comments[x]["reply"],
                            self.comments[x]["reply"].score,
                            self.delThreshold,
                        ))
                    try:
                        self.comments[x]["reply"].delete()
                        self.comments[x].update({"removed": time.time()})
                        self.dbc.execute(
                            "update {} set removed=? where comment_id=?;".
                            format(self.dbTable),
                            (str(self.comments[x].get("removed")), str(x)),
                        )
                    except Exception as e:
                        log.error(
                            "Error deleting downvoted comment: {}".format(e))
                        self.comments[x]["errors"].append(
                            "Error deleting downvoted comment: {}".format(e))

            self.db.commit()

            limits = self.r.auth.limits
            if limits.get("remaining") < 60:
                log.warn(
                    "Approaching Reddit API rate limit, sleeping for a minute... {}"
                    .format(limits))
                time.sleep(60)
            else:
                log.debug("Reddit API limits: {}".format(limits))

        return
Exemple #14
0
async def pstats(ctx, *, args):
    players = statsapi.lookup_player(args)
    if (len(players)) == 0:
        await ctx.send("I couldn't find anyone with that name.")
    elif (len(players)) > 1:
        allPlayers = "Found %s players\n" % (len(players))
        for x in players:
            allPlayers = allPlayers + (x['fullName']) + "\n"
        await ctx.send(allPlayers)
    else:
        player = players[0]
        title = "%s | %s - %s" % (player['primaryNumber'], player['fullName'],
                                  player['primaryPosition']['abbreviation'])
        playerStats = statsapi.player_stat_data(player['id'],
                                                group="[pitching]",
                                                type="season")
        team = playerStats['current_team']
        stats = playerStats['stats']
        if (len(stats)) == 0:
            await ctx.send("I don't have any data for that player.")
        else:
            stats = stats[0]['stats']
            record = "%s - %s (%s)" % (stats['wins'], stats['losses'],
                                       stats['saves'])
            embed = createEmbed(title, team)
            embed.add_field(name="Record", value=record, inline=True)
            embed.add_field(name="Saves", value=stats['saves'], inline=True)
            embed.add_field(name="ERA", value=stats['era'], inline=True)
            embed.add_field(name="WHIP", value=stats['whip'], inline=True)
            embed.add_field(
                name="Opp. Batting",
                value=(
                    "%s/%s/%s/%s" %
                    (stats['avg'], stats['obp'], stats['slg'], stats['ops'])),
                inline=True)
            embed.add_field(name="Earned Runs",
                            value=stats['earnedRuns'],
                            inline=True)
            embed.add_field(name="Innings Pitched",
                            value=stats['inningsPitched'],
                            inline=True)
            embed.add_field(name="Hits", value=stats['hits'], inline=True)
            embed.add_field(name="Walks",
                            value=stats['baseOnBalls'],
                            inline=True)
            embed.add_field(name="Homeruns",
                            value=stats['homeRuns'],
                            inline=True)
            embed.add_field(name="Strikeouts",
                            value=stats['strikeOuts'],
                            inline=True)
            embed.add_field(name="Strike %",
                            value=stats['strikePercentage'],
                            inline=True)
            embed.add_field(name="Pitches/Inning",
                            value=stats['pitchesPerInning'],
                            inline=True)
            embed.add_field(name="K/BB Ratio",
                            value=stats['strikeoutWalkRatio'],
                            inline=True)
            embed.add_field(name="K/9",
                            value=stats['strikeoutsPer9Inn'],
                            inline=True)
            embed.add_field(name="BB/9",
                            value=stats['walksPer9Inn'],
                            inline=True)
            embed.add_field(name="Hits/9",
                            value=stats['hitsPer9Inn'],
                            inline=True)
            embed.add_field(name="HR/9",
                            value=stats['homeRunsPer9'],
                            inline=True)
            await ctx.send(embed=embed)
Exemple #15
0
async def stats(ctx, *, args):
    players = statsapi.lookup_player(args)
    if (len(players)) == 0:
        await ctx.send("I couldn't find anyone with that name.")
    elif (len(players)) > 1:
        allPlayers = "Found %s players\n" % (len(players))
        for x in players:
            allPlayers = allPlayers + (x['fullName']) + "\n"
        await ctx.send(allPlayers)
    else:
        player = players[0]
        title = "%s | %s - %s" % (player['primaryNumber'], player['fullName'],
                                  player['primaryPosition']['abbreviation'])
        playerStats = statsapi.player_stat_data(player['id'],
                                                group="[hitting]",
                                                type="season")
        team = playerStats['current_team']
        stats = playerStats['stats']
        if (len(stats)) == 0:
            await ctx.send("I don't have any data for that player.")
        else:
            print(stats)
            stats = stats[0]['stats']
            embed = createEmbed(title, team)
            embed.add_field(
                name="AVG/OBP/SLG/OPS",
                value=(
                    "%s/%s/%s/%s" %
                    (stats['avg'], stats['obp'], stats['slg'], stats['ops'])),
                inline=False)
            embed.add_field(name="Games Played",
                            value=stats['gamesPlayed'],
                            inline=True)
            embed.add_field(name="Runs", value=stats['runs'], inline=True)
            embed.add_field(name="RBIs", value=stats['rbi'], inline=True)
            embed.add_field(name="BABIP", value=stats['babip'], inline=True)
            embed.add_field(name="ABs", value=stats['atBats'], inline=True)
            embed.add_field(name="PAs",
                            value=stats['plateAppearances'],
                            inline=True)
            embed.add_field(name="Hits", value=stats['hits'], inline=True)
            embed.add_field(name="BB", value=stats['baseOnBalls'], inline=True)
            embed.add_field(name="HRs", value=stats['homeRuns'], inline=True)
            embed.add_field(name="Triples",
                            value=stats['triples'],
                            inline=True)
            embed.add_field(name="Doubles",
                            value=stats['doubles'],
                            inline=True)
            embed.add_field(name="IBB",
                            value=stats['intentionalWalks'],
                            inline=True)
            embed.add_field(name="HBP", value=stats['hitByPitch'], inline=True)
            embed.add_field(name="Total Bases",
                            value=stats['totalBases'],
                            inline=True)
            embed.add_field(name="Strikeouts",
                            value=stats['strikeOuts'],
                            inline=True)
            embed.add_field(name="LOB", value=stats['leftOnBase'], inline=True)
            embed.add_field(name="Stolen Bases",
                            value=stats['stolenBases'],
                            inline=True)
            embed.add_field(name="SB %",
                            value=stats['stolenBasePercentage'],
                            inline=True)
            await ctx.send(embed=embed)
Exemple #16
0
def findPlayer(lookup_value, year):
	lookupInfo = statsapi.lookup_player(lookup_value, season=year)
	if lookupInfo == []:
		return None
	playerId = lookupInfo[0]['id']
	return playerId
Exemple #17
0
    def run(self):
        self.dbc.execute(
            'SELECT comment_id,date,reply FROM comments ORDER BY date DESC LIMIT 500;'
        )
        comment_ids = self.dbc.fetchall()
        for cid in comment_ids:
            self.comments.update({
                cid[0]: {
                    'date': cid[1],
                    'reply': cid[2],
                    'historical': True
                }
            })

        while True:
            print('Monitoring comments in the following subreddit(s): {}...'.
                  format(self.sub))
            for comment in self.r.subreddit(
                    self.sub).stream.comments(pause_after=self.pause_after):
                if not comment:
                    break  #take a break to delete downvoted replies
                if comment.id in self.comments.keys():
                    print('Already processed comment {}'.format(comment.id))
                    continue
                replyText = ''
                if str(self.r.user.me()).lower() in comment.body.lower(
                ) and comment.author != self.r.user.me():
                    self.comments.update({
                        comment.id: {
                            'sub': comment.subreddit,
                            'author': comment.author,
                            'post': comment.submission,
                            'date': time.time(),
                            'cmd': [],
                            'errors': []
                        }
                    })
                    self.dbc.execute(
                        "insert or ignore into comments (comment_id, sub, author, post, date) values (?, ?, ?, ?, ?);",
                        (str(comment.id), str(comment.subreddit),
                         str(comment.author), str(
                             comment.submission), str(comment.created_utc)))
                    print('({}) {} - {}: {}'.format(comment.subreddit,
                                                    comment.id, comment.author,
                                                    comment.body))
                    if 'help' in comment.body.lower():
                        self.comments[comment.id]['cmd'].append('help')
                        replyText += 'Invoke me by including my name anywhere in your comment.\n\n'
                        replyText += 'Include an available command in your comment: [help, score, careerstats, seasonstats, standings, winprob], '
                        replyText += 'along with the subject in curly brackets.\n\n'
                        replyText += 'For stats commands, you can also include the type: [hitting, pitching, fielding].\n\n'
                        replyText += 'For example, `careerstats {hamels} pitching` or `score {phillies}` or `standings {nle}` '
                        replyText += '(try including the word wildcard when asking for standings).\n\n'
                        replyText += 'I am currently monitoring the following subreddit(s): ' + self.sub + '.'
                    if 'seasonstats' in comment.body.lower():
                        self.comments[comment.id]['cmd'].append('seasonstats')
                        if replyText != '': replyText += '\n\n*****\n\n'
                        try:
                            who = statsapi.lookup_player(
                                comment.body[comment.body.find('{') +
                                             1:comment.body.find('}'
                                                                 )])[0]['id']
                            what = []
                            if 'hitting' in comment.body.lower(
                            ) or 'batting' in comment.body.lower():
                                what.append('hitting')
                            if 'pitching' in comment.body.lower():
                                what.append('pitching')
                            if 'fielding' in comment.body.lower():
                                what.append('fielding')
                            if len(what):
                                stats = statsapi.player_stats(
                                    who,
                                    str(what).replace('\'',
                                                      '').replace(' ', ''),
                                    'season')
                            else:
                                stats = statsapi.player_stats(who,
                                                              type='season')
                            replyText += '\n    ' + stats.replace(
                                '\n', '\n    ')
                        except Exception as e:
                            print(
                                'Error generating response for seasonstats: {}'
                                .format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error generating response for seasonstats: {}'
                                .format(e))
                    if 'careerstats' in comment.body.lower():
                        self.comments[comment.id]['cmd'].append('careerstats')
                        if replyText != '': replyText += '\n\n*****\n\n'
                        try:
                            who = self.lookup_player(
                                comment.body[comment.body.find('{') +
                                             1:comment.body.find('}')])
                            what = []
                            if 'hitting' in comment.body.lower(
                            ) or 'batting' in comment.body.lower():
                                what.append('hitting')
                            if 'pitching' in comment.body.lower():
                                what.append('pitching')
                            if 'fielding' in comment.body.lower():
                                what.append('fielding')
                            if len(what):
                                stats = statsapi.player_stats(
                                    who,
                                    str(what).replace('\'',
                                                      '').replace(' ', ''),
                                    'career')
                            else:
                                stats = statsapi.player_stats(who,
                                                              type='career')
                            replyText += '\n    ' + stats.replace(
                                '\n', '\n    ')
                        except Exception as e:
                            print(
                                'Error generating response for careerstats: {}'
                                .format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error generating response for careerstats: {}'
                                .format(e))
                    if 'nextgame' in comment.body.lower():
                        self.comments[comment.id]['cmd'].append('nextgame')
                        if replyText != '': replyText += '\n\n*****\n\n'
                        try:
                            who = statsapi.lookup_team(
                                comment.body[comment.body.find('{') +
                                             1:comment.body.find('}'
                                                                 )])[0]['id']
                            next = statsapi.next_game(who)
                            game = statsapi.schedule(game_id=next)
                            replyText += game[0]['summary']
                        except Exception as e:
                            print('Error generating response for nextgame: {}'.
                                  format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error generating response for nextgame: {}'.
                                format(e))
                    if 'lastgame' in comment.body.lower():
                        self.comments[comment.id]['cmd'].append('lastgame')
                        if replyText != '': replyText += '\n\n*****\n\n'
                        try:
                            who = statsapi.lookup_team(
                                comment.body[comment.body.find('{') +
                                             1:comment.body.find('}'
                                                                 )])[0]['id']
                            last = statsapi.last_game(who)
                            game = statsapi.schedule(game_id=last)
                            replyText += game[0]['summary']
                        except Exception as e:
                            print('Error generating response for lastgame: {}'.
                                  format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error generating response for lastgame: {}'.
                                format(e))
                    if 'winprob' in comment.body.lower():
                        self.comments[comment.id]['cmd'].append('winprob')
                        if replyText != '': replyText += '\n\n*****\n\n'
                        try:
                            who = statsapi.lookup_team(
                                comment.body[comment.body.find('{') +
                                             1:comment.body.find('}'
                                                                 )])[0]['id']
                            game = statsapi.schedule(team=who)[0]
                            contextMetrics = statsapi.get(
                                'game_contextMetrics',
                                {'gamePk': game['game_id']})
                            away_win_prob = contextMetrics.get(
                                'awayWinProbability', '-')
                            home_win_prob = contextMetrics.get(
                                'homeWinProbability', '-')
                            replyText += '\n    ' + game['summary'] + '\n'
                            replyText += '    Current win probabilities: ' + game[
                                'away_name'] + ' ' + str(
                                    away_win_prob
                                ) + '%, ' + game['home_name'] + ' ' + str(
                                    home_win_prob) + '%'
                        except Exception as e:
                            print('Error generating response for winprob: {}'.
                                  format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error generating response for winprob: {}'.
                                format(e))
                    if 'score' in comment.body.lower(
                    ) and 'Current win probabilities' not in replyText:
                        self.comments[comment.id]['cmd'].append('score')
                        if replyText != '': replyText += '\n\n*****\n\n'
                        try:
                            who = comment.body[comment.body.find('{') +
                                               1:comment.body.find('}')].lower(
                                               )
                            if who in [
                                    'nle', 'nlw', 'nlc', 'ale', 'alw', 'alc',
                                    'all'
                            ]:
                                todaysGames = statsapi.get(
                                    'schedule', {
                                        'fields':
                                        'dates,date,games,gamePk,teams,away,team,division,abbreviation',
                                        'sportId': 1,
                                        'hydrate': 'team(division)'
                                    })
                                gamePks = ''
                                for i in (
                                        x['gamePk'] for x in
                                        todaysGames['dates'][0]['games']
                                        if who == 'all' or x['teams']['away']
                                    ['team']['division']['abbreviation'].lower(
                                    ) == who or x['teams']['home']['team']
                                    ['division']['abbreviation'].lower() == who
                                ):
                                    gamePks += '{},'.format(i)
                                if len(gamePks):
                                    if gamePks[-1] == ',':
                                        gamePks = gamePks[:-1]
                                games = statsapi.schedule(game_id=gamePks)
                                for game in games:
                                    replyText += '\n    ' + game['summary']
                            else:
                                who = statsapi.lookup_team(
                                    comment.body[comment.body.find('{') +
                                                 1:comment.body.find('}')]
                                )[0]['id']
                                game = statsapi.schedule(team=who)
                                replyText += game[0]['summary']
                        except Exception as e:
                            print('Error generating response for score: {}'.
                                  format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error generating response for score: {}'.
                                format(e))
                    if 'standings' in comment.body.lower():
                        self.comments[comment.id]['cmd'].append('standings')
                        if replyText != '': replyText += '\n\n*****\n\n'
                        try:
                            if comment.body.find('{') != -1:
                                who = comment.body[comment.body.find('{') +
                                                   1:comment.body.
                                                   find('}')].lower()
                            else:
                                who = 'all'
                            wc = True if any(
                                True for x in ['wc', 'wildcard', 'wild card']
                                if x in comment.body) else False
                            if who == 'all':
                                standings = statsapi.standings(
                                    date=datetime.today().strftime('%m/%d/%Y'),
                                    include_wildcard=wc)
                            elif who in [
                                    'nle', 'nlw', 'nlc', 'ale', 'alw', 'alc'
                            ]:
                                standings = statsapi.standings(
                                    date=datetime.today().strftime('%m/%d/%Y'),
                                    division=who,
                                    include_wildcard=wc)
                            elif who in ['nl', 'al']:
                                leagueId = 103 if who == 'al' else 104
                                standings = statsapi.standings(
                                    leagueId=leagueId,
                                    date=datetime.today().strftime('%m/%d/%Y'),
                                    include_wildcard=wc)
                            replyText += '\n    {}'.format(
                                standings.replace('\n', '\n    '))
                        except Exception as e:
                            print(
                                'Error generating response for standings: {}'.
                                format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error generating response for standings: {}'.
                                format(e))

                    if replyText != '':
                        try:
                            latest_reply = comment.reply(replyText +
                                                         self.replyFooter)
                            self.comments[comment.id].update(
                                {'reply': latest_reply})
                            latest_reply.disable_inbox_replies()
                            print(
                                'Replied with comment id {} and disabled inbox replies.'
                                .format(latest_reply))
                            self.dbc.execute(
                                "update comments set cmd=?,reply=? where comment_id=?;",
                                (str(self.comments[comment.id]['cmd']),
                                 str(latest_reply), str(comment.id)))
                        except Exception as e:
                            print(
                                'Error replying to comment or disabling inbox replies: {}'
                                .format(e))
                            self.comments[comment.id]['errors'].append(
                                'Error submitting comment or disabling inbox replies: {}'
                                .format(e))

                    if len(self.comments[comment.id].get('errors')):
                        self.dbc.execute(
                            "update comments set errors=? where comment_id=?;",
                            (str(self.comments[comment.id].get('errors')),
                             str(comment.id)))
                    self.db.commit()

            print('Checking for downvotes on {} replies...'.format(
                sum(1 for x in self.comments if self.comments[x].get('reply')
                    and not self.comments[x].get('removed')
                    and not self.comments[x].get('historical'))))
            for x in (x for x in self.comments if self.comments[x].get('reply')
                      and not self.comments[x].get('removed')
                      and not self.comments[x].get('historical')):
                if self.comments[x]['reply'].score <= self.del_threshold:
                    print(
                        'Deleting comment {} with score ({}) at or below threshold ({})...'
                        .format(self.comments[x]['reply'],
                                self.comments[x]['reply'].score,
                                self.del_threshold))
                    try:
                        self.comments[x]['reply'].delete()
                        self.comments[x].update({'removed': time.time()})
                        self.dbc.execute(
                            "update comments set removed=? where comment_id=?;",
                            (str(self.comments[x].get('removed')), str(x)))
                    except Exception as e:
                        print('Error deleting downvoted comment: {}'.format(e))
                        self.comments[x]['errors'].append(
                            'Error deleting downvoted comment: {}'.format(e))
            self.db.commit()

        return
Exemple #18
0
 def lookupPlayerTeam(self, id):
     playerInfo = statsapi.lookup_player(id)
     if len(playerInfo) != 1:
         print("Player ID", id, "cannot be resolved to a single team")
         return
     return playerInfo[0]['currentTeam']['id']
Exemple #19
0
def getPlayer(playername):
    player = statsapi.lookup_player(playername, season="2019")
    return player
Exemple #20
0
def results(request):
	
	# url = "http://lookup-service-prod.mlb.com/json/named.search_player_all.bam?sport_code='mlb'&name_part={}"
	# url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=271d1234d3f497eed5b1d80a07b3fcd1'

	if request.method == 'POST':

		r = statsapi.lookup_player(request.POST.get("name_field"), season=2019) # search by name first
		# returns a list - if so, can work in r[0] for succ contexts

		# case 1: all 3 provided
		if (request.POST.get("name_field") != '' and request.POST.get("number_field") != ''\
		and request.POST.get("team_field") != ''):
			num = request.POST.get("number_field")
			team = request.POST.get("team_field")
			team_list_dict = statsapi.lookup_team(team)
			
			if len(team_list_dict) == 0:
				# context = {'com': 'Inconsistent information - team does not exist'}
				context = {'com': []}
			else:
				players = []
				for player in r:
					if len(team_list_dict) == 1:
						team_id = team_list_dict[0]['id']
						if player['primaryNumber'] == num and player['currentTeam']['id'] == team_id:
							players.append(player)
					else:  # len(team_list_dict) > 1
						for ind_team in team_list_dict:
							team_id = ind_team['id']
							if player['primaryNumber'] == num and player['currentTeam']['id'] == team_id:
								players.append(player)

				if len(players) != 0:
					context = {'com': players}  
				# elif len(players) > 1: 
				# 	context = {'com': 'Too broad - make information more specific'}
				else:
					# context = {'com': 'No player found - possibly inconsisent information'}
					context = {'com': []}

		# case 2: no info provided

		elif (request.POST.get("name_field") == '' and request.POST.get("number_field") == ''\
		and request.POST.get("team_field") == ''):
			# context = {'com': 'No information given'}
			context = {'com': []}

		# case 3: name only 
		elif (request.POST.get("name_field") != '' and request.POST.get("number_field") == ''\
		and request.POST.get("team_field") == ''):
			if len(r) != 0:   # multiple players
				context = {'com': r}
			# elif len(r) > 1:  # more than 1 player 
			# 	context = {'com': 'Too broad - add player information'}
			else:  # no players
				# context = {'com': 'No player found'}
				context = {'com': []}

		# case 4: name, number
		elif (request.POST.get("name_field") != '' and request.POST.get("number_field") != ''\
		and request.POST.get("team_field") == ''):
			num = request.POST.get("number_field")
			players = []

			for player in r:
				try:
					if player['primaryNumber'] == num:  # both strings so ok
						players.append(player)
				except:
					pass
			
			if len(players) != 0:
				context = {'com': players}  
			# elif len(players) > 1: 
			# 	context = {'com': 'Too broad - add player information'}
			else:
				# context = {'com': 'No player found'}
				context = {'com': []}

		# case 5: name, team
		elif (request.POST.get("name_field") != '' and request.POST.get("number_field") == ''\
		and request.POST.get("team_field") != ''):
			team = request.POST.get("team_field")
			team_list_dict = statsapi.lookup_team(team)
			
			if len(team_list_dict) == 0:
				# context = {'com': 'Inconsistent information - team does not exist'}
				context = {'com': []}

			else:
				players = []
				for player in r:
					if len(team_list_dict) == 1:
						team_id = team_list_dict[0]['id']
						if player['currentTeam']['id'] == team_id:
							players.append(player)
					else:  # len(team_list_dict) > 1
						for ind_team in team_list_dict:
							team_id = ind_team['id']
							if player['currentTeam']['id'] == team_id:
								players.append(player)

				if len(players) != 0:
					context = {'com': players}  
				# elif len(players) > 1: 
				# 	context = {'com': 'Too broad - multiple players share parts of this name'}
				else:
					# context = {'com': 'No player found'}
					context = {'com': []}

		# case 6: number only 
		elif (request.POST.get("name_field") == '' and request.POST.get("number_field") != ''\
		and request.POST.get("team_field") == ''):
			num = request.POST.get("number_field")
			number_list_dict = statsapi.lookup_player(num, season=2019)
			players = []

			for player in number_list_dict:
				try:
					if player['primaryNumber'] == num:  
						players.append(player)
				except:
					pass

			if len(players) != 0:
				context = {'com': players} 
			# elif len(players) > 0: 
			# 	context = {'com': 'Too broad - add player information'}
			else:
				# context = {'com': 'No player found - no player holds this jersey number'}
				context = {'com': []}

		# case 7: number, team
		elif (request.POST.get("name_field") == '' and request.POST.get("number_field") != ''\
		and request.POST.get("team_field") != ''):
			
			num = request.POST.get("number_field")
			number_list_dict = statsapi.lookup_player(num, season=2019)

			team = request.POST.get("team_field")
			team_list_dict = statsapi.lookup_team(team)

			if len(team_list_dict) == 0:
				# context = {'com': 'Inconsistent information - team does not exist'}
				context = {'com': []}

			elif len(number_list_dict) == 0:
				# context = {'com': 'No player found - no player holds this jersey number'}
				context = {'com': []}

			else:
				players = []

				for player in number_list_dict:
					try:
						if player['primaryNumber'] == num:  
							players.append(player)
					except:
						pass

				players2 = []
				for player in players:
					if len(team_list_dict) == 1:
						team_id = team_list_dict[0]['id']
						if player['currentTeam']['id'] == team_id:
							players2.append(player)
					else:  # len(team_list_dict) > 1
						for ind_team in team_list_dict:
							team_id = ind_team['id']
							if player['currentTeam']['id'] == team_id:
								players2.append(player)
				
				if len(players2) != 0:
					context = {'com': players2}  
				# elif len(players2) > 1:  #lowkey impossible for multiple numbers on same team
				# 	context = {'com': 'Too broad - multiple players share this jersey number'}
				else:
					# context = {'com': 'No player found - no player on this team holds this jersey number'}
					context = {'com': []}

		# case 8: team only
		elif (request.POST.get("name_field") == '' and request.POST.get("number_field") == ''\
		and request.POST.get("team_field") != ''):
			team = request.POST.get("team_field")
			team_list_dict = statsapi.lookup_team(team)

			if len(team_list_dict) == 0:
				# context = {'com': 'Inconsistent information - team does not exist'}
				context = {'com': []}
			else:
				players = []
				for team in team_list_dict:
					team_id = team['id']
					all_players = statsapi.lookup_player(team_id, season=2019)
					
					for player in all_players:
						if player['currentTeam']['id'] == team_id:
							players.append(player)

				context = {'com': players}

		for player in context['com']:
			player['useName'] = player['useName'].lower()
			player['lastName'] = player['lastName'].lower()

			team_dict = statsapi.lookup_team(player['currentTeam']['id'])
			team_name = team_dict[0]['name']
			player['teamName'] = team_name

		return render(request, "model1/results.html", context)

	else:
		# context = {'com': PlayerInput()}
		return render(request, "model1/home.html", {})
def playerdatabase():
    playerset_num = 0
    player_database = [[], [], [], [], [], [], [], [], [], [], []]
    for playerset in players:
        playerset_database = []
        player_num = 0
        for player in playerset:
            print(len(playerset))
            print(player_num)
            if statsapi.lookup_player(player) != [] and statsapi.lookup_player(
                    player) != 'none':
                if playerset_num == 0 or playerset_num == 1:
                    player_ID = str(statsapi.lookup_player(player)[0]['id'])
                    get_player_stats = requests.get(base_url + player_ID +
                                                    pitching_url)
                    player_stats = get_player_stats.json()
                    new_player = {
                        "player_name":
                        player,
                        "era":
                        player_stats['stats'][0]['splits'][0]['stat']['era'],
                        "k_per_9":
                        player_stats['stats'][0]['splits'][0]['stat']
                        ['strikeoutsPer9Inn'],
                        "k_per_w":
                        player_stats['stats'][0]['splits'][0]['stat']
                        ['strikeoutWalkRatio'],
                        "whip":
                        player_stats['stats'][0]['splits'][0]['stat']['whip'],
                        "wins":
                        player_stats['stats'][0]['splits'][0]['stat']['wins'],
                        "player_team":
                        str(
                            statsapi.lookup_team(
                                statsapi.lookup_player(player)[0]
                                ['currentTeam']['id'])[0]['name']),
                        "player_id":
                        player_ID
                    }
                    playerset_database.append(new_player)
                else:
                    player_ID = str(statsapi.lookup_player(player)[0]['id'])
                    print(player_ID)
                    get_player_stats = requests.get(base_url + player_ID +
                                                    hitting_url)
                    player_stats = get_player_stats.json()
                    if playerset_num == 8:
                        player_defense = []
                    else:
                        get_player_fielding = requests.get(base_url +
                                                           player_ID +
                                                           fielding_url)
                        player_fielding = get_player_fielding.json()
                        index = 0
                        num_indexes = len(
                            (player_fielding['stats'][0]['splits']))
                        player_defense = []
                        while index < num_indexes:
                            new_position = {
                                "position":
                                player_fielding['stats'][0]['splits'][index]
                                ['stat']['position']['abbreviation'],
                                "fielding_perc":
                                player_fielding['stats'][0]['splits'][index]
                                ['stat']['fielding'],
                            }
                            player_defense.append(new_position)
                            index += 1

                    new_player = {
                        "player_name":
                        player,
                        "average":
                        player_stats['stats'][0]['splits'][0]['stat']['avg'],
                        "on_base_per":
                        player_stats['stats'][0]['splits'][0]['stat']['obp'],
                        "slugging_per":
                        player_stats['stats'][0]['splits'][0]['stat']['slg'],
                        "homeruns":
                        player_stats['stats'][0]['splits'][0]['stat']
                        ['homeRuns'],
                        "stolen_bases":
                        player_stats['stats'][0]['splits'][0]['stat']
                        ['stolenBases'],
                        "player_team":
                        str(
                            statsapi.lookup_team(
                                statsapi.lookup_player(player)[0]
                                ['currentTeam']['id'])[0]['name']),
                        "player_id":
                        player_ID,
                        "fielding_perc":
                        player_defense
                    }
                    playerset_database.append(new_player)
            player_num += 1
        player_database[playerset_num] = playerset_database
        playerset_num += 1
    return jsonify(player_database)