├── tests ├── __init__.py ├── test_players.py ├── test_drafts.py ├── test_user.py ├── test_stats.py └── test_league.py ├── requirements.txt ├── sleeper_wrapper ├── __init__.py ├── base_api.py ├── players.py ├── drafts.py ├── user.py ├── stats.py └── league.py ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTORS.md ├── setup.py ├── LICENSE.md ├── .gitignore └── README.md /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.22.0 2 | pytest==4.6.2 -------------------------------------------------------------------------------- /sleeper_wrapper/__init__.py: -------------------------------------------------------------------------------- 1 | from .league import League 2 | from .base_api import BaseApi 3 | from .user import User 4 | from .drafts import Drafts 5 | from .stats import Stats 6 | from .players import Players -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "3.5" 5 | - "3.5-dev" 6 | - "3.6" 7 | - "3.6-dev" 8 | 9 | install: 10 | - pip install -r requirements.txt 11 | 12 | script: 13 | - pytest -------------------------------------------------------------------------------- /tests/test_players.py: -------------------------------------------------------------------------------- 1 | from sleeper_wrapper import Players 2 | 3 | def test_get_trending_players(capsys): 4 | players = Players() 5 | added = players.get_trending_players("nfl","add", 1, 4) 6 | 7 | dropped = players.get_trending_players("nfl","drop") 8 | 9 | # with capsys.disabled(): 10 | # print(added) 11 | # print(dropped) -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## Version 1.0.1 and 1.0.2 4 | - Created all objects for the wrapper 5 | - Created all initial functions 6 | 7 | ## Version 1.0.3 8 | - Added losses to standings 9 | - Updated documentation 10 | 11 | ## Version 1.0.6 12 | - Fixed scoreboards bug caused by sleeper api giving None as custom pts 13 | 14 | ## Version 1.0.7 15 | - Fixed KeyError in the get_team_score() method. 16 | -------------------------------------------------------------------------------- /sleeper_wrapper/base_api.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | 5 | class BaseApi(): 6 | def _call(self, url): 7 | result_json_string = requests.get(url); 8 | try: 9 | result_json_string.raise_for_status() 10 | except requests.exceptions.HTTPError as e: 11 | return e 12 | #return SleeperWrapperException("Empty value returned") 13 | 14 | result = result_json_string.json() 15 | return result; -------------------------------------------------------------------------------- /sleeper_wrapper/players.py: -------------------------------------------------------------------------------- 1 | from .base_api import BaseApi 2 | 3 | class Players(BaseApi): 4 | def __init__(self): 5 | pass 6 | 7 | def get_all_players(self): 8 | return self._call("https://api.sleeper.app/v1/players/nfl") 9 | 10 | def get_trending_players(self,sport, add_drop, hours=24, limit=25 ): 11 | return self._call("https://api.sleeper.app/v1/players/{}/trending/{}?lookback_hours={}&limit={}".format(sport, add_drop, hours, limit)) -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | sleeper-api-wrapper contributors 2 | ============================================ 3 | 4 | [Swapnik Katkoori](https://github.com/SwapnikKatkoori) 5 | 6 | - Author and Maintainer 7 | - Initial code and documentation 8 | 9 | [Alex Hawkins](https://github.com/AlexHawkins1) 10 | - Added losses data to the data returned by the get_standings() method. 11 | - Updated documentation 12 | 13 | [scipio314](https://github.com/scipio314) 14 | - Fixed KeyError in the get_team_score() method. 15 | -------------------------------------------------------------------------------- /tests/test_drafts.py: -------------------------------------------------------------------------------- 1 | from sleeper_wrapper import Drafts 2 | 3 | def test_get_specific_draft(): 4 | draft = Drafts(257270643320426496) 5 | specific_draft = draft.get_specific_draft() 6 | 7 | assert isinstance(specific_draft,dict) 8 | def test_get_all_picks(): 9 | draft = Drafts(257270643320426496) 10 | all_picks = draft.get_all_picks() 11 | first_item = all_picks[0] 12 | 13 | assert isinstance(all_picks,list) 14 | assert isinstance(first_item, dict) 15 | 16 | def test_get_traded_picks(): 17 | draft = Drafts(257270643320426496) 18 | traded_picks = draft.get_traded_picks() 19 | 20 | assert isinstance(traded_picks,list) 21 | -------------------------------------------------------------------------------- /sleeper_wrapper/drafts.py: -------------------------------------------------------------------------------- 1 | from .base_api import BaseApi 2 | 3 | class Drafts(BaseApi): 4 | def __init__(self, draft_id): 5 | self.draft_id = draft_id 6 | self._base_url = "https://api.sleeper.app/v1/draft/{}".format(self.draft_id) 7 | 8 | def get_specific_draft(self): 9 | """gets the draft specified by the draft_id""" 10 | return self._call(self._base_url) 11 | 12 | def get_all_picks(self): 13 | """gets all the picks in the draft specified by the draft_id""" 14 | return self._call("{}/{}".format(self._base_url,"picks")) 15 | 16 | def get_traded_picks(self): 17 | """gets all traded picks in the draft specified by the draft_id""" 18 | return self._call("{}/{}".format(self._base_url,"traded_picks")) 19 | -------------------------------------------------------------------------------- /tests/test_user.py: -------------------------------------------------------------------------------- 1 | from sleeper_wrapper import User 2 | 3 | def test_get_user(capsys): 4 | user = User("swa") 5 | user = user.get_user() 6 | assert isinstance(user, dict) 7 | assert user['username'] == "swa" 8 | 9 | def test_get_all_leagues(capsys): 10 | user = User("78623389212098560") 11 | leagues = user.get_all_leagues("nfl", 2019) 12 | 13 | assert isinstance(leagues, list) 14 | assert isinstance(leagues[0], dict) 15 | 16 | user = User("swa") 17 | leagues = user.get_all_leagues("nfl", 2019) 18 | assert isinstance(leagues, list) 19 | assert isinstance(leagues[0], dict) 20 | 21 | def test_get_all_drafts(capsys): 22 | user = User("swa") 23 | drafts = user.get_all_drafts("nfl", 2019) 24 | assert isinstance(drafts, list) 25 | assert isinstance(drafts[0], dict) -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | from setuptools import setup 3 | 4 | # The directory containing this file 5 | HERE = pathlib.Path(__file__).parent 6 | 7 | # The text of the README file 8 | README = (HERE / "README.md").read_text() 9 | 10 | setup( 11 | name="sleeper-api-wrapper", 12 | version="1.0.7", 13 | description="A Python API wrapper for Sleeper Fantasy Football, as well as tools to simplify data recieved.", 14 | long_description=README, 15 | long_description_content_type="text/markdown", 16 | url="https://github.com/SwapnikKatkoori/sleeper-api-wrapper", 17 | author="Swapnik Katkoori", 18 | author_email="katkoor2@msu.edu", 19 | license="MIT", 20 | classifiers=[ 21 | "License :: OSI Approved :: MIT License", 22 | "Programming Language :: Python :: 3.5", 23 | "Programming Language :: Python :: 3.7", 24 | ], 25 | packages=["sleeper_wrapper"], 26 | include_package_data=True, 27 | install_requires=["requests==2.22.0", "pytest==4.6.2"] 28 | ) -------------------------------------------------------------------------------- /sleeper_wrapper/user.py: -------------------------------------------------------------------------------- 1 | from .base_api import BaseApi 2 | 3 | class User(BaseApi): 4 | def __init__(self, initial_user_input): 5 | self.user_id = "" 6 | self._base_url = "https://api.sleeper.app/v1/user" 7 | self._user = self._call("{}/{}".format(self._base_url,initial_user_input)) 8 | self._username = self._user["username"] 9 | self._user_id = self._user["user_id"] 10 | 11 | def get_user(self): 12 | return self._user 13 | 14 | def get_all_leagues(self, sport, season): 15 | return self._call("{}/{}/{}/{}/{}".format(self._base_url, self._user_id, "leagues", sport, season)) 16 | 17 | def get_all_drafts(self, sport, season): 18 | return self._call("{}/{}/{}/{}/{}".format(self._base_url, self._user_id, "drafts",sport, season )) 19 | 20 | def get_username(self): 21 | """A method that might be useful to convert user_id to username. For example a user can initialize with a user_id and get a username""" 22 | return self._username 23 | 24 | def get_user_id(self): 25 | """A method that might be useful to convert username to user_id. For example a user can initialize with a username and get a userid""" 26 | return self._user_id 27 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Swapnik Katkoori 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /sleeper_wrapper/stats.py: -------------------------------------------------------------------------------- 1 | from sleeper_wrapper.base_api import BaseApi 2 | 3 | class Stats(BaseApi): 4 | def __init__(self): 5 | self._base_url = "https://api.sleeper.app/v1/stats/{}".format("nfl") 6 | self._projections_base_url = "https://api.sleeper.app/v1/projections/{}".format("nfl") 7 | self._full_stats = None 8 | 9 | def get_all_stats(self, season_type, season): 10 | return self._call("{}/{}/{}".format(self._base_url, season_type, season)) 11 | 12 | def get_week_stats(self, season_type, season, week): 13 | return self._call("{}/{}/{}/{}".format(self._base_url, season_type, season, week)) 14 | 15 | def get_all_projections(self, season_type, season): 16 | return self._call("{}/{}/{}".format(self._projections_base_url, season_type, season)) 17 | 18 | def get_week_projections(self, season_type, season, week): 19 | return self._call("{}/{}/{}/{}".format(self._projections_base_url, season_type, season, week)) 20 | 21 | def get_player_week_stats(self, stats, player_id): 22 | try: 23 | return stats[player_id] 24 | except: 25 | return None 26 | 27 | 28 | def get_player_week_score(self, stats, player_id): 29 | #TODO: Need to cache stats by week, to avoid continuous api calls 30 | result_dict = {} 31 | try: 32 | player_stats = stats[player_id] 33 | except: 34 | return None 35 | 36 | if stats: 37 | try: 38 | result_dict["pts_ppr"] = player_stats["pts_ppr"] 39 | except: 40 | result_dict["pts_ppr"] = None 41 | 42 | try: 43 | result_dict["pts_std"] = player_stats["pts_std"] 44 | except: 45 | result_dict["pts_std"] = None 46 | 47 | try: 48 | result_dict["pts_half_ppr"] = player_stats["pts_half_ppr"] 49 | except: 50 | result_dict["pts_half_ppr"] = None 51 | 52 | return result_dict 53 | -------------------------------------------------------------------------------- /tests/test_stats.py: -------------------------------------------------------------------------------- 1 | from sleeper_wrapper import Stats 2 | import pytest 3 | 4 | def test_get_all_stats(capsys): 5 | stats = Stats() 6 | all_stats = stats.get_all_stats('regular', 2018) 7 | assert isinstance(all_stats, dict) 8 | 9 | def test_get_week_stats(): 10 | stats = Stats() 11 | week_stats = stats.get_week_stats('regular', 2018, '2') 12 | assert isinstance(week_stats, dict) 13 | 14 | def test_get_all_projections(): 15 | stats = Stats() 16 | projections = stats.get_all_projections("regular", "2019") 17 | assert isinstance(projections, dict) 18 | 19 | def test_get_week_projections(): 20 | stats = Stats() 21 | week_projections = stats.get_week_projections("regular", 2018, "4") 22 | assert isinstance(week_projections, dict) 23 | 24 | def test_get_player_week_score(capsys): 25 | stats = Stats() 26 | week_stats = stats.get_week_stats("regular",2018, 5) 27 | score = stats.get_player_week_score(week_stats, "GB") 28 | 29 | 30 | assert isinstance(score, dict) 31 | assert score["pts_ppr"] == None 32 | 33 | score = stats.get_player_week_score(week_stats, "1262") 34 | assert isinstance(score, dict) 35 | assert score["pts_ppr"] == None 36 | 37 | score = stats.get_player_week_score(week_stats, "5170") 38 | 39 | assert isinstance(score, dict) 40 | assert score["pts_ppr"] != None 41 | 42 | 43 | score = stats.get_player_week_score(week_stats, "30000000000") 44 | assert score is None 45 | 46 | def test_get_player_week_stats(): 47 | stats = Stats() 48 | week_stats = stats.get_week_stats("regular", 2018, 5) 49 | player_week_stats = stats.get_player_week_stats(week_stats, "1262") 50 | 51 | assert isinstance(player_week_stats, dict) 52 | 53 | player_week_stats = stats.get_player_week_stats(week_stats, "300000000") 54 | assert player_week_stats is None 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /tests/test_league.py: -------------------------------------------------------------------------------- 1 | from sleeper_wrapper import League 2 | 3 | def test_get_league(capsys): 4 | """ Tests the get_league method""" 5 | league = League(355526480094113792) 6 | league_info = league.get_league() 7 | 8 | assert isinstance(league_info, dict) 9 | assert league_info["league_id"] == "355526480094113792" 10 | 11 | def test_get_rosters(): 12 | """ Tests the get_rosters method""" 13 | league = League(355526480094113792) 14 | rosters = league.get_rosters() 15 | 16 | assert isinstance(rosters, list) 17 | assert len(rosters)>5 18 | 19 | def test_get_users(): 20 | """ Tests the get_users method""" 21 | league = League(355526480094113792) 22 | users = league.get_users() 23 | 24 | assert isinstance(users, list) 25 | assert isinstance(users[0]["user_id"], str) 26 | #I guess username is not a thing 27 | 28 | def test_get_matchups(capsys): 29 | """ Tests the get_matchups method""" 30 | league = League(355526480094113792) 31 | matchup_info = league.get_matchups(4) 32 | first_item = matchup_info[0] 33 | assert isinstance(matchup_info, list) 34 | assert isinstance(first_item, dict) 35 | 36 | matchup_info = league.get_matchups(20) 37 | 38 | assert len(matchup_info) == 0 39 | 40 | def test_get_playoff_winners_bracket(): 41 | """ Tests the get_playoff_winners_bracket method""" 42 | league = League(355526480094113792) 43 | bracket = league.get_playoff_winners_bracket() 44 | first_item = bracket[0] 45 | 46 | assert isinstance(bracket, list) 47 | assert isinstance(first_item, dict) 48 | 49 | def test_get_playoff_losers_bracket(): 50 | """ Tests the get_playoff_losers method""" 51 | league = League(355526480094113792) 52 | bracket = league.get_playoff_losers_bracket() 53 | first_item = bracket[0] 54 | 55 | assert isinstance(bracket, list) 56 | assert isinstance(first_item, dict) 57 | 58 | def test_get_transactions(): 59 | """ Tests the get_transactions method 60 | Note: Not really sure wether this method works or what its supposed to do yet because the season has not fully started. 61 | """ 62 | league = League(355526480094113792) 63 | transactions = league.get_transactions(4) 64 | assert isinstance(transactions, list) 65 | 66 | transactions = league.get_transactions("4") 67 | assert isinstance(transactions, list) 68 | 69 | def test_get_traded_picks(): 70 | """ Tests the get_traded_picks method""" 71 | league = League(355526480094113792) 72 | traded_picks = league.get_traded_picks() 73 | first_item = traded_picks[0] 74 | 75 | assert isinstance(traded_picks, list) 76 | assert isinstance(first_item, dict) 77 | 78 | def test_get_all_drafts(): 79 | league = League(355526480094113792) 80 | drafts = league.get_all_drafts() 81 | first_item = drafts[0] 82 | 83 | assert isinstance(drafts, list) 84 | assert isinstance(first_item, dict) 85 | def test_get_standings(capsys): 86 | """ Tests the get_standings method""" 87 | league = League(355526480094113792) 88 | rosters = league.get_rosters() 89 | users = league.get_users() 90 | standings = league.get_standings(rosters,users) 91 | first_item = standings[0] 92 | 93 | assert isinstance(first_item, tuple) 94 | assert len(standings)==12 95 | 96 | def test_get_scoreboards(capsys): 97 | """Tests the get_scoreoards method 98 | -Needs more testing after the season starts""" 99 | league = League(442724598706860032) 100 | matchups = league.get_matchups(1) 101 | users = league.get_users() 102 | rosters = league.get_rosters() 103 | scoreboards = league.get_scoreboards(rosters, matchups, users, "pts_half_ppr", 1) 104 | print(scoreboards) 105 | assert isinstance(scoreboards, dict) 106 | 107 | def test_get_close_games(capsys): 108 | """ 109 | Tests the get_close_games method 110 | -Notes: Need to test more. 111 | """ 112 | league = League(442724598706860032) 113 | matchups = league.get_matchups(1) 114 | users = league.get_users() 115 | rosters = league.get_rosters() 116 | scoreboards = league.get_scoreboards(rosters, matchups, users, "pts_half_ppr", 1) 117 | close_games = league.get_close_games(scoreboards, 10) 118 | assert isinstance(close_games, dict) 119 | 120 | def test_empty_roster_spots(): 121 | pass 122 | 123 | def test_get_negative_scores(): 124 | pass -------------------------------------------------------------------------------- /sleeper_wrapper/league.py: -------------------------------------------------------------------------------- 1 | from .base_api import BaseApi 2 | from .stats import Stats 3 | 4 | class League(BaseApi): 5 | def __init__(self, league_id): 6 | self.league_id = league_id 7 | self._base_url = "https://api.sleeper.app/v1/league/{}".format(self.league_id) 8 | self._league = self._call(self._base_url) 9 | 10 | def get_league(self): 11 | return self._league 12 | 13 | def get_rosters(self): 14 | return self._call("{}/{}".format(self._base_url,"rosters")) 15 | 16 | def get_users(self): 17 | return self._call("{}/{}".format(self._base_url,"users")) 18 | 19 | def get_matchups(self, week): 20 | return self._call("{}/{}/{}".format(self._base_url,"matchups", week)) 21 | 22 | def get_playoff_winners_bracket(self): 23 | return self._call("{}/{}".format(self._base_url,"winners_bracket")) 24 | 25 | def get_playoff_losers_bracket(self): 26 | return self._call("{}/{}".format(self._base_url,"losers_bracket")) 27 | 28 | def get_transactions(self, week): 29 | return self._call("{}/{}/{}".format(self._base_url,"transactions", week)) 30 | 31 | def get_traded_picks(self): 32 | return self._call("{}/{}".format(self._base_url,"traded_picks")) 33 | 34 | def get_all_drafts(self): 35 | return self._call("{}/{}".format(self._base_url, "drafts")) 36 | 37 | def map_users_to_team_name(self, users): 38 | """ returns dict {user_id:team_name}""" 39 | users_dict = {} 40 | 41 | #Maps the user_id to team name for easy lookup 42 | for user in users: 43 | try: 44 | users_dict[user["user_id"]] = user["metadata"]["team_name"] 45 | except: 46 | users_dict[user["user_id"]] = user["display_name"] 47 | return users_dict 48 | 49 | def get_standings(self, rosters, users): 50 | users_dict = self.map_users_to_team_name(users) 51 | 52 | roster_standings_list = [] 53 | for roster in rosters: 54 | wins = roster["settings"]["wins"] 55 | points = roster["settings"]["fpts"] 56 | name = roster["owner_id"] 57 | losses = roster["settings"]["losses"] 58 | if name is not None: 59 | roster_tuple = (wins, losses, points, users_dict[name]) 60 | else: 61 | roster_tuple = (wins, losses, points, None) 62 | roster_standings_list.append(roster_tuple) 63 | 64 | roster_standings_list.sort(reverse = 1) 65 | 66 | clean_standings_list = [] 67 | for item in roster_standings_list: 68 | clean_standings_list.append((item[3], str(item[0]), str(item[1]), str(item[2]))) 69 | 70 | return clean_standings_list 71 | 72 | def map_rosterid_to_ownerid(self, rosters ): 73 | """returns: dict {roster_id:[owner_id,pts]} """ 74 | result_dict = {} 75 | for roster in rosters: 76 | roster_id = roster["roster_id"] 77 | owner_id = roster["owner_id"] 78 | result_dict[roster_id] = owner_id 79 | 80 | return result_dict 81 | 82 | def get_scoreboards(self, rosters, matchups, users, score_type, week): 83 | """ returns dict {matchup_id:[(team_name,score), (team_name, score)]}""" 84 | roster_id_dict = self.map_rosterid_to_ownerid(rosters) 85 | 86 | 87 | if len(matchups) == 0: 88 | return None 89 | 90 | #Get the users to team name stats 91 | users_dict = self.map_users_to_team_name(users) 92 | 93 | 94 | #map roster_id to points 95 | scoreboards_dict = {} 96 | 97 | for team in matchups: 98 | matchup_id = team["matchup_id"] 99 | current_roster_id = team["roster_id"] 100 | owner_id = roster_id_dict[current_roster_id] 101 | if owner_id is not None: 102 | team_name = users_dict[owner_id] 103 | else: 104 | team_name = "Team name not available" 105 | 106 | team_score = self.get_team_score(team["starters"], score_type, week) 107 | if team_score is None: 108 | team_score = 0 109 | 110 | team_score_tuple = (team_name, team_score) 111 | if matchup_id not in scoreboards_dict: 112 | scoreboards_dict[matchup_id] = [team_score_tuple] 113 | else: 114 | scoreboards_dict[matchup_id].append(team_score_tuple) 115 | return scoreboards_dict 116 | 117 | def get_close_games(self, scoreboards, close_num): 118 | """ -Notes: Need to find a better way to compare scores rather than abs value of the difference of floats. """ 119 | close_games_dict = {} 120 | for key in scoreboards: 121 | team_one_score = scoreboards[key][0][1] 122 | team_two_score = scoreboards[key][1][1] 123 | 124 | if abs(team_one_score-team_two_score) < close_num: 125 | close_games_dict[key] = scoreboards[key] 126 | return close_games_dict 127 | 128 | def get_team_score(self,starters, score_type, week): 129 | total_score = 0 130 | stats = Stats() 131 | week_stats = stats.get_week_stats("regular", 2019, week) 132 | for starter in starters: 133 | if stats.get_player_week_stats(week_stats, starter) is not None: 134 | try: 135 | total_score += stats.get_player_week_stats(week_stats, starter)[score_type] 136 | except KeyError: 137 | total_score += 0 138 | 139 | return total_score 140 | 141 | def empty_roster_spots(self): 142 | pass 143 | 144 | def get_negative_scores(self, week): 145 | pass 146 | 147 | def get_rosters_players(self): 148 | pass 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/SwapnikKatkoori/sleeper-api-wrapper.svg?branch=master)](https://travis-ci.org/SwapnikKatkoori/sleeper-api-wrapper) 2 | ![GitHub](https://img.shields.io/github/license/SwapnikKatkoori/sleeper-api-wrapper.svg?color=blue) 3 | ![GitHub issues](https://img.shields.io/github/issues/SwapnikKatkoori/sleeper-api-wrapper.svg?color=orange) 4 | ![PyPI](https://img.shields.io/pypi/v/sleeper-api-wrapper) 5 | 6 | This repo is no longer actively maintained. @dtsong has created a new repo that will contain new updates for this project, please check it out: 7 | https://github.com/dtsong/sleeper-api-wrapper 8 | 9 | # sleeper-api-wrapper 10 | A Python API wrapper for Sleeper Fantasy Football, as well as tools to simplify data recieved. It makes all endpoints found in the sleeper api docs: https://docs.sleeper.app/ available and turns the JSON response recieved into python types for easy usage. 11 | 12 | 13 | # Table of Contents 14 | 15 | 1. [ Installation ](#install) 16 | 17 | 2. [Usage](#usage) 18 | 19 | * [League](#league) 20 | * [Initialize](#league_initialize) 21 | * [get_league()](#get_league) 22 | * [get_rosters()](#get_rosters) 23 | * [get_users()](#get_users) 24 | * [get_matchups()](#get_matchups) 25 | * [get_playoff_winners_bracket()](#get_playoff_winners_racket) 26 | * [get_playoff_losers_bracket()](#get_playoff_losers_racket) 27 | * [get_transactions()](#get_transactions) 28 | * [get_traded_picks()](#get_traded_picks) 29 | * [get_all_drafts()](#get_all_drafts) 30 | * [get_standings()](#get_standings) 31 | * [get_scoreboards()](#get_scoreboards) 32 | * [get_close_games()](#get_close_games) 33 | * [User](#user) 34 | * [Initialize](#user_initialize) 35 | * [get_user()](#get_user) 36 | * [get_all_leagues()](#get_all_leagues) 37 | * [get_all_drafts()](#get_all_drafts) 38 | * [get_username()](#get_username) 39 | * [get_user_id()](#get_user_id) 40 | * [Stats](#stats) 41 | * [Initialize](#stats_initialize) 42 | * [get_all_stats()](#get_all_stats) 43 | * [get_week_stats()](#get_week_stats) 44 | * [get_all_projections()](#get_all_projections) 45 | * [get_week_projections()](#get_week_projections) 46 | * [get_player_week_score()](#get_player_week_score) 47 | * [Players](#players) 48 | * [Initialize](#players_initialize) 49 | * [get_all_players()](#get_all_players) 50 | * [get_trending_players()](#get_trending_players) 51 | 3. [Notes](#notes) 52 | 4. [Dependecnies](#depends) 53 | 5. [License](#license) 54 | 55 | 56 | # Install 57 | ~~~ 58 | pip install sleeper-api-wrapper 59 | ~~~ 60 | 61 | 62 | # Usage 63 | There are five objects that get data from the Sleeper API specified below. Most of them are intuitive based on the Sleeper Api docs. 64 | 65 | 66 | 67 | ## League 68 | 69 | 70 | ### Initiaize 71 | ~~~ 72 | from sleeper_wrapper import League 73 | 74 | league = League(league_id) 75 | ~~~ 76 | - league_id: (str)The id of your sleeper league 77 | 78 | 79 | ### League.get_league() 80 | Gets data for the league that was specified when the League object was initialized. Data returned looks like: https://docs.sleeper.app/#get-a-specific-league 81 | 82 | 83 | ### League.get_rosters() 84 | Gets all of the rosters in the league. Data returned looks like: https://docs.sleeper.app/#getting-rosters-in-a-league 85 | 86 | 87 | ### League.get_users() 88 | Gets all of the users in the league. Data returned looks like: https://docs.sleeper.app/#getting-users-in-a-league 89 | 90 | 91 | ### League.get_matchups(week) 92 | Gets all of the users in the league. Data returned looks like: https://docs.sleeper.app/#getting-matchups-in-a-league 93 | 94 | - week:(int or string) week of the matchups to be returned. 95 | 96 | 97 | ### League.get_playoff_winners_bracket() 98 | Gets the playoff winners bracket for the league. Data returned looks like: https://docs.sleeper.app/#getting-the-playoff-bracket 99 | 100 | 101 | ### League.get_playoff_losers_bracket() 102 | Gets the playoff losers bracket for the league. Data returned looks like: https://docs.sleeper.app/#getting-the-playoff-bracket 103 | 104 | 105 | ### League.get_transactions(week) 106 | Gets all of the transactions data in the league. Data returned looks like: https://docs.sleeper.app/#get-transactions 107 | 108 | - week:(int or str) week of the matchups to be returned. 109 | 110 | 111 | ### League.get_traded_picks() 112 | Gets all of the traded picks in the league. Data returned looks like: https://docs.sleeper.app/#get-traded-picks 113 | 114 | 115 | ### League.get_all_drafts() 116 | Gets all of the draft data in the league. Data returned looks like: https://docs.sleeper.app/#get-all-drafts-for-a-league 117 | 118 | 119 | ### League.get_standings(rosters, users) 120 | Gets the standings in a league. Returns a list of the standings in order of most wins to least wins. 121 | - rosters: (list)The data returned by the get_rosters() method. 122 | - users: (list)The data returned by the get_standings() method. 123 | 124 | Data returned looks like: 125 | 126 | ~~~ 127 | [(username, number_of_wins, number_of_losses, total_points), (username, number_of_wins, number_of_losses, total_points),...] 128 | ~~~ 129 | - types: username(str), number_of_wins(int), number_of_losses(int), total_points(int) 130 | - "username" could be None if a user does not have a username. 131 | 132 | Example usage: 133 | 134 | ~~~ 135 | league = League(league_id) 136 | rosters = league.get_rosters() 137 | users = league.get_users() 138 | standings = league.get_standings(rosters,users) 139 | ~~~ 140 | 141 | 142 | ### League.get_scoreboards(rosters, matchups, users, score_type, week) 143 | Gets the scoreboards of the league. Returns a dict of league mathups and scores. 144 | - rosters: (list)The data returned by the get_rosters() method. 145 | - matchups: (list)The data returned by the get_mathcups() method. 146 | - users: (list)The data returned by the get_standings() method. 147 | - score_type: (string) either "pts_std", "pts_half_ppr", or "pts_ppr". 148 | - week: (int) week 149 | 150 | Data returned looks like: 151 | 152 | ~~~ 153 | {matchup_id:[(team_name,score), (team_name, score)], matchup_id:[(team_name,score), (team_name, score)], ... } 154 | ~~~ 155 | - types: matchup_id(int), team_name(str), score(float) 156 | 157 | Example usage: 158 | 159 | ~~~ 160 | league = League(league_id) 161 | matchups = league.get_matchups(11) 162 | users = league.get_users() 163 | rosters = league.get_rosters() 164 | scoreboards = league.get_scoreboards(rosters, matchups, users) 165 | ~~~ 166 | 167 | ### League.get_close_games(scoreboards, close_num) 168 | Gets all of the close games in a league. Returns a dict. 169 | - scoreboards: (dict)The data returned by the get_scoreboards() method. 170 | - close_num: (int)How close the games need to be considered a close game. For example, if the close num is 5, the data returned would only include matchups that are within 5 points of each other. 171 | 172 | Data returned looks like: 173 | 174 | ~~~ 175 | {matchup_id:[(team_name,score), (team_name, score)], matchup_id:[(team_name,score), (team_name, score)], ... } 176 | ~~~ 177 | - types: matchup_id(int), team_name(str), score(float) 178 | 179 | Example usage: 180 | 181 | ~~~ 182 | league = League(league_id) 183 | matchups = league.get_matchups(11) 184 | users = league.get_users() 185 | rosters = league.get_rosters() 186 | scoreboards = league.get_scoreboards(rosters, matchups, users) 187 | close_games = league.get_close_games(scoreboards, 10) 188 | ~~~ 189 | 190 | ## User 191 | 192 | 193 | ### Initiaize 194 | ~~~ 195 | from sleeper_wrapper import User 196 | 197 | user = User(user_id) 198 | ~~~ 199 | - user_id: (str)The id of a user. It can also be a username. 200 | 201 | 202 | ### User.get_user() 203 | Gets data for the user that was specified by the user_id or username when the User object was initialized. Data returned looks like: https://docs.sleeper.app/#user 204 | 205 | 206 | ### User.get_all_leagues(sport, season) 207 | Gets the data of all of the leagues that a user belongs to. Data returned looks like: https://docs.sleeper.app/#get-all-leagues-for-user 208 | 209 | - sport: (str)The sport of the leagues. Currently, it can ony be "nfl". 210 | - season: (int or str)The season of the leagues. ex. 2018,2019, etc. 211 | 212 | 213 | ### User.get_all_drafts(sport, season) 214 | Gets the data of all of the drafts of a user in the specified season. Data returned looks like: https://docs.sleeper.app/#get-all-drafts-for-user 215 | 216 | - sport: (str)The sport of the leagues. Currently, it can ony be "nfl". 217 | - season: (int or str)The season of the leagues. ex. 2018,2019, etc. 218 | 219 | 220 | ### User.get_username() 221 | Returns the username of the User. This can be useful if the User was initialized with a user_id. 222 | 223 | 224 | ### User.get_user_id() 225 | Returns the user_id of the User. This can be useful if the User was initialized with a username. 226 | 227 | 228 | ## Stats 229 | 230 | 231 | ### Initiaize 232 | ~~~ 233 | from sleeper_wrapper import Stats 234 | 235 | stats = Stats() 236 | ~~~ 237 | 238 | ### Stats.get_all_stats(season_type, season) 239 | Gets all of the stats in a season. Data returned looks like: https://docs.sleeper.app/#stats-and-projections 240 | 241 | - season_type: (str) The type of the season. Supports "regular", "pre", "post". 242 | - season: (int or str) The season of the leagues. ex. 2018,2019, etc. 243 | 244 | 245 | ### Stats.get_week_stats(season_type, season, week) 246 | Gets all of the stats for a specific week in a season. Data returned looks like: https://docs.sleeper.app/#stats-and-projections 247 | 248 | - season_type: (str) The type of the season. Supports "regular", "pre", "post". 249 | - season: (int or str) The season of the leagues. ex. 2018,2019, etc. 250 | - week: (int or str) The week of the stats to get. 251 | 252 | 253 | ### Stats.get_all_projections(season_type, season) 254 | Gets all of the projections in a season. Data returned looks like: https://docs.sleeper.app/#stats-and-projections 255 | 256 | - season_type: (str) The type of the season. Supports "regular", "pre", "post". 257 | - season: (int or str) The season of the leagues. ex. 2018,2019, etc. 258 | 259 | 260 | ### Stats.get_week_projections(season_type, season, week) 261 | Gets all of the projections for a specific week in a season. Data returned looks like: https://docs.sleeper.app/#stats-and-projections 262 | 263 | - season_type: (str) The type of the season. Supports "regular", "pre", "post". 264 | - season: (int or str) The season of the leagues. ex. 2018,2019, etc. 265 | - week: (int or str) The week of the stats to get. 266 | 267 | 268 | ### Stats.get_player_week_score(week_stats, player_id) 269 | Gets the player score of a specified week. 270 | 271 | - week_stats: (dict) The result of the method get_week_stats(). 272 | - player_id: (str) The player_id of the player to get the stats of. ex. 2018,2019, etc. 273 | 274 | Data returned looks like: 275 | ~~~ 276 | {'pts_ppr':score_float, 'pts_std': score_float, 'pts_half_ppr': score_float} 277 | ~~~ 278 | - types: score_float(float) 279 | - If the score is not available for a format, the value will be None. 280 | 281 | Example usage: 282 | 283 | ~~~ 284 | stats = Stats() 285 | week_stats = stats.get_week_stats("regular",2018, 5) 286 | score = stats.get_player_week_score(week_stats, "DET") 287 | ~~~ 288 | 289 | ## Players 290 | 291 | 292 | ### Initiaize 293 | ~~~ 294 | from sleeper_wrapper import Players 295 | 296 | players = Players() 297 | ~~~ 298 | 299 | ### Players.get_all_players() 300 | Gets all of the players in fantasy football. Data returned looks like: https://docs.sleeper.app/#fetch-all-players 301 | 302 | 303 | ### Players.get_trending_players(sport, add_drop, hours, limit) 304 | Gets all of the players in fantasy football. Data returned looks like: https://docs.sleeper.app/#trending-players 305 | 306 | - sport: (str) The sport to get. Supports only "nfl" right now. 307 | - add_drop: (str) Either "add" or "drop". 308 | - hours: (int or str) Number of hours to look back. Default is 24 hours. 309 | - limit: (int or str) Number of results you want. Default is 25. 310 | 311 | 312 | # Notes 313 | This package is intended to be used by Python version 3.5 and higher. There might be some wacky results for previous versions. 314 | 315 | 316 | # Dependancies 317 | 318 | [requests](https://github.com/kennethreitz/requests) 319 | - Used for all http requests in sleeper_wrapper 320 | 321 | [pytest](https://github.com/pytest-dev/pytest) 322 | - Used for all testing in sleeper_wrapper 323 | 324 | 325 | # License 326 | This project is licensed under the terms of the MIT license. 327 | --------------------------------------------------------------------------------