├── .github
└── workflows
│ └── codeql-analysis.yml
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── CONTRIBUTORS.md
├── LICENSE.md
├── README.md
├── docs
├── drafts.md
├── league.md
├── players.md
├── stats.md
└── user.md
├── pyproject.toml
├── renovate.json
├── requirements.txt
├── sleeper_wrapper
├── __init__.py
├── base_api.py
├── drafts.py
├── league.py
├── players.py
├── stats.py
└── user.py
└── tests
├── __init__.py
├── test_drafts.py
├── test_league.py
├── test_players.py
├── test_stats.py
└── test_user.py
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ master ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ master ]
20 | schedule:
21 | - cron: '26 16 * * 0'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'python' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37 | # Learn more about CodeQL language support at https://git.io/codeql-language-support
38 |
39 | steps:
40 | - name: Checkout repository
41 | uses: actions/checkout@v4
42 |
43 | # Initializes the CodeQL tools for scanning.
44 | - name: Initialize CodeQL
45 | uses: github/codeql-action/init@v1
46 | with:
47 | languages: ${{ matrix.language }}
48 | # If you wish to specify custom queries, you can do so here or in a config file.
49 | # By default, queries listed here will override any specified in a config file.
50 | # Prefix the list here with "+" to use these queries and those in the config file.
51 | # queries: ./path/to/local/query, your-org/your-repo/queries@main
52 |
53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
54 | # If this step fails, then you should remove it and run the build manually (see below)
55 | - name: Autobuild
56 | uses: github/codeql-action/autobuild@v1
57 |
58 | # ℹ️ Command-line programs to run using the OS shell.
59 | # 📚 https://git.io/JvXDl
60 |
61 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
62 | # and modify them (or add more) to build your code if your project
63 | # uses a compiled language
64 |
65 | #- run: |
66 | # make bootstrap
67 | # make release
68 |
69 | - name: Perform CodeQL Analysis
70 | uses: github/codeql-action/analyze@v1
71 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.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
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/CONTRIBUTORS.md:
--------------------------------------------------------------------------------
1 | sleeper-api-wrapper contributors
2 | ============================================
3 | [Daniel Song](https://github.com/dtsong)
4 | - Current Maintainer
5 |
6 | [Swapnik Katkoori](https://github.com/SwapnikKatkoori)
7 |
8 | - Original Author and Maintainer
9 | - Initial code and documentation
10 |
11 | [Alex Hawkins](https://github.com/AlexHawkins1)
12 | - Added losses data to the data returned by the get_standings() method.
13 | - Updated documentation
14 |
15 | [scipio314](https://github.com/scipio314)
16 | - Fixed KeyError in the get_team_score() method.
17 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | 
3 | 
4 | # sleeper-api-wrapper
5 | A Python API wrapper for Sleeper Fantasy Sports, as well as tools to simplify data received. It makes all endpoints found in the Sleeper API docs: https://docs.sleeper.app/ available and turns the JSON response received into Python types for easy usage.
6 |
7 | Ownership was transferred from @SwapnikKatkoori to @dtsong in March 2022 to continue efforts.
8 | Original Repository: https://github.com/SwapnikKatkoori/sleeper-api-wrapper
9 |
10 | # Table of Contents
11 | 1. [Project Roadmap](#roadmap)
12 | 2. [Installation](#install)
13 | 3. [Documentation](#documentation)
14 | 4. [Notes](#notes)
15 | 5. [Dependencies](#depends)
16 | 6. [License](#license)
17 |
18 |
19 | # Project Roadmap
20 | * Establish solid CICD practices with automated testing and validation of pull requests via GitHub Actions
21 | * Ensure libraries are up to date and secure.
22 | * Update endpoints and logic with the current Sleeper API docs
23 | * Investigate performance optimization (effort, implementation, etc)
24 |
25 | Want to help? Send me a message to @dtsong
26 |
27 |
28 | # Install
29 | ```
30 | pip install sleeper-api-wrapper
31 | ```
32 |
33 |
34 | # Documentation
35 | There are five objects in the package that get data from the Sleeper API. Most of them are intuitive based on the [Sleeper API docs](https://docs.sleeper.com/), but full documentation for the Python objects and their methods can be found in the [`docs` folder](https://github.com/dtsong/sleeper-api-wrapper/tree/master/docs). There are some bespoke methods for transforming the data into more useful structures in addition to the methods that directly call the API.
36 |
37 |
38 | # Notes
39 | This package is intended to be used by Python version 3.8 and higher. There might be some wacky results for previous versions.
40 |
41 |
42 | # Dependencies
43 |
44 | [requests](https://github.com/kennethreitz/requests)
45 | - Used for all http requests in sleeper_wrapper
46 |
47 | [pytest](https://github.com/pytest-dev/pytest)
48 | - Used for all testing in sleeper_wrapper
49 |
50 |
51 | # License
52 | This project is licensed under the terms of the MIT license.
53 |
--------------------------------------------------------------------------------
/docs/drafts.md:
--------------------------------------------------------------------------------
1 | # Drafts
2 | `sleeper_wrapper.Drafts(draft_id)`
3 |
4 | Instantiating a `Drafts` object will allow interaction with Sleeper's [Drafts endpoint](https://docs.sleeper.com/#drafts) by pulling data for the draft specified by the `draft_id`. Examples for how the data is structured for methods hitting the API directly may be found in their documentation for the endpoint.
5 |
6 | ## Attributes
7 | `draft_id` _(Union[int, str])_: The Sleeper ID for the draft. May be provided as a string or int.
8 |
9 | ## Methods
10 | `get_specific_draft`(): Returns the draft's data, such as draft settings, start time, league information, and order. It does not include the picks themselves.
11 |
12 | `get_all_picks`(): Returns all the picks in the specified draft.
13 |
14 | `get_traded_picks`(): Returns all the traded picks in the specified draft.
15 |
16 | ## Examples
17 | ```
18 | from sleeper_wrapper import Drafts
19 |
20 | drafts = Drafts(draft_id="992218427449999361")
21 | my_draft = drafts.get_specific_draft()
22 | all_picks = drafts.get_all_picks()
23 | ```
24 |
--------------------------------------------------------------------------------
/docs/league.md:
--------------------------------------------------------------------------------
1 | # League
2 | `sleeper_wrapper.League(league_id)`
3 |
4 | Instantiating a `League` object will allow interaction with Sleeper's [Leagues endpoint](https://docs.sleeper.com/#leagues) by pulling data for the league specified by the `league_id`. Examples for how the data is structured for methods hitting the API directly may be found in their documentation for the endpoint.
5 |
6 |
7 | ## Attributes
8 | `league_id` _(Union[int, str])_: The Sleeper ID for the league. May be provided as a string or int.
9 |
10 | ## Methods
11 | `get_league()`: Returns the league's data.
12 |
13 | `get_rosters()`: Retrieves the league's rosters.
14 |
15 | `get_users()`: Retrieves the league's users.
16 |
17 | `get_matchups(week)`: Retrieves the league's matchups for the given week.
18 |
19 | `get_playoff_winners_bracket()`: Retrieves the winner's playoff bracket.
20 |
21 | `get_playoff_losers_bracket()`: Retrieves the loser's playoff bracket.
22 |
23 | `get_transactions(week)`: Retrieves all of a league's transactions for the given week.
24 |
25 | `get_trades(week)`: Retrieves the league's trades for the given week.
26 |
27 | `get_waivers(week)`: Retrieves the league's waiver transactions for the given week.
28 |
29 | `get_free_agents(week)`: Retrieves the league's free agent transactions for the given week.
30 |
31 | `get_traded_picks()`: Retrieves the league's traded draft picks.
32 |
33 | `get_all_drafts()`: Retrieves all of a league's drafts. This will typically return only one draft.
34 |
35 | `map_users_to_team_name(users)`: Creates and returns a mapping from user ID to team name.
36 |
37 | `get_standings(rosters, users)`: Creates and returns standings based on the team's wins, losses, and ties.
38 |
39 | `map_rosterid_to_ownerid(rosters)`: Creates and returns a mapping from roster ID to owner ID.
40 |
41 | `get_scoreboards(rosters, matchups, users, score_type, season, week)`: Returns the team names and scores from each matchup.
42 |
43 | Uses the provided information about the league to create a scoreboard
44 | for the given week. It pulls data from the rosters and users to find
45 | the team name and then pulls the team's score. It does not currently
46 | support leagues with custom scoring options and relies on the `Stats()`
47 | class, which is no longer officially documented by Sleeper.
48 |
49 | `get_close_games(scoreboards, close_num)`: Returns scoreboard's games where final margin is beneath given number.
50 |
51 | `get_team_score(starters, score_type, season, week)`: Retrieves a team's scores for a week based on the score type.
52 |
53 | Uses the provided list of starters to pull their stats for that week
54 | with the given score type. It does not currently support leagues with
55 | custom scoring options because it pulls the pre-calculated score based
56 | on score type and does not calculate the score based on the league's
57 | scoring setting. It relies on the `Stats()` class to do this, which is
58 | no longer officially documented by Sleeper.
59 |
60 | `empty_roster_spots(user_id)`: Returns the number of empty roster spots on a user's team.
61 |
62 | `get_league_name()`: Returns name of league.
63 |
64 |
65 | ## Examples
66 | ```
67 | from sleeper_wrapper import League
68 |
69 | # creates the league object and stores its basic data
70 | league = League(league_id)
71 | rosters = league.get_rosters()
72 | users = league.get_users()
73 |
74 | # gets the matchups for the first week
75 | matchups = league.get_matchups(week=1)
76 |
77 | # retrieves the standings and returns them with user information
78 | standings = league.get_standings(rosters=rosters, users=users)
79 |
80 | # retrieves the scoreboard for the given week and returns it with user information
81 | scoreboards = league.get_scoreboards(rosters=rosters, matchups=matchups, users=users, score_type="pts_std", season=2023, week=1)
82 | ```
--------------------------------------------------------------------------------
/docs/players.md:
--------------------------------------------------------------------------------
1 | # Players
2 | `sleeper_wrapper.Players()`
3 |
4 | Instantiating a `Players` object will allow interaction with Sleeper's [Players endpoint](https://docs.sleeper.com/#players) by pulling data on the players. Examples for how the data is structured for methods hitting the API directly may be found in their documentation for the endpoint.
5 |
6 |
7 | ## Methods
8 | `get_all_players(sport)`: Gets all players from Sleeper. Retrieves data pertaining to each player in the Sleeper, including positions, biographical data, height / weight, team, and more.
9 |
10 | > Please use this call sparingly, as it is intended only to be used once per day at most to keep your player IDs updated.
11 | >
12 | > Save the information to your own servers, if possible.
13 |
14 | `get_trending_players(sport, add_drop, hours, limit)`: Gets trending players from Sleeper. Retrieves the player ID and number of adds / drops for that player during the specified lookback hours.
15 |
16 | > If you use this trending data, please attribute Sleeper.
17 | > Copy the code below to embed it in your app:
18 | >
19 | > \
20 |
21 |
22 | ## Examples
23 | ```
24 | from sleeper_wrapper import Players
25 |
26 | players = Players()
27 |
28 | # gets all NFL players in the Sleeper system
29 | all_players = players.get_all_players(sport="nfl")
30 |
31 | # gets the top 10 added NFL players in the last 24 hours
32 | trending_players = players.get_trending_players(sport="nfl", add_drop="add", hours=24, limit=10)
33 | ```
--------------------------------------------------------------------------------
/docs/stats.md:
--------------------------------------------------------------------------------
1 | # Stats
2 | `sleeper_wrapper.Stats()`
3 |
4 | Instantiating a `Stats` object will allow interaction with Sleeper's Stats endpoint and retrieve stats and projections for Sleeper, though it is no longer officially documented and supported. Both stats and projections include box score and detailed stats as well as rollups to fantasy scores in standard scoring formats (standard, ppr, half ppr).
5 |
6 |
7 | ## Methods
8 | `get_all_stats(season_type, season)`: Retrieves all statistics for the given season. It supports detailed data going back until 2010 before only providing ranks for the various scoring formats. The detailed data contains information such as passing yards per attempt, field goal makes and misses by 10 yard buckets, snaps played, red zone statistics, and more.
9 |
10 | `get_week_stats(season_type, season, week)`: Retrieves all statistics for the given season and week. It supports detailed data going back until 2010 before only providing ranks for the various scoring formats. The detailed data contains information such as passing yards per attempt, field goal makes and misses by 10 yard buckets, snaps played, red zone statistics, and more.
11 |
12 | `get_all_projections(season_type, season)`: Retrieves all projections for the given season. It supports data going back until 2018 and contains information such as passing yards per attempt, field goal makes and misses by 10 yard buckets, ADP, games played, and more.
13 |
14 | `get_week_projections(season_type, season, week)`: Retrieves all projections for the given season and week. It supports data going back until 2018 and contains information such as passing yards per attempt, field goal makes and misses by 10 yard buckets, ADP, games played, and more.
15 |
16 | `get_player_week_stats(stats, player_id)`: Gets a player's stats or projections from the given dictionary.
17 |
18 | `get_player_week_score(stats, player_id)`: Retrieves a player's points scored for the primary scoring formats (standard, PPR, half PPR).
19 |
20 |
21 | ## Examples
22 | ```
23 | from sleeper_wrapper import Stats
24 |
25 | stats = Stats()
26 |
27 | # pulls all of the stats for week 1 of the 2023 regular season
28 | week_stats = stats.get_week_stats("regular", 2023, 1)
29 |
30 | # retrieves stats for the Detroit defense for the provided week
31 | score = stats.get_player_week_score(week_stats, "DET")
32 | ```
--------------------------------------------------------------------------------
/docs/user.md:
--------------------------------------------------------------------------------
1 | # User
2 | `sleeper_wrapper.User()`
3 |
4 | Instantiating a `User` object will allow interaction with Sleeper's [User endpoint](https://docs.sleeper.com/#user) by pulling data for the user specified by the `user_id`.
5 |
6 |
7 | ## Attributes
8 | `initial_user_input` _(Union[str, int])_: The Sleeper user ID or username for the user. May be provided as a string or an int.
9 |
10 |
11 | ## Methods
12 | `get_user()`: Returns the user's data.
13 |
14 | `get_all_leagues(sport, season)`: Returns every league the user is in for that sport and season.
15 |
16 | `get_all_drafts(sport, season)`: Returns every draft the user is in for that sport and season.
17 |
18 | `get_username()`: Retrieves username.
19 |
20 | `get_user_id()`: Retrieves user_id.
21 |
22 | `get_display_name()`: Retrieves display name.
23 |
24 |
25 | ## Examples
26 | ```
27 | from sleeper_wrapper import User
28 |
29 | user = User("foobar")
30 |
31 | # get all the user's leagues for the 2023 NFL season
32 | user_leagues = user.get_all_leagues(sport="nfl", season=2023)
33 |
34 | # get all the user's drafts for the 2023 NFL season
35 | user_drafts = user.get_all_drafts(sport="nfl", season=2023)
36 | ```
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | # pyproject.toml
2 |
3 | [tool.poetry]
4 | name = "sleeper-api-wrapper"
5 | packages = [ { include = "sleeper_wrapper" } ]
6 | version = "1.1.0"
7 | description = "A Python API wrapper for Sleeper Fantasy sports, as well as tools to simplify received data."
8 | authors = ["Dan Song, Ford Higgins "]
9 | readme = "README.md"
10 | license = "MIT"
11 | homepage = "https://github.com/dtsong/sleeper-api-wrapper"
12 | repository = "https://github.com/dtsong/sleeper-api-wrapper"
13 | documentation = "https://github.com/dtsong/sleeper-api-wrapper/tree/master/docs"
14 | keywords = ["fantasy football", "fantasy sports", "sports", "sleeper fantasy", "sleeper"]
15 | classifiers = [
16 | "License :: OSI Approved :: MIT License",
17 | "Programming Language :: Python",
18 | "Programming Language :: Python :: 3",
19 | ]
20 |
21 | [tool.poetry.dependencies]
22 | python = "^3.9"
23 | requests = "^2.22.0"
24 |
25 | [build-system]
26 | requires = ["poetry-core"]
27 | build-backend = "poetry.core.masonry.api"
28 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": [
4 | "config:base"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | atomicwrites==1.4.1
2 | attrs==23.1.0
3 | certifi==2023.7.22
4 | chardet==3.0.4
5 | charset-normalizer==2.1.1
6 | idna==2.10
7 | importlib-metadata==4.13.0
8 | more-itertools==8.14.0
9 | packaging==21.3
10 | pluggy==0.13.1
11 | py==1.11.0
12 | pyparsing==3.0.7
13 | pytest==4.6.11
14 | requests>=2.22.0
15 | six==1.16.0
16 | urllib3==1.26.18
17 | wcwidth==0.2.8
18 | zipp==3.17.0
19 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/sleeper_wrapper/base_api.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 |
5 | class BaseApi():
6 | def _call(self, url: str) -> dict:
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/drafts.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from .base_api import BaseApi
4 |
5 | class Drafts(BaseApi):
6 | """The data associated with a given Sleeper draft.
7 |
8 | Attributes:
9 | draft_id: Union[str, int]
10 | The Sleeper ID for the draft. May be provided as a string or int.
11 | """
12 |
13 | def __init__(self, draft_id: Union[str, int]) -> None:
14 | """Initializes the instance based on draft ID.
15 |
16 | Args:
17 | draft_id: Union[str, int]
18 | The Sleeper ID for the draft. May be provided as a string or int.
19 | """
20 | self.draft_id = draft_id
21 | self._base_url = "https://api.sleeper.app/v1/draft/{}".format(self.draft_id)
22 |
23 | def get_specific_draft(self) -> dict:
24 | """Returns the draft's data."""
25 | return self._call(self._base_url)
26 |
27 | def get_all_picks(self) -> list:
28 | """Returns all the picks in the specified draft."""
29 | return self._call("{}/{}".format(self._base_url,"picks"))
30 |
31 | def get_traded_picks(self) -> list:
32 | """Returns all the traded picks in the specified draft."""
33 | return self._call("{}/{}".format(self._base_url,"traded_picks"))
34 |
--------------------------------------------------------------------------------
/sleeper_wrapper/league.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from .base_api import BaseApi
4 | from .stats import Stats
5 |
6 | class League(BaseApi):
7 | """The data associated with the given Sleeper league.
8 |
9 | Can retrieve data for the league such as matchups, transactions, brackets,
10 | drafts, scoreboards, and more. Some of these are simple calls to the
11 | Sleeper API while others add on a layer of data transformation or include
12 | multiple calls.
13 |
14 | Attributes:
15 | league_id: Union[str, int]
16 | The Sleeper ID for the league. May be provided as a string or int.
17 | """
18 |
19 | def __init__(self, league_id: Union[str, int]) -> None:
20 | """Initializes the instance based on league ID.
21 |
22 | Args:
23 | league_id: Union[str, int]
24 | Defines the league ID for data retrieval.
25 | """
26 | self.league_id = league_id
27 | self._base_url = "https://api.sleeper.app/v1/league/{}".format(self.league_id)
28 | self._league = self._call(self._base_url)
29 |
30 | def get_league(self) -> dict:
31 | """Returns the league data."""
32 | return self._league
33 |
34 | def get_rosters(self) -> list:
35 | """Retrieves the league's rosters."""
36 | return self._call("{}/{}".format(self._base_url,"rosters"))
37 |
38 | def get_users(self) -> list:
39 | """Retrieves the league's users."""
40 | return self._call("{}/{}".format(self._base_url,"users"))
41 |
42 | def get_matchups(self, week: Union[str, int]) -> list:
43 | """Retrieves the league's matchups for the given week."""
44 | return self._call("{}/{}/{}".format(self._base_url,"matchups", week))
45 |
46 | def get_playoff_winners_bracket(self) -> list:
47 | """Retrieves the winner's playoff bracket."""
48 | return self._call("{}/{}".format(self._base_url,"winners_bracket"))
49 |
50 | def get_playoff_losers_bracket(self) -> list:
51 | """Retrieves the loser's playoff bracket."""
52 | return self._call("{}/{}".format(self._base_url,"losers_bracket"))
53 |
54 | def get_transactions(self, week: Union[str, int]) -> list:
55 | """Retrieves all of a league's transactions for the given week."""
56 | return self._call("{}/{}/{}".format(self._base_url,"transactions", week))
57 |
58 | def get_trades(self, week: Union[str, int]) -> list:
59 | """Retrieves the league's trades for the given week."""
60 | transactions = self.get_transactions(week)
61 | return [t for t in transactions if t["type"] == "trade"]
62 |
63 | def get_waivers(self, week: Union[str, int]) -> list:
64 | """Retrieves the league's waiver transactions for the given week."""
65 | transactions = self.get_transactions(week)
66 | return [t for t in transactions if t["type"] == "waiver"]
67 |
68 | def get_free_agents(self, week: Union[str, int]) -> list:
69 | """Retrieves the league's free agent transactions for the given week."""
70 | transactions = self.get_transactions(week)
71 | return [t for t in transactions if t["type"] == "free_agent"]
72 |
73 | def get_traded_picks(self) -> list:
74 | """Retrieves the league's traded draft picks."""
75 | return self._call("{}/{}".format(self._base_url,"traded_picks"))
76 |
77 | def get_all_drafts(self) -> list:
78 | """Retrieves all of a league's drafts.
79 |
80 | This will typically return only one draft.
81 | """
82 | return self._call("{}/{}".format(self._base_url, "drafts"))
83 |
84 | def map_users_to_team_name(self, users: list) -> dict:
85 | """Creates a mapping from user ID to team name.
86 |
87 | Args:
88 | users: list
89 | List of user IDs for the league.
90 |
91 | Returns:
92 | A dict mapping the user ID to team name for each user / team
93 | combination in the league.
94 | """
95 | users_dict = {}
96 |
97 | # Maps the user_id to team name for easy lookup
98 | for user in users:
99 | try:
100 | users_dict[user["user_id"]] = user["metadata"]["team_name"]
101 | except:
102 | users_dict[user["user_id"]] = user["display_name"]
103 | return users_dict
104 |
105 | def get_standings(self, rosters: list, users: list) -> dict:
106 | """Creates standings based on the team's wins, losses, and ties.
107 |
108 | Args:
109 | rosters:
110 | List of rosters for the league.
111 | users: list
112 | List of user IDs for the league.
113 |
114 | Returns:
115 | List of tuples (team_name, wins, losses, points) sorted by wins in
116 | descending order.
117 | """
118 | users_dict = self.map_users_to_team_name(users)
119 |
120 | roster_standings_list = []
121 | for roster in rosters:
122 | wins = roster["settings"]["wins"]
123 | points = roster["settings"]["fpts"]
124 | name = roster["owner_id"]
125 | losses = roster["settings"]["losses"]
126 | if name is not None:
127 | roster_tuple = (wins, losses, points, users_dict[name])
128 | else:
129 | roster_tuple = (wins, losses, points, None)
130 | roster_standings_list.append(roster_tuple)
131 |
132 | roster_standings_list.sort(reverse = 1)
133 |
134 | clean_standings_list = []
135 | for item in roster_standings_list:
136 | clean_standings_list.append((item[3], str(item[0]), str(item[1]), str(item[2])))
137 |
138 | return clean_standings_list
139 |
140 | def map_rosterid_to_ownerid(self, rosters: list) -> dict:
141 | """Creates a mapping from roster ID to owner ID.
142 |
143 | Args:
144 | rosters: list
145 | List of rosters for the league.
146 |
147 | Returns:
148 | A dict mapping the roster ID to owner ID for each roster / owner
149 | combination in the league.
150 | """
151 | result_dict = {}
152 | for roster in rosters:
153 | roster_id = roster["roster_id"]
154 | owner_id = roster["owner_id"]
155 | result_dict[roster_id] = owner_id
156 |
157 | return result_dict
158 |
159 | def get_scoreboards(self, rosters: list, matchups: list, users: list, score_type: str, season: Union[str, int], week: Union[str, int]) -> Union[dict, None]:
160 | """Returns the team names and scores from each matchup.
161 |
162 | Uses the provided information about the league to create a scoreboard
163 | for the given week. It pulls data from the rosters and users to find
164 | the team name and then pulls the team's score. It does not currently
165 | support leagues with custom scoring options and relies on the `Stats()`
166 | class, which is no longer officially documented by Sleeper.
167 |
168 | Args:
169 | rosters: list
170 | List of rosters for the league.
171 | matchups: list
172 | List of matchups for that week.
173 | users: list
174 | List of users for the league.
175 | score_type: str
176 | Scoring type for the league, eg "pts_std", "pts_ppr", or "pts_half_ppr"
177 | season: Union[str, int]
178 | The season to retrieve the scoreboards. May be provided as either a
179 | str or an int.
180 | week: Union[str, int]
181 | The week to retrieve the scoreboards. May be provided as either a
182 | str or an int.
183 |
184 | Returns:
185 | A dict with the matchup ID as key and the corresponding teams' names
186 | and scores for that matchup.
187 | """
188 | roster_id_dict = self.map_rosterid_to_ownerid(rosters)
189 |
190 | if len(matchups) == 0:
191 | return None
192 |
193 | # Get the users to team name stats
194 | users_dict = self.map_users_to_team_name(users)
195 |
196 | # Map roster_id to points
197 | scoreboards_dict = {}
198 |
199 | for team in matchups:
200 | matchup_id = team["matchup_id"]
201 | current_roster_id = team["roster_id"]
202 | owner_id = roster_id_dict[current_roster_id]
203 | if owner_id is not None:
204 | team_name = users_dict[owner_id]
205 | else:
206 | team_name = "Team name not available"
207 |
208 | team_score = self.get_team_score(team["starters"], score_type, season, week)
209 | if team_score is None:
210 | team_score = 0
211 |
212 | team_score_tuple = (team_name, team_score)
213 | if matchup_id not in scoreboards_dict:
214 | scoreboards_dict[matchup_id] = [team_score_tuple]
215 | else:
216 | scoreboards_dict[matchup_id].append(team_score_tuple)
217 | return scoreboards_dict
218 |
219 | def get_close_games(self, scoreboards: list, close_num: float) -> dict:
220 | """Returns scoreboard's games where final margin is beneath given number.
221 |
222 | Args:
223 | scoreboards: list
224 | List of scoreboards, which can be retrieved with the
225 | `get_scoreboards()` method.
226 | close_num: float
227 | The final margin to use as a threshold for determining close games.
228 |
229 | Returns:
230 | A dict of matchups qualifying as close.
231 | """
232 | close_games_dict = {}
233 | for key in scoreboards:
234 | team_one_score = scoreboards[key][0][1]
235 | team_two_score = scoreboards[key][1][1]
236 |
237 | if abs(team_one_score-team_two_score) < close_num:
238 | close_games_dict[key] = scoreboards[key]
239 | return close_games_dict
240 |
241 | def get_team_score(self, starters: list, score_type: str, season: Union[str, int], week: Union[str, int]) -> float:
242 | """Retrieves a team's scores for a week based on the score type.
243 |
244 | Uses the provided list of starters to pull their stats for that week
245 | with the given score type. It does not currently support leagues with
246 | custom scoring options because it pulls the pre-calculated score based
247 | on score type and does not calculate the score based on the league's
248 | scoring setting. It relies on the `Stats()` class to do this, which is
249 | no longer officially documented by Sleeper.
250 |
251 | Args:
252 | starters: list
253 | A list of starters for the team.
254 | score_type: str
255 | Scoring type for the league, eg "pts_std", "pts_ppr", or "pts_half_ppr"
256 | season: Union[str, int]
257 | The season to retrieve the scores. May be provided as either a str
258 | or an int.
259 | week: Union[str, int]
260 | The week to retrieve the scores. May be provided as either a str or
261 | an int.
262 |
263 | Returns:
264 | The total score as a float for the team in that week.
265 | """
266 | total_score = 0
267 | stats = Stats()
268 | week_stats = stats.get_week_stats("regular", season, week)
269 | for starter in starters:
270 | if stats.get_player_week_stats(week_stats, starter) is not None:
271 | try:
272 | total_score += stats.get_player_week_stats(week_stats, starter)[score_type]
273 | except KeyError:
274 | total_score += 0
275 |
276 | return total_score
277 |
278 | def empty_roster_spots(self, user_id: Union[str, int]) -> Union[int, None]:
279 | """Returns the number of empty roster spots on a user's team.
280 |
281 | Args:
282 | user_id: Union[str, int]
283 | The user's ID to check for empty roster spots.
284 |
285 | Returns:
286 | The number of empty roster spots assuming the user was found. Otherwise
287 | returns `None`.
288 | """
289 | # get size of maximum roster
290 | max_roster_size = len(self._league["roster_positions"])
291 |
292 | # finds roster of user, returns max size - size of user roster
293 | rosters = self.get_rosters()
294 | for roster in rosters:
295 | if user_id == roster["owner_id"]:
296 | return max_roster_size - len(roster["players"])
297 |
298 | # returns None if user was not found
299 | return None
300 |
301 |
302 | def get_league_name(self) -> str:
303 | """Returns name of league."""
304 | return self._league["name"]
305 |
306 | def get_negative_scores(self, week: Union[str, int]) -> None:
307 | pass
308 |
309 | def get_rosters_players(self) -> None:
310 | pass
311 |
--------------------------------------------------------------------------------
/sleeper_wrapper/players.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from .base_api import BaseApi
4 |
5 | logging.basicConfig(level=logging.INFO)
6 |
7 | class Players(BaseApi):
8 | """Retrieves player data from Sleeper."""
9 |
10 | def __init__(self):
11 | pass
12 |
13 | def get_all_players(self, sport: str = "nfl") -> dict:
14 | """Gets all players from Sleeper.
15 |
16 | Retrieves data pertaining to each player in the Sleeper, including
17 | positions, biographical data, height / weight, team, and more.
18 |
19 | Args:
20 | sport: str
21 | The sport to retrieve the players. Options include "nfl",
22 | "nba", and "lcs".
23 |
24 | Returns:
25 | A dict of dicts where the keys are the player IDs and the values
26 | contain all of the player information.
27 | """
28 |
29 | message = """Please use this call sparingly, as it is intended only to be used once per day at most to keep your player IDs updated.
30 |
31 | Save the information to your own servers, if possible.
32 | """
33 | logging.info(message)
34 | return self._call("https://api.sleeper.app/v1/players/nfl")
35 |
36 | def get_trending_players(self, sport: str, add_drop: str = "add", hours: int = 24, limit: int = 25) -> list:
37 | """Gets trending players from Sleeper.
38 |
39 | Retrieves the player ID and number of adds / drops for that player
40 | during the specified lookback hours.
41 |
42 | Args:
43 | sport: str
44 | The sport to retrieve the players. Options include "nfl",
45 | "nba", and "lcs".
46 | add_drop: str
47 | Type of action to retreive. Either "add" or "drop".
48 | hours: int
49 | The number of hours to look back.
50 | limit: int
51 | The number of players to retrieve.
52 |
53 | Returns:
54 | A list of dicts containing the player ID and a count of the adds /
55 | drops.
56 | """
57 |
58 |
59 | message = """If you use this trending data, please attribute Sleeper.
60 |
61 | Copy the code below to embed it in your app:
62 |
63 | """
64 | logging.info(message)
65 | return self._call("https://api.sleeper.app/v1/players/{}/trending/{}?lookback_hours={}&limit={}".format(sport, add_drop, hours, limit))
66 |
--------------------------------------------------------------------------------
/sleeper_wrapper/stats.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from typing import Union
3 |
4 | from sleeper_wrapper.base_api import BaseApi
5 |
6 | logging.basicConfig(level=logging.WARN)
7 |
8 | warning_message = "The Stats API is no longer included in Sleeper's documentation, therefore we cannot guarantee that this class will continue working."
9 |
10 | class Stats(BaseApi):
11 | """Retrieves stats and projections from Sleeper's stats provider.
12 |
13 | Can retrieve stats and projections for Sleeper, though it is no longer
14 | officially documented and supported. Both stats and projections include
15 | box score and detailed stats as well as rollups to fantasy scores in
16 | standard scoring formats (standard, ppr, half ppr).
17 | """
18 |
19 | def __init__(self):
20 | """Initializes the instance for getting the stats."""
21 | logging.warning(warning_message)
22 | self._base_url = "https://api.sleeper.app/v1/stats/{}".format("nfl")
23 | self._projections_base_url = "https://api.sleeper.app/v1/projections/{}".format("nfl")
24 |
25 | def get_all_stats(self, season_type: str, season: Union[str, int]) -> dict:
26 | """Retrieves all statistics for the given season.
27 |
28 | It supports detailed data going back until 2010 before only providing
29 | ranks for the various scoring formats. The detailed data contains information
30 | such as passing yards per attempt, field goal makes and misses by 10 yard
31 | buckets, snaps played, red zone statistics, and more.
32 |
33 | Arguments:
34 | season_type: str
35 | The type of season for pulling the stats. Supports "regular", "pre",
36 | and "post".
37 | season: Union[str, int]
38 | The year of the season for pulling the stats.
39 |
40 | Returns:
41 | A dictionary with each player and their statistics for the season.
42 | """
43 | # season_type: "regular" works..."reg", "regular_season", "playoffs", and "preseason" don't seem to work
44 | return self._call("{}/{}/{}".format(self._base_url, season_type, season))
45 |
46 | def get_week_stats(self, season_type: str, season: Union[str, int], week: str) -> dict:
47 | """Retrieves all statistics for the given season and week.
48 |
49 | It supports detailed data going back until 2010 before only providing
50 | ranks for the various scoring formats. The detailed data contains information
51 | such as passing yards per attempt, field goal makes and misses by 10 yard
52 | buckets, snaps played, red zone statistics, and more.
53 |
54 | Arguments:
55 | season_type: str
56 | The type of season for pulling the stats. Supports "regular", "pre",
57 | and "post".
58 | season: Union[str, int]
59 | The year of the season for pulling the stats.
60 | week: Union[str, int]
61 | The week of the season for pulling the stats.
62 |
63 | Returns:
64 | A dictionary with each player and their statistics for the season's week.
65 | """
66 | return self._call("{}/{}/{}/{}".format(self._base_url, season_type, season, week))
67 |
68 | def get_all_projections(self, season_type: str, season: Union[str, int]) -> dict:
69 | """Retrieves all projections for the given season.
70 |
71 | It supports data going back until 2018 and contains information such as
72 | passing yards per attempt, field goal makes and misses by 10 yard buckets,
73 | ADP, games played, and more.
74 |
75 | Arguments:
76 | season_type: str
77 | The type of season for pulling the projections. Supports "regular",
78 | "pre", and "post".
79 | season: Union[str, int]
80 | The year of the season for pulling the projections.
81 |
82 | Returns:
83 | A dictionary with each player and their projections for the year.
84 | """
85 | return self._call("{}/{}/{}".format(self._projections_base_url, season_type, season))
86 |
87 | def get_week_projections(self, season_type: str, season: Union[str, int], week: str) -> dict:
88 | """Retrieves all projections for the given season and week.
89 |
90 | It supports data going back until 2018 and contains information such as
91 | passing yards per attempt, field goal makes and misses by 10 yard buckets,
92 | ADP, games played, and more.
93 |
94 | Arguments:
95 | season_type: str
96 | The type of season for pulling the projections. Supports "regular",
97 | "pre", and "post".
98 | season: Union[str, int]
99 | The year of the season for pulling the projections.
100 | week: Union[str, int]
101 | The week of the season for pulling the projections.
102 |
103 | Returns:
104 | A dictionary with each player and their projections for the year.
105 | """
106 | return self._call("{}/{}/{}/{}".format(self._projections_base_url, season_type, season, week))
107 |
108 | def get_player_week_stats(self, stats: dict, player_id: str) -> Union[dict, None]:
109 | """Gets a player's stats or projections from the given dictionary.
110 |
111 | Arguments:
112 | stats: dict
113 | Either stats or projections returned by the API. Can be for the whole
114 | season or a single week.
115 | player_id: str
116 | The ID for the player of interest.
117 |
118 | Returns:
119 | A dictionary of the player's stats or projections for the time period
120 | associated with the dictionary provided to the function.
121 | """
122 |
123 | return stats.get(player_id, None)
124 |
125 |
126 | def get_player_week_score(self, stats: dict, player_id: str) -> Union[dict, None]:
127 | """Retrieves a player's points scored for the primary scoring formats.
128 |
129 | Arguments:
130 | stats: dict
131 | Either stats or projections returned by the API. Can be for the whole
132 | season or a single week.
133 | player_id: str
134 | The ID for the player of interest.
135 |
136 | Returns:
137 | A dictionary with the points scored for standard, PPR, and half PPR
138 | scoring formats.
139 | """
140 | result_dict = {}
141 | player_stats = stats.get(player_id, None)
142 |
143 | if player_stats:
144 | result_dict["pts_ppr"] = player_stats.get("pts_ppr", None)
145 | result_dict["pts_std"] = player_stats.get("pts_std", None)
146 | result_dict["pts_half_ppr"] = player_stats.get("pts_half_ppr", None)
147 |
148 | return result_dict
149 |
150 |
--------------------------------------------------------------------------------
/sleeper_wrapper/user.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from .base_api import BaseApi
4 |
5 | class User(BaseApi):
6 | """The data associated with a given Sleeper user."""
7 |
8 | def __init__(self, initial_user_input: Union[str, int]) -> None:
9 | """Initializes the instance based on either username or user ID.
10 |
11 | Args:
12 | initial_user_input: Union[str, int]
13 | The Sleeper user ID or username for the user. May be provided as a
14 | string or int.
15 | """
16 | self._base_url = "https://api.sleeper.app/v1/user"
17 | self._user = self._call("{}/{}".format(self._base_url, initial_user_input))
18 | self._username = self._user["username"]
19 | self._user_id = self._user["user_id"]
20 |
21 | def get_user(self) -> dict:
22 | """Returns the user's data."""
23 | return self._user
24 |
25 | def get_all_leagues(self, sport: str, season: Union[str, int]) -> list:
26 | """Returns every league the user is in for that sport and season.
27 |
28 | Args:
29 | sport: str
30 | The sport to retrieve the leagues. Options include "nfl",
31 | "nba", and "lcs".
32 | season: Union[str, int]
33 | The season to retrieve the leagues. May be provided as either a
34 | str or an int.
35 |
36 | Returns:
37 | A list of dicts corresponding to the leagues a user is in. Each entry
38 | will look akin to a specific League().get_league() call.
39 | """
40 | return self._call("{}/{}/{}/{}/{}".format(self._base_url, self._user_id, "leagues", sport, season))
41 |
42 | def get_all_drafts(self, sport: str, season: Union[str, int]) -> list:
43 | """Returns every draft the user is in for that sport and season.
44 |
45 | Args:
46 | sport: str
47 | The sport to retrieve the drafts. Options include "nfl",
48 | "nba", and "lcs".
49 | season: Union[str, int]
50 | The season to retrieve the drafts. May be provided as either a
51 | str or an int.
52 |
53 | Returns:
54 | A list of dicts corresponding to the drafts a user completed.
55 | """
56 | return self._call("{}/{}/{}/{}/{}".format(self._base_url, self._user_id, "drafts", sport, season))
57 |
58 | def get_username(self) -> str:
59 | """Retrieves username."""
60 | return self._username
61 |
62 | def get_user_id(self) -> str:
63 | """Retrieves user_id."""
64 | return self._user_id
65 |
66 | def get_display_name(self) -> str:
67 | """Retrieves display name."""
68 | return self._user["display_name"]
69 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dtsong/sleeper-api-wrapper/83cb09e574a5e32eb2952df56aad3185af90522a/tests/__init__.py
--------------------------------------------------------------------------------
/tests/test_drafts.py:
--------------------------------------------------------------------------------
1 | from sleeper_wrapper import Drafts
2 |
3 | def test_get_specific_draft() -> None:
4 | draft = Drafts(257270643320426496)
5 | specific_draft = draft.get_specific_draft()
6 |
7 | assert isinstance(specific_draft, dict)
8 |
9 | def test_get_all_picks() -> None:
10 | draft = Drafts(257270643320426496)
11 | all_picks = draft.get_all_picks()
12 | first_item = all_picks[0]
13 |
14 | assert isinstance(all_picks, list)
15 | assert isinstance(first_item, dict)
16 |
17 | def test_get_traded_picks() -> None:
18 | draft = Drafts(257270643320426496)
19 | traded_picks = draft.get_traded_picks()
20 |
21 | assert isinstance(traded_picks, list)
22 |
--------------------------------------------------------------------------------
/tests/test_league.py:
--------------------------------------------------------------------------------
1 | from sleeper_wrapper import League
2 |
3 | def test_get_league() -> None:
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() -> None:
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() -> None:
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() -> None:
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() -> None:
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() -> None:
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() -> None:
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_trades() -> None:
70 | """ Tests the get_trades method.
71 | Note: It would be better if we had trades to verify!"""
72 | league = League(355526480094113792)
73 | trades = league.get_trades(4)
74 | assert isinstance(trades, list)
75 | assert len(trades) == 0
76 |
77 | def test_get_waivers() -> None:
78 | """Tests the get_waivers method.
79 | Note: It would be better if we had waivers to verify!"""
80 | league = League(355526480094113792)
81 | waivers = league.get_waivers(4)
82 | assert isinstance(waivers, list)
83 | assert len(waivers) == 0
84 |
85 | def test_get_free_agents() -> None:
86 | """Tests the get_free_agents method.
87 | Note: It would be better if we had free agents to verify!"""
88 | league = League(355526480094113792)
89 | free_agents = league.get_free_agents(4)
90 | assert isinstance(free_agents, list)
91 | assert len(free_agents) == 0
92 |
93 | def test_get_traded_picks() -> None:
94 | """ Tests the get_traded_picks method"""
95 | league = League(355526480094113792)
96 | traded_picks = league.get_traded_picks()
97 | first_item = traded_picks[0]
98 |
99 | assert isinstance(traded_picks, list)
100 | assert isinstance(first_item, dict)
101 |
102 | def test_get_all_drafts() -> None:
103 | league = League(355526480094113792)
104 | drafts = league.get_all_drafts()
105 | first_item = drafts[0]
106 |
107 | assert isinstance(drafts, list)
108 | assert isinstance(first_item, dict)
109 |
110 | def test_get_standings() -> None:
111 | """ Tests the get_standings method"""
112 | league = League(355526480094113792)
113 | rosters = league.get_rosters()
114 | users = league.get_users()
115 | standings = league.get_standings(rosters,users)
116 | first_item = standings[0]
117 |
118 | assert isinstance(first_item, tuple)
119 | assert len(standings)==12
120 |
121 | def test_get_scoreboards() -> None:
122 | """Tests the get_scoreoards method
123 | -Needs more testing after the season starts"""
124 | league = League(442724598706860032)
125 | matchups = league.get_matchups(1)
126 | users = league.get_users()
127 | rosters = league.get_rosters()
128 | scoreboards = league.get_scoreboards(rosters, matchups, users, "pts_half_ppr", 1)
129 | print(scoreboards)
130 | assert isinstance(scoreboards, dict)
131 |
132 | def test_get_close_games() -> None:
133 | """
134 | Tests the get_close_games method
135 | -Notes: Need to test more.
136 | """
137 | league = League(442724598706860032)
138 | matchups = league.get_matchups(1)
139 | users = league.get_users()
140 | rosters = league.get_rosters()
141 | scoreboards = league.get_scoreboards(rosters, matchups, users, "pts_half_ppr", 1)
142 | close_games = league.get_close_games(scoreboards, 10)
143 | assert isinstance(close_games, dict)
144 |
145 | def test_empty_roster_spots() -> None:
146 | """
147 | Tests the empty_roster_spots method
148 |
149 | Assertion 1: ensures that our function returns an integer for all league users (and not None)
150 |
151 | Assertion 2: ensures that our function returns None when an invalid user id is sent
152 | """
153 | league = League(442724598706860032)
154 | users = league.get_users()
155 | rosters = league.get_rosters()
156 | # Assertion 1
157 | for user in users:
158 | user_id = user["user_id"]
159 | for roster in rosters:
160 | if user_id == roster["user_id"]:
161 | assert league.empty_roster_spots(user_id) is not None
162 |
163 | # Assertion 2
164 | assert league.empty_roster_spots(-10000) is None
165 |
166 | def test_get_negative_scores() -> None:
167 | pass
--------------------------------------------------------------------------------
/tests/test_players.py:
--------------------------------------------------------------------------------
1 | from sleeper_wrapper import Players
2 |
3 | def test_get_trending_players() -> None:
4 | players = Players()
5 | added = players.get_trending_players("nfl","add", 1, 4)
6 |
7 | dropped = players.get_trending_players("nfl","drop")
8 |
--------------------------------------------------------------------------------
/tests/test_stats.py:
--------------------------------------------------------------------------------
1 | from sleeper_wrapper import Stats
2 | import pytest
3 |
4 | def test_get_all_stats() -> None:
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() -> None:
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() -> None:
15 | stats = Stats()
16 | projections = stats.get_all_projections("regular", "2019")
17 | assert isinstance(projections, dict)
18 |
19 | def test_get_week_projections() -> None:
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() -> None:
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() -> None:
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 |
--------------------------------------------------------------------------------
/tests/test_user.py:
--------------------------------------------------------------------------------
1 | from sleeper_wrapper import User
2 |
3 | def test_get_user() -> None:
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() -> None:
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() -> None:
22 | user = User("swa")
23 | drafts = user.get_all_drafts("nfl", 2019)
24 | assert isinstance(drafts, list)
25 | assert isinstance(drafts[0], dict)
--------------------------------------------------------------------------------