├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ ├── publish_image.yaml
│ ├── test.yml
│ └── test_image.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── Procfile
├── README.md
├── app.json
├── docker-compose.yml
├── gamedaybot
├── chat
│ ├── discord.py
│ ├── groupme.py
│ └── slack.py
├── espn
│ ├── env_vars.py
│ ├── espn_bot.py
│ ├── functionality.py
│ ├── scheduler.py
│ └── season_recap.py
└── utils
│ └── util.py
├── requirements-test.txt
├── requirements.txt
├── runtime.txt
├── setup.cfg
├── setup.py
└── tests
├── conftest.py
├── dry_run_all_functions.py
├── test_discord.py
├── test_groupme.py
├── test_slack.py
└── test_utils.py
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 |
5 | ---
6 |
7 | **Describe the bug**
8 | A clear and concise description of what the bug is.
9 |
10 | **To Reproduce**
11 | Steps to reproduce the behavior
12 |
13 | **Expected behavior**
14 | A clear and concise description of what you expected to happen.
15 |
16 | **Screenshots**
17 | If applicable, add screenshots to help explain your problem.
18 |
19 | **Chat application**
20 | Chat application you are attempting to communicate with
21 |
22 | **Additional context**
23 | Add any other context about the problem here.
24 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 |
5 | ---
6 |
7 | **Is your feature request related to a problem? Please describe.**
8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
9 |
10 | **Describe the solution you'd like**
11 | A clear and concise description of what you want to happen.
12 |
13 | **Describe alternatives you've considered**
14 | A clear and concise description of any alternative solutions or features you've considered.
15 |
16 | **Additional context**
17 | Add any other context or screenshots about the feature request here.
18 |
--------------------------------------------------------------------------------
/.github/workflows/publish_image.yaml:
--------------------------------------------------------------------------------
1 | name: Publish image on commit or published release
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | - main
8 | release:
9 | types:
10 | - published
11 |
12 | jobs:
13 | push-image:
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 | - name: Checkout
18 | uses: actions/checkout@v2
19 |
20 | - name: Set up Docker Buildx
21 | uses: docker/setup-buildx-action@v1
22 |
23 | - name: Login to GitHub Container Registry
24 | uses: docker/login-action@v1
25 | with:
26 | registry: ghcr.io
27 | username: ${{ github.actor }}
28 | password: ${{ github.token }}
29 |
30 | - name: Set tag name for releases
31 | if: ${{ github.event_name == 'release' }}
32 | run: echo "TAG=ghcr.io/${GITHUB_REPOSITORY,,}:${GITHUB_REF##*/}" >>${GITHUB_ENV}
33 |
34 | - name: Set tag name for commits
35 | if: ${{ github.event_name == 'push' }}
36 | run: echo "TAG=ghcr.io/${GITHUB_REPOSITORY,,}:${{ github.sha }}" >>${GITHUB_ENV}
37 |
38 | - name: Build image
39 | uses: docker/build-push-action@v2
40 | with:
41 | load: true
42 | push: false
43 | tags: ${{ env.TAG }}
44 |
45 | - name: Test image
46 | run: |
47 | docker run ${{ env.TAG }} /bin/sh -c "\
48 | python -m pip install --upgrade pip && \
49 | pip install -r requirements.txt && \
50 | pip install -r requirements-test.txt && \
51 | pytest"
52 |
53 | - name: Push image to registry
54 | uses: docker/build-push-action@v2
55 | with:
56 | push: true
57 | tags: ${{ env.TAG }}
58 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Run tests on PRs and commits
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | - master
8 | pull_request:
9 | types: [opened, synchronize]
10 | branches:
11 | - main
12 | - master
13 | workflow_dispatch:
14 |
15 | env:
16 | BOT_ID: 916ccfd76a7fda25c74d09e1d5
17 | LEAGUE_ID: 164483
18 | TEST_TAG: user/test_build:test
19 |
20 | jobs:
21 | test:
22 | runs-on: ubuntu-latest
23 |
24 | steps:
25 | - uses: actions/checkout@v2
26 |
27 | - name: Set up Python 3.9.13
28 | uses: actions/setup-python@v2
29 | with:
30 | python-version: 3.9.13
31 |
32 | - name: Install dependencies
33 | run: |
34 | python -m pip install --upgrade pip
35 | python -m pip install -r requirements.txt
36 | python -m pip install -r requirements-test.txt
37 |
38 | - name: Test with pytest
39 | run: pytest
40 |
--------------------------------------------------------------------------------
/.github/workflows/test_image.yml:
--------------------------------------------------------------------------------
1 | name: Run tests on PRs and commits
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | - master
8 | pull_request:
9 | branches:
10 | - main
11 | - master
12 | workflow_dispatch:
13 |
14 | env:
15 | BOT_ID: 916ccfd76a7fda25c74d09e1d5
16 | LEAGUE_ID: 164483
17 | TEST_TAG: user/test_build:test
18 |
19 | jobs:
20 | test:
21 | runs-on: ubuntu-latest
22 |
23 | steps:
24 | - uses: actions/checkout@v2
25 |
26 | - name: Set up Docker Buildx
27 | uses: docker/setup-buildx-action@v1
28 |
29 | - name: Build container
30 | uses: docker/build-push-action@v2
31 | with:
32 | push: false
33 | context: .
34 | load: true
35 | tags: ${{ env.TEST_TAG }}
36 |
37 | - name: Run image against tests
38 | run: |
39 | docker run ${{ env.TEST_TAG }} /bin/sh -c "\
40 | python -m pip install --upgrade pip && \
41 | pip install -r requirements.txt && \
42 | pip install -r requirements-test.txt && \
43 | pytest"
44 |
--------------------------------------------------------------------------------
/.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 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 | .envrc
113 | .direnv/
114 |
115 | # Spyder project settings
116 | .spyderproject
117 | .spyproject
118 |
119 | # Rope project settings
120 | .ropeproject
121 |
122 | # mkdocs documentation
123 | /site
124 |
125 | # mypy
126 | .mypy_cache/
127 | .dmypy.json
128 | dmypy.json
129 |
130 | # Pyre type checker
131 | .pyre/
132 |
133 | #misc.
134 | .vscode/*
135 |
136 | gamedaybot/ids.txt
137 | *.sh
138 | *.ipynb
139 | .DS_STORE
140 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.9.13
2 |
3 | # Install app
4 | ADD . /usr/src/gamedaybot
5 | WORKDIR /usr/src/gamedaybot
6 | RUN python3 setup.py install
7 |
8 | # Launch app
9 | CMD ["python3", "gamedaybot/espn/espn_bot.py"]
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | worker: python3 gamedaybot/espn/espn_bot.py
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/dtcarls/fantasy_football_chat_bot/releases/latest/)
2 | 
3 | 
4 |
5 | For troubleshooting and release notifications, join the discord!
6 |
7 | [](https://discord.gg/VFXSkcgjxh)
8 |
9 | Like the bot? Star the repository and consider making a donation to buy me a coffee
10 | ------
11 | * PayPal:
12 | [](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ZDLFECJVGG6RG¤cy_code=USD&source=url)
13 | * BTC: bc1q3wxm269mdmwdqjqkxgt7s5zp8ah05dexdua0zv
14 | * ETH: 0x8c096710e3621fe5f8E384efBd17D8E3E798Dc0c (Cryptik.eth)
15 | * DOGE: D6n2g2KGdqEwR4MhhT7uAdvZFaTwqwd6rS
16 | * Venmo: @dtcarls
17 |
18 | # ESPN Fantasy Football GroupMe Slack and Discord Chat Bot
19 |
20 | This repository runs a GroupMe, Discord, or Slack chat bot to send ESPN Fantasy Football information to a GroupMe, Discord or Slack chat room.
21 |
22 | **What does this do?**
23 |
24 | Schedule Link: https://www.gamedaybot.com/message-schedule/
25 | - Sends out the following messages on this schedule:
26 | - Close Scores - Mon - 18:30 east coast time (Games that are within 16 points of eachother to keep an eye on during the Monday night game)
27 | - Scoreboard - Mon,Tue,Fri - 7:30 local time (Current ESPN fantasy scoreboard)
28 | - Trophies - Tue - 7:30 local time (High score, low score, biggest win, closest win)
29 | - Power rankings - Tue - 18:30 local time
30 | - Current standings - Wed - 7:30 local time
31 | - Waiver report - Wed - 7:30 local time
32 | - Matchups - Thu - 19:30 east coast time (Upcoming matchups)
33 | - Players to Monitor report - Sun - 7:30 local time (Players in starting lineup that are Questionable, Doubtful, or Out)
34 | - Scoreboard - Sun - 16:00, 20:00 east coast time (Current ESPN fantasy scoreboard)
35 |
36 |
37 | Table of Contents
38 | =================
39 |
40 | * [Setting up GroupMe, Discord, or Slack, and deploying app in Heroku](#setting-up-groupme-discord-or-slack-and-deploying-app-in-heroku)
41 | * [GroupMe Setup](#groupme-setup)
42 | * [Slack setup](#slack-setup)
43 | * [Discord setup](#discord-setup)
44 | * [Heroku setup](#heroku-setup)
45 | * [Private Leagues](#private-leagues)
46 | * [Troubleshooting / FAQ](#troubleshooting--faq)
47 | * [Getting Started for development and testing](#getting-started-for-development-and-testing)
48 | * [Installing for development](#installing-for-development)
49 | * [Environment Variables](#environment-variables)
50 | * [Running with Docker](#running-with-docker)
51 | * [Running without Docker](#running-without-docker)
52 | * [Running the tests](#running-the-tests)
53 |
54 | :cold_sweat::cold_sweat::cold_sweat:
55 |
56 | **All of this look too complicated and confusing? Don't know what a "Heroku" is? Consider checking out https://www.GameDayBot.com/ where I offer a hosting service and do my best to minimize complexity.**
57 |
58 | :cold_sweat::cold_sweat::cold_sweat:
59 | ## Setting up GroupMe, Discord, or Slack, and deploying app in Heroku
60 |
61 | **Do not deploy 2 of the same bot in the same chat. In general, you should let your commissioner do the setup**
62 |
63 | ### GroupMe Setup
64 |
65 | Click to expand!
66 |
67 | Go to www.groupme.com and sign up or login
68 |
69 | If you don't have one for your league already, create a new "Group Chat"
70 |
71 | 
72 |
73 | Next we will setup the bot for GroupMe
74 |
75 | Go to https://dev.groupme.com/session/new and login
76 |
77 | Click "Create Bot"
78 |
79 | 
80 |
81 | Create your bot. GroupMe does a good job explaining what each thing is.
82 |
83 | 
84 |
85 | After you have created your bot you will see something similar to this. Click "Edit"
86 |
87 | 
88 |
89 | This page is important as you will need the "Bot ID" on this page.You can also send a test message with the text box to be sure it is connected to your chat room.
90 | Side note: If you use the bot id depicted in the page you will spam an empty chat room so not worth the effort
91 |
92 | 
93 |
94 |
95 | ### Slack setup
96 |
97 | Click to expand!
98 |
99 | Go to https://slack.com/signin and sign in to the workspace the bot will be in
100 |
101 | If you don't have one for your league already, create a new League Channel
102 |
103 | Next we will setup the bot for Slack
104 |
105 | Go to https://api.slack.com/apps/new
106 |
107 | Name the app, and choose the intended workspace from the dropdown.
108 |
109 | Select the Incoming Webhooks section on the side.
110 |
111 | 
112 |
113 | Change the toggle from Off to On.
114 |
115 | Select Add New Webhook to Workspace
116 |
117 | 
118 |
119 | In the Post to dropdown, select the channel you want to send messages to, then
120 | select Authorize.
121 |
122 | This page is important as you will need the "Webhook URL" on this page.
123 |
124 | 
125 |
126 |
127 | ### Discord setup
128 |
129 | Click to expand!
130 |
131 | Log into or create a discord account
132 |
133 | Go to or create a discord server to receive messages in
134 |
135 | Open the server settings
136 |
137 | 
138 |
139 | Go to Webhooks
140 |
141 | 
142 |
143 | Create a webhook, give it a name and pick which channel to receive messages in
144 |
145 | 
146 |
147 | Save the "Webhook URL" on this page
148 |
149 | 
150 |
151 |
152 | ### Heroku setup
153 | **"November 28, 2022, Heroku stopped offering free product plans"**
154 |
155 | I offer a hosting service far lower than the new costs of Heroku at https://www.GameDayBot.com/
156 |
157 | Click to expand!
158 | Heroku is what you can use to host the chat bot.
159 |
160 | Go to https://id.heroku.com/login and sign up or login
161 |
162 |
163 | :warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning:
164 |
165 | :rotating_light:**Click this purple button to automatically deploy the code:**:rotating_light:
166 |
167 | [](https://heroku.com/deploy)
168 |
169 | :warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning:
170 |
171 | Go to your dashboard (https://dashboard.heroku.com/apps)
172 | Now you will need to setup your environment variables so that it works for your league. Click Settings at your dashboard. Then click "Reveal Config Vars" button and you will see something like this.
173 |
174 | 
175 |
176 | Now we will need to edit these variables (click the pencil to the right of the variable to modify)
177 | Note: App will restart when you change any variable so your chat room may be semi-spammed with the init message of "Hi" you can change the INIT_MSG variable to be blank to have no init message. It should also be noted that Heroku seems to restart the app about once a day
178 |
179 | See [Environment Variables Section](#environment-variables) for documentation
180 |
181 | After you have setup your variables you will need to turn it on. Navigate to the "Resources" tab of your Heroku app Dashboard.
182 | You should see something like below. Click the pencil on the right and toggle the buton so it is blue like depicted and click "Confirm."
183 | 
184 |
185 | You're done! You now have a fully featured GroupMe/Slack/Discord chat bot for ESPN leagues! If you have an INIT_MSG you will see it exclaimed in your GroupMe, Discord, or Slack chat room.
186 |
187 | Unfortunately to do auto deploys of the latest version you need admin access to the repository on git. You can check for updates on the github page (https://github.com/dtcarls/fantasy_football_chat_bot/commits/master) and click the deploy button again; however, this will deploy a new instance and the variables will need to be edited again.
188 |
189 |
190 | ## Getting Started for development and testing
191 |
192 |
193 | Click to expand!
194 |
195 | These instructions will get you a copy of the project up and running
196 | on your local machine for development and testing purposes.
197 |
198 | ### Installing for development
199 | With Docker:
200 | ```bash
201 | git clone https://github.com/dtcarls/fantasy_football_chat_bot
202 |
203 | cd fantasy_football_chat_bot
204 |
205 | docker build -t fantasy_football_chat_bot .
206 | ```
207 |
208 | Without Docker:
209 |
210 | ```bash
211 | git clone https://github.com/dtcarls/fantasy_football_chat_bot
212 |
213 | cd fantasy_football_chat_bot
214 |
215 | pip install -r requirements.txt
216 | # or
217 | #python3 setup.py install
218 | ```
219 |
220 | ### Environment Variables
221 | |Var|Type|Required|Default|Description|
222 | |---|----|--------|-------|-----------|
223 | |BOT_ID|String|For GroupMe|None|This is your Bot ID from the GroupMe developers page|
224 | |SLACK_WEBHOOK_URL|String|For Slack|None|This is your Webhook URL from the Slack App page|
225 | |DISCORD_WEBHOOK_URL|String|For Discord|None|This is your Webhook URL from the Discord Settings page|
226 | |LEAGUE_ID|String|Yes|None|This is your ESPN league id|
227 | |START_DATE|Date|Yes|Start of current season (YYYY-MM-DD)|This is when the bot will start paying attention and sending messages to your chat.|
228 | |END_DATE|Date|Yes|End of current season (YYYY-MM-DD)|This is when the bot will stop paying attention and stop sending messages to your chat.|
229 | |LEAGUE_YEAR|String|Yes|Currernt Year (YYYY)|ESPN League year to look at|
230 | |TIMEZONE|String|Yes|America/New_York|The timezone that the messages will look to send in.|
231 | |INIT_MSG|String|No|None|The message that the bot will say when it is started.|
232 | |TOP_HALF_SCORING|Bool|No|False|If set to True, when standings are posted on Wednesday it will also include being in the top half of your league for points and you receive an additional "win" for it.|
233 | |RANDOM_PHRASE|Bool|No|False|If set to True, when matchups are posted on Tuesday it will also include a random phrase|
234 | |MONITOR_REPORT|Bool|No|False|If set to True, will provide a report of players in starting lineup that are Questionable, Doubtful, Out, or projected for less than 4 points|
235 | |WAIVER_REPORT|Bool|No|False|If set to True, will provide a waiver report of add/drops. :warning: ESPN_S2 and SWID are required for this to work :warning:|
236 | |DAILY_WAIVER|Bool|No|False|If set to True, will provide a waiver report of add/drops daily. :warning: ESPN_S2 and SWID are required for this to work :warning:|
237 | |ESPN_S2|String|For Private leagues|None|Used for private leagues. See [Private Leagues Section](#private-leagues) for documentation|
238 | |SWID|String|For Private leagues|None|Used for private leagues. (Can be defined with or without {}) See [Private Leagues Section](#private-leagues) for documentation|
239 |
240 | ### Running with Docker
241 |
242 | Use BOT_ID if using Groupme, DISCORD_WEBHOOK_URL if using Discord, and SLACK_WEBHOOK_URL if using Slack (or multiple to get messages in multiple places)
243 |
244 | ```bash
245 | >>> export BOT_ID=[enter your GroupMe Bot ID]
246 | >>> export WEBHOOK_URL=[enter your Webhook URL]
247 | >>> export LEAGUE_ID=[enter ESPN league ID]
248 | >>> export LEAGUE_YEAR=[enter league year]
249 | >>> cd fantasy_football_chat_bot
250 | >>> docker run --rm=True \
251 | -e BOT_ID=$BOT_ID \
252 | -e LEAGUE_ID=$LEAGUE_ID \
253 | -e LEAGUE_YEAR=$LEAGUE_YEAR \
254 | fantasy_football_chat_bot
255 | ```
256 |
257 | ### Running without Docker
258 |
259 | Use BOT_ID if using Groupme, DISCORD_WEBHOOK_URL if using Discord, and SLACK_WEBHOOK_URL if using Slack (or multiple to get messages in multiple places)
260 |
261 | ```bash
262 | >>> export BOT_ID=[enter your GroupMe Bot ID]
263 | >>> export WEBHOOK_URL=[enter your Webhook URL]
264 | >>> export LEAGUE_ID=[enter ESPN league ID]
265 | >>> export LEAGUE_YEAR=[enter league year]
266 | >>> python3 gamedaybot/espn/espn_bot.py
267 | ```
268 |
269 | ### Running the tests
270 |
271 | Automated tests for this package are included in the `tests` directory. After installation,
272 | you can run these tests by changing the directory to the `gamedaybot` directory and running the following:
273 |
274 | ```python3
275 | pip install -r requirements-test.txt
276 | pytest
277 | ```
278 |
279 |
280 | #### Private Leagues
281 |
282 | For private league you will need to get your swid and espn_s2.
283 | You can find these two values after logging into your espn fantasy football account on espn's website.
284 | (Chrome Browser)
285 | Right click anywhere on the website and click inspect option.
286 | From there click Application on the top bar.
287 | On the left under Storage section click Cookies then http://fantasy.espn.com.
288 | From there you should be able to find your swid and espn_s2 variables and values.
289 | ## FAQ
290 |
291 | **League must be full.**
292 |
293 | The bot isn't working
294 |
295 | * Did you miss a step in the instructions? Try doing it from scratch again. If still no luck, open an issue (https://github.com/dtcarls/fantasy_football_chat_bot/issues) or hop into the discord (link at the top of readme) so the answer can be shared with others.
296 |
297 | How are power ranks calculated?
298 |
299 | * They are calculated using 2 step dominance, as well as a combination of points scored and margin of victory. Weighted 80/15/5 respectively. I wouldn't so much pay attention to the actual number but more of the gap between teams. Full source of the calculations can be seen here: https://github.com/cwendt94/espn-api/pull/12/files. If you want a tutorial on dominance matrices: https://www.youtube.com/watch?v=784TmwaHPOw
300 |
301 | Is there a version of this for Yahoo/CBS/NFL/[insert other site]?
302 |
303 | * No, this would require a significant rework for other sites.
304 |
305 | How do I set another timezone?
306 |
307 | * Specify your variable https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List
308 |
309 | Is there a version of this for Messenger/WhatsApp/[insert other chat]?
310 |
311 | * No, but I am open to pull requests implementing their API for additional cross platform support.
312 |
313 | My Standings look wrong. I have weird (+1) in it.
314 |
315 | * TOP_HALF_SCORING: If set to True, when standings are posted on Wednesday it will also include top half scoring wins
316 | * Top half wins is being in the top half of your league for points and you receive an additional "win" for it. The number in parenthesis (+1) tells you how many added wins over the season for top half wins.
317 |
318 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "stack": "heroku-22",
3 | "name": "Fantasy Football Chat Bot",
4 | "description": "ESPN Fantasy Football GroupMe, Slack, and Discord Chat Bot.",
5 | "keywords": [
6 | "fantasy football",
7 | "espn",
8 | "groupme",
9 | "slack",
10 | "discord",
11 | "chat bot",
12 | "ff"
13 | ],
14 | "website": "https://github.com/dtcarls/fantasy_football_chat_bot/",
15 | "repository": "https://github.com/dtcarls/fantasy_football_chat_bot/",
16 | "env": {
17 | "BOT_ID": {
18 | "description": "GroupMe Bot ID",
19 | "value": "1",
20 | "required": false
21 | },
22 | "SLACK_WEBHOOK_URL": {
23 | "description": "Slack Webhook URL",
24 | "value": "1",
25 | "required": false
26 | },
27 | "DISCORD_WEBHOOK_URL": {
28 | "description": "Discord Webhook URL",
29 | "value": "1",
30 | "required": false
31 | },
32 | "LEAGUE_ID": {
33 | "description": "ESPN League ID",
34 | "value": "1"
35 | },
36 | "LEAGUE_YEAR": {
37 | "description": "ESPN League Year",
38 | "value": "2024",
39 | "required": false
40 | },
41 | "TIMEZONE": {
42 | "description": "League timezone for sending messages",
43 | "value": "America/New_York",
44 | "required": false
45 | },
46 | "START_DATE": {
47 | "description": "Season Start Date",
48 | "value": "2024-09-05",
49 | "required": false
50 | },
51 | "END_DATE": {
52 | "description": "Season End Date",
53 | "value": "2025-01-05",
54 | "required": false
55 | },
56 | "INIT_MSG": {
57 | "description": "Bot Init Message",
58 | "value": "Successfully installed https://github.com/dtcarls/fantasy_football_chat_bot you can now remove this init_msg"
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | gamedaybot:
3 | build:
4 | context: .
5 | restart: always
6 | environment:
7 | #Bot ID from the GroupMe developers page (REQUIRED IF USING GROUPME)
8 | BOT_ID: "1"
9 | #Webhook URL from the Slack App page (REQUIRED IF USING SLACK)
10 | SLACK_WEBHOOK_URL: "1"
11 | #This is your Webhook URL from the Discord Settings page (REQUIRED IF USING DISCORD)
12 | DISCORD_WEBHOOK_URL: "1"
13 | #ESPN league id (REQUIRED)
14 | LEAGUE_ID:
15 | # #When the bot will start paying attention and sending messages to your chat.
16 | # START_DATE:
17 | # #When the bot will stop paying attention and stop sending messages to your chat.
18 | # END_DATE:
19 | # #ESPN League year
20 | # LEAGUE_YEAR:
21 | # #The timezone that the messages will look to send in. (America/New_York by default)
22 | # TIMEZONE:
23 | # #The message that the bot will say when it is started (can be blank for no message)
24 | # INIT_MSG:
25 | # #If set to True, when standings are posted on Wednesday it will also include top half scoring wins
26 | # TOP_HALF_SCORING:
27 | # #If set to True, when matchups are posted on Tuesday it will also include a random phrase
28 | # RANDOM_PHRASE:
29 | # #Used for private leagues. See Private Leagues Section for documentation
30 | # ESPN_S2:
31 | # #Used for private leagues. See Private Leagues Section for documentation
32 | # SWID:
33 |
--------------------------------------------------------------------------------
/gamedaybot/chat/discord.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import logging
4 |
5 | logger = logging.getLogger(__name__)
6 |
7 |
8 | class DiscordException(Exception):
9 | pass
10 |
11 |
12 | class Discord(object):
13 | """
14 | A class used to send messages to a Discord channel through a webhook.
15 |
16 | Parameters
17 | ----------
18 | webhook_url : str
19 | The URL of the Discord webhook to send messages to.
20 |
21 | Attributes
22 | ----------
23 | webhook_url : str
24 | The URL of the Discord webhook to send messages to.
25 |
26 | Methods
27 | -------
28 | send_message(text: str)
29 | Sends a message to the Discord channel.
30 | """
31 |
32 | def __init__(self, webhook_url):
33 | self.webhook_url = webhook_url
34 |
35 | def __repr__(self):
36 | return "Discord Webhook Url(%s)" % self.webhook_url
37 |
38 | def send_message(self, text):
39 | """
40 | Sends a message to the Discord channel.
41 |
42 | Parameters
43 | ----------
44 | text : str
45 | The message to be sent to the Discord channel.
46 |
47 | Returns
48 | -------
49 | r : requests.Response
50 | The response object of the POST request.
51 |
52 | Raises
53 | ------
54 | DiscordException
55 | If there is an error with the POST request.
56 | """
57 |
58 | message = "```{0}```".format(text)
59 | template = {
60 | "content": message # limit 3000 chars
61 | }
62 |
63 | headers = {'content-type': 'application/json'}
64 |
65 | if self.webhook_url not in (1, "1", ''):
66 | r = requests.post(self.webhook_url,
67 | data=json.dumps(template), headers=headers)
68 |
69 | if r.status_code != 204:
70 | print(r.content)
71 | logger.error(r.content)
72 | raise DiscordException(r.content)
73 |
74 | return r
75 |
--------------------------------------------------------------------------------
/gamedaybot/chat/groupme.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import logging
4 |
5 | logger = logging.getLogger(__name__)
6 |
7 |
8 | class GroupMeException(Exception):
9 | pass
10 |
11 |
12 | class GroupMe(object):
13 | """
14 | Creates a GroupMe bot to send messages to a specified chatroom.
15 |
16 | Parameters:
17 | bot_id (str): The unique bot ID for the GroupMe chatroom.
18 |
19 | Attributes:
20 | bot_id (str): The unique bot ID for the GroupMe chatroom.
21 | """
22 |
23 | def __init__(self, bot_id):
24 | self.bot_id = bot_id
25 |
26 | def __repr__(self):
27 | return "GroupMeBot(%s)" % self.bot_id
28 |
29 | def send_message(self, text):
30 | """
31 | Sends a message to the specified GroupMe chatroom.
32 |
33 | Parameters:
34 | text (str): The message to be sent to the chatroom. Limit 1000 characters.
35 |
36 | Returns:
37 | r (requests.Response): The response from the GroupMe API.
38 | """
39 | template = {
40 | "bot_id": self.bot_id,
41 | "text": text,
42 | "attachments": []
43 | }
44 |
45 | headers = {'content-type': 'application/json'}
46 |
47 | if self.bot_id not in (1, "1", ''):
48 | r = requests.post("https://api.groupme.com/v3/bots/post",
49 | data=json.dumps(template), headers=headers)
50 | if r.status_code != 202:
51 | logger.error(r.content)
52 | raise GroupMeException(r.content)
53 |
54 | return r
55 |
--------------------------------------------------------------------------------
/gamedaybot/chat/slack.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import logging
4 |
5 | logger = logging.getLogger(__name__)
6 |
7 |
8 | class SlackException(Exception):
9 | pass
10 |
11 |
12 | class Slack:
13 | """
14 | A class used to send messages to a Slack channel through a webhook.
15 |
16 | Parameters
17 | ----------
18 | webhook_url : str
19 | The URL of the Slack webhook to send messages to.
20 |
21 | Attributes
22 | ----------
23 | webhook_url : str
24 | The URL of the Slack webhook to send messages to.
25 |
26 | Methods
27 | -------
28 | send_message(text: str)
29 | Sends a message to the Slack channel.
30 | """
31 |
32 | def __init__(self, webhook_url: str):
33 | self.webhook_url = webhook_url
34 |
35 | def __repr__(self):
36 | return "Slack Webhook Url(%s)" % self.webhook_url
37 |
38 | def send_message(self, text: str):
39 | """
40 | Sends a message to the Slack channel.
41 |
42 | Parameters
43 | ----------
44 | text : str
45 | The message to be sent to the Slack channel.
46 |
47 | Returns
48 | -------
49 | r : requests.Response
50 | The response object of the POST request.
51 |
52 | Raises
53 | ------
54 | SlackException
55 | If there is an error with the POST request.
56 | """
57 |
58 | message = "```{0}```".format(text)
59 | template = {
60 | "text": message # limit 40000
61 | }
62 |
63 | headers = {'content-type': 'application/json'}
64 |
65 | if self.webhook_url not in (1, "1", ''):
66 | r = requests.post(self.webhook_url,
67 | data=json.dumps(template), headers=headers)
68 |
69 | if r.status_code != 200:
70 | logger.error(r.content)
71 | raise SlackException(r.content)
72 |
73 | return r
74 |
--------------------------------------------------------------------------------
/gamedaybot/espn/env_vars.py:
--------------------------------------------------------------------------------
1 | import os
2 | import gamedaybot.espn.functionality as espn
3 | import gamedaybot.utils.util as utils
4 |
5 |
6 | def get_env_vars():
7 | data = {}
8 | try:
9 | ff_start_date = os.environ["START_DATE"]
10 | except KeyError:
11 | ff_start_date = '2024-09-05'
12 |
13 | data['ff_start_date'] = ff_start_date
14 |
15 | try:
16 | ff_end_date = os.environ["END_DATE"]
17 | except KeyError:
18 | ff_end_date = '2025-01-05'
19 |
20 | data['ff_end_date'] = ff_end_date
21 |
22 | try:
23 | my_timezone = os.environ["TIMEZONE"]
24 | except KeyError:
25 | my_timezone = 'America/New_York'
26 |
27 | data['my_timezone'] = my_timezone
28 |
29 | try:
30 | daily_waiver = utils.str_to_bool(os.environ["DAILY_WAIVER"])
31 | except KeyError:
32 | daily_waiver = False
33 |
34 | data['daily_waiver'] = daily_waiver
35 |
36 | try:
37 | monitor_report = utils.str_to_bool(os.environ["MONITOR_REPORT"])
38 | except KeyError:
39 | monitor_report = True
40 |
41 | data['monitor_report'] = monitor_report
42 |
43 | str_limit = 40000 # slack char limit
44 |
45 | try:
46 | bot_id = os.environ["BOT_ID"]
47 | str_limit = 1000
48 | except KeyError:
49 | bot_id = 1
50 |
51 | try:
52 | slack_webhook_url = os.environ["SLACK_WEBHOOK_URL"]
53 | except KeyError:
54 | slack_webhook_url = 1
55 |
56 | try:
57 | discord_webhook_url = os.environ["DISCORD_WEBHOOK_URL"]
58 | str_limit = 3000
59 | except KeyError:
60 | discord_webhook_url = 1
61 |
62 | if (len(str(bot_id)) <= 1 and
63 | len(str(slack_webhook_url)) <= 1 and
64 | len(str(discord_webhook_url)) <= 1):
65 | # Ensure that there's info for at least one messaging platform,
66 | # use length of str in case of blank but non null env variable
67 | raise Exception("No messaging platform info provided. Be sure one of BOT_ID, SLACK_WEBHOOK_URL, or DISCORD_WEBHOOK_URL env variables are set")
68 |
69 | data['str_limit'] = str_limit
70 | data['bot_id'] = bot_id
71 | data['slack_webhook_url'] = slack_webhook_url
72 | data['discord_webhook_url'] = discord_webhook_url
73 |
74 | data['league_id'] = os.environ["LEAGUE_ID"]
75 |
76 | try:
77 | year = int(os.environ["LEAGUE_YEAR"])
78 | except KeyError:
79 | year = 2024
80 |
81 | data['year'] = year
82 |
83 | try:
84 | swid = os.environ["SWID"]
85 | except KeyError:
86 | swid = '{1}'
87 |
88 | if swid.find("{", 0) == -1:
89 | swid = "{" + swid
90 | if swid.find("}", -1) == -1:
91 | swid = swid + "}"
92 |
93 | data['swid'] = swid
94 |
95 | try:
96 | espn_s2 = os.environ["ESPN_S2"]
97 | except KeyError:
98 | espn_s2 = '1'
99 |
100 | data['espn_s2'] = espn_s2
101 |
102 | try:
103 | test = utils.str_to_bool(os.environ["TEST"])
104 | except KeyError:
105 | test = False
106 |
107 | data['test'] = test
108 |
109 | try:
110 | top_half_scoring = utils.str_to_bool(os.environ["TOP_HALF_SCORING"])
111 | except KeyError:
112 | top_half_scoring = False
113 |
114 | data['top_half_scoring'] = top_half_scoring
115 |
116 | try:
117 | random_phrase = utils.str_to_bool(os.environ["RANDOM_PHRASE"])
118 | except KeyError:
119 | random_phrase = False
120 |
121 | data['random_phrase'] = random_phrase
122 |
123 | try:
124 | waiver_report = utils.str_to_bool(os.environ["WAIVER_REPORT"])
125 | except KeyError:
126 | waiver_report = False
127 |
128 | data['waiver_report'] = waiver_report
129 |
130 | try:
131 | data['init_msg'] = os.environ["INIT_MSG"]
132 | except KeyError:
133 | # do nothing here, empty init message
134 | pass
135 |
136 | return data
137 |
--------------------------------------------------------------------------------
/gamedaybot/espn/espn_bot.py:
--------------------------------------------------------------------------------
1 | import os
2 | if os.environ.get("AWS_EXECUTION_ENV") is not None:
3 | # For use in lambda function
4 | import utils.util as util
5 | from chat.groupme import GroupMe
6 | from chat.slack import Slack
7 | from chat.discord import Discord
8 | else:
9 | # For local use
10 | import sys
11 | sys.path.insert(1, os.path.abspath('.'))
12 | import gamedaybot.utils.util as util
13 | from gamedaybot.chat.groupme import GroupMe
14 | from gamedaybot.chat.slack import Slack
15 | from gamedaybot.chat.discord import Discord
16 | from gamedaybot.espn.env_vars import get_env_vars
17 | import gamedaybot.espn.functionality as espn
18 | import gamedaybot.espn.season_recap as recap
19 |
20 |
21 | from espn_api.football import League
22 | import json
23 | import logging
24 |
25 | logger = logging.getLogger(__name__)
26 | # logger.setLevel(logging.INFO)
27 | logger.setLevel(logging.DEBUG)
28 |
29 |
30 | def espn_bot(function):
31 | """
32 | This function is used to send messages to a messaging platform (e.g. Slack, Discord, or GroupMe) with information
33 | about a fantasy football league.
34 |
35 | Parameters
36 | ----------
37 | function: str
38 | A string that specifies which type of information to send (e.g. "get_matchups", "get_power_rankings").
39 |
40 | Returns
41 | -------
42 | None
43 |
44 | Notes
45 | -----
46 | The function uses the following information from the data dictionary:
47 |
48 | str_limit: the character limit for messages on slack.
49 | bot_id: the id of the GroupMe bot.
50 | If not provided, defaults to 1.
51 | slack_webhook_url: the webhook url for the slack bot.
52 | If not provided, defaults to 1.
53 | discord_webhook_url: the webhook url for the discord bot.
54 | If not provided, defaults to 1.
55 | league_id: the id of the fantasy football league.
56 | year: the year of the league.
57 | If not provided, defaults to current year.
58 | swid: the swid of the league.
59 | If not provided, defaults to '{1}'.
60 | espn_s2: the espn s2 of the league.
61 | If not provided, defaults to '1'.
62 | top_half_scoring: a boolean that indicates whether to include only the top half of the league in the standings.
63 | If not provided, defaults to False.
64 | random_phrase: a boolean that indicates whether to include a random phrase in the message.
65 | If not provided, defaults to False.
66 |
67 | The function creates GroupMe, Slack, and Discord objects, and a League object using the provided information.
68 | It then uses the specified function to generate a message and sends it through the appropriate messaging platform.
69 |
70 | Possible function values:
71 |
72 | get_matchups: sends the current week's matchups and the projected scores for the remaining games.
73 | get_monitor: sends a message with a summary of the current week's scores.
74 | get_scoreboard_short: sends a short version of the current week's scores.
75 | get_projected_scoreboard: sends the projected scores for the remaining games.
76 | get_close_scores: sends a message with the scores of games that have a difference of less than 7 points.
77 | get_power_rankings: sends a message with the power rankings for the league.
78 | get_trophies: sends a message with the trophies for the league.
79 | get_standings: sends a message with the standings for the league.
80 | get_final: sends the final scores and trophies for the previous week.
81 | get_waiver_report: sends a message with the waiver report for the league.
82 | init: sends a message to confirm that the bot has been set up.
83 | """
84 |
85 | data = get_env_vars()
86 | str_limit = data['str_limit'] # slack char limit
87 |
88 | try:
89 | bot_id = data['bot_id']
90 | except KeyError:
91 | bot_id = 1
92 |
93 | try:
94 | slack_webhook_url = data['slack_webhook_url']
95 | except KeyError:
96 | slack_webhook_url = 1
97 |
98 | try:
99 | discord_webhook_url = data['discord_webhook_url']
100 | except KeyError:
101 | discord_webhook_url = 1
102 |
103 | if (len(str(bot_id)) <= 1 and
104 | len(str(slack_webhook_url)) <= 1 and
105 | len(str(discord_webhook_url)) <= 1):
106 | # Ensure that there's info for at least one messaging platform,
107 | # use length of str in case of blank but non null env variable
108 | raise Exception("No messaging platform info provided. Be sure one of BOT_ID, SLACK_WEBHOOK_URL, or DISCORD_WEBHOOK_URL env variables are set")
109 |
110 | league_id = data['league_id']
111 |
112 | try:
113 | year = int(data['year'])
114 | except KeyError:
115 | year = 2024
116 |
117 | try:
118 | swid = data['swid']
119 | except KeyError:
120 | swid = '{1}'
121 |
122 | if swid.find("{", 0) == -1:
123 | swid = "{" + swid
124 | if swid.find("}", -1) == -1:
125 | swid = swid + "}"
126 |
127 | try:
128 | espn_s2 = data['espn_s2']
129 | except KeyError:
130 | espn_s2 = '1'
131 |
132 | try:
133 | top_half_scoring = util.str_to_bool(data['top_half_scoring'])
134 | except KeyError:
135 | top_half_scoring = False
136 |
137 | try:
138 | random_phrase = util.str_to_bool(data['random_phrase'])
139 | except KeyError:
140 | random_phrase = False
141 |
142 | groupme_bot = GroupMe(bot_id)
143 | slack_bot = Slack(slack_webhook_url)
144 | discord_bot = Discord(discord_webhook_url)
145 |
146 | if swid == '{1}' or espn_s2 == '1':
147 | league = League(league_id=league_id, year=year)
148 | else:
149 | league = League(league_id=league_id, year=year, espn_s2=espn_s2, swid=swid)
150 |
151 | try:
152 | broadcast_message = data['broadcast_message']
153 | except KeyError:
154 | broadcast_message = None
155 |
156 | # always let init and broadcast run
157 | if function not in ["init", "broadcast", "win_matrix", "trophy_recap"] and league.scoringPeriodId > len(league.settings.matchup_periods):
158 | logger.info("Not in active season")
159 | return
160 |
161 | text = ''
162 | logger.info("Function: " + function)
163 |
164 | if function == "get_matchups":
165 | text = espn.get_matchups(league, random_phrase)
166 | text = text + "\n\n" + espn.get_projected_scoreboard(league)
167 | elif function == "get_monitor":
168 | text = espn.get_monitor(league)
169 | elif function == "get_scoreboard_short":
170 | text = espn.get_scoreboard_short(league)
171 | text = text + "\n\n" + espn.get_projected_scoreboard(league)
172 | elif function == "get_projected_scoreboard":
173 | text = espn.get_projected_scoreboard(league)
174 | elif function == "get_close_scores":
175 | text = espn.get_close_scores(league)
176 | elif function == "get_power_rankings":
177 | text = espn.get_power_rankings(league)
178 | elif function == "get_trophies":
179 | text = espn.get_trophies(league)
180 | elif function == "get_standings":
181 | text = espn.get_standings(league, top_half_scoring)
182 | elif function == "win_matrix":
183 | text = recap.win_matrix(league)
184 | elif function == "trophy_recap":
185 | text = recap.trophy_recap(league)
186 | # groupme_bot.send_message(text, file_path='/tmp/season_recap.png')
187 | # slack_bot.send_message(text, file_path='/tmp/season_recap.png')
188 | # discord_bot.send_message(text, file_path='/tmp/season_recap.png')
189 | elif function == "get_final":
190 | # on Tuesday we need to get the scores of last week
191 | week = league.current_week - 1
192 | text = "Final " + espn.get_scoreboard_short(league, week=week)
193 | text = text + "\n\n" + espn.get_trophies(league, week=week)
194 | elif function == "get_waiver_report" and swid != '{1}' and espn_s2 != '1':
195 | faab = league.settings.faab
196 | text = espn.get_waiver_report(league, faab)
197 | elif function == "broadcast":
198 | try:
199 | text = broadcast_message
200 | except KeyError:
201 | # do nothing here, empty broadcast message
202 | pass
203 | elif function == "init":
204 | try:
205 | text = data["init_msg"]
206 | except KeyError:
207 | # do nothing here, empty init message
208 | pass
209 | else:
210 | text = "Something bad happened. HALP"
211 |
212 | logger.debug(data)
213 | if text != '':
214 | logger.debug(text)
215 | messages = util.str_limit_check(text, str_limit)
216 | for message in messages:
217 | groupme_bot.send_message(message)
218 | slack_bot.send_message(message)
219 | discord_bot.send_message(message)
220 |
221 |
222 | if __name__ == '__main__':
223 | from gamedaybot.espn.scheduler import scheduler
224 |
225 | espn_bot("init")
226 | scheduler()
227 |
--------------------------------------------------------------------------------
/gamedaybot/espn/functionality.py:
--------------------------------------------------------------------------------
1 | from datetime import date
2 |
3 |
4 | def get_scoreboard_short(league, week=None):
5 | """
6 | Retrieve the scoreboard for a given week of the fantasy football season.
7 |
8 | Parameters
9 | ----------
10 | league: espn_api.football.League
11 | The league for which to retrieve the scoreboard.
12 | week: int
13 | The week of the season for which to retrieve the scoreboard.
14 |
15 | Returns
16 | -------
17 | list of dict
18 | A list of dictionaries representing the games on the scoreboard for the given week. Each dictionary contains
19 | information about a single game, including the teams and their scores.
20 | """
21 |
22 | # Gets current week's scoreboard
23 | box_scores = league.box_scores(week=week)
24 | score = ['%4s %6.2f - %6.2f %s' % (i.home_team.team_abbrev, i.home_score,
25 | i.away_score, i.away_team.team_abbrev) for i in box_scores
26 | if i.away_team]
27 | text = ['Score Update'] + score
28 | return '\n'.join(text)
29 |
30 |
31 | def get_projected_scoreboard(league, week=None):
32 | """
33 | Retrieve the projected scoreboard for a given week of the fantasy football season.
34 |
35 | Parameters
36 | ----------
37 | league: espn_api.football.League
38 | The league for which to retrieve the projected scoreboard.
39 | week: int
40 | The week of the season for which to retrieve the projected scoreboard.
41 |
42 | Returns
43 | -------
44 | list of dict
45 | A list of dictionaries representing the projected games on the scoreboard for the given week. Each dictionary
46 | contains information about a single game, including the teams and their projected scores.
47 | """
48 |
49 | # Gets current week's scoreboard projections
50 | box_scores = league.box_scores(week=week)
51 | score = ['%4s %6.2f - %6.2f %s' % (i.home_team.team_abbrev, get_projected_total(i.home_lineup),
52 | get_projected_total(i.away_lineup), i.away_team.team_abbrev) for i in box_scores
53 | if i.away_team]
54 | text = ['Approximate Projected Scores'] + score
55 | return '\n'.join(text)
56 |
57 |
58 | def get_standings(league, top_half_scoring=False, week=None):
59 | """
60 | Retrieve the current standings for a fantasy football league, with an option to include top-half scoring.
61 |
62 | Parameters
63 | ----------
64 | league: object
65 | The league object for which to retrieve the standings.
66 | top_half_scoring: bool, optional
67 | If True, include top-half scoring in the standings calculation. Defaults to False.
68 | week: int, optional
69 | The week for which to retrieve the standings. Defaults to the current week of the league.
70 |
71 | Returns
72 | -------
73 | str
74 | A string containing the current standings, formatted as a list of teams with their records and positions.
75 | """
76 |
77 | standings_txt = ''
78 | teams = league.teams
79 | standings = []
80 | if not top_half_scoring:
81 | standings = league.standings()
82 | standings_txt = [f"{pos + 1:2}: ({team.wins}-{team.losses}) {team.team_name} " for
83 | pos, team in enumerate(standings)]
84 | else:
85 | # top half scoring can be enabled by default in ESPN now.
86 | # this should generally not be used
87 | top_half_totals = {t.team_name: 0 for t in teams}
88 | if not week:
89 | week = league.current_week
90 | for w in range(1, week):
91 | top_half_totals = top_half_wins(league, top_half_totals, w)
92 |
93 | for t in teams:
94 | wins = top_half_totals[t.team_name] + t.wins
95 | standings.append((wins, t.losses, t.team_name))
96 |
97 | standings = sorted(standings, key=lambda tup: tup[0], reverse=True)
98 | standings_txt = [f"{pos + 1:2}: {team_name} ({wins}-{losses}) (+{top_half_totals[team_name]})" for
99 | pos, (wins, losses, team_name) in enumerate(standings)]
100 | text = ["Current Standings"] + standings_txt
101 |
102 | return "\n".join(text)
103 |
104 |
105 | def top_half_wins(league, top_half_totals, week):
106 | box_scores = league.box_scores(week=week)
107 |
108 | scores = [(i.home_score, i.home_team.team_name) for i in box_scores] + \
109 | [(i.away_score, i.away_team.team_name) for i in box_scores if i.away_team]
110 |
111 | scores = sorted(scores, key=lambda tup: tup[0], reverse=True)
112 |
113 | for i in range(0, len(scores) // 2):
114 | points, team_name = scores[i]
115 | top_half_totals[team_name] += 1
116 |
117 | return top_half_totals
118 |
119 |
120 | def get_projected_total(lineup):
121 | """
122 | Retrieve the projected total points for a given lineup in a fantasy football league.
123 |
124 | Parameters
125 | ----------
126 | lineup : list
127 | A list of player objects that represents the lineup
128 |
129 | Returns
130 | -------
131 | float
132 | The projected total points for the given lineup.
133 | """
134 |
135 | total_projected = 0
136 | for i in lineup:
137 | # exclude player on bench and injured reserve
138 | if i.slot_position != 'BE' and i.slot_position != 'IR':
139 | # Check if the player has already played or not
140 | if i.points != 0 or i.game_played > 0:
141 | total_projected += i.points
142 | else:
143 | total_projected += i.projected_points
144 | return total_projected
145 |
146 |
147 | def all_played(lineup):
148 | """
149 | Check if all the players in a given lineup have played their game.
150 |
151 | Parameters
152 | ----------
153 | lineup : list
154 | A list of player objects that represents the lineup
155 |
156 | Returns
157 | -------
158 | bool
159 | True if all the players in the lineup have played their game, False otherwise.
160 | """
161 |
162 | for i in lineup:
163 | # exclude player on bench and injured reserve
164 | if i.slot_position != 'BE' and i.slot_position != 'IR' and i.game_played < 100:
165 | return False
166 | return True
167 |
168 |
169 | def get_monitor(league):
170 | """
171 | Retrieve a list of players from a given fantasy football league that should be monitored during a game.
172 |
173 | Parameters
174 | ----------
175 | league: object
176 | The league object for which to retrieve the monitor players.
177 |
178 | Returns
179 | -------
180 | str
181 | A string containing the list of players to monitor, formatted as a list of player names and status.
182 | """
183 |
184 | box_scores = league.box_scores()
185 | monitor = []
186 | text = ''
187 | for i in box_scores:
188 | monitor += scan_roster(i.home_lineup, i.home_team)
189 | monitor += scan_roster(i.away_lineup, i.away_team)
190 |
191 | if monitor:
192 | text = ['Starting Players to Monitor'] + monitor
193 | else:
194 | text = ['No Players to Monitor this week. Good Luck!']
195 | return '\n'.join(text)
196 |
197 |
198 | def scan_roster(lineup, team):
199 | """
200 | Retrieve a list of players from a given fantasy football league that have a status.
201 |
202 | Parameters
203 | ----------
204 | lineup : list
205 | A list of player objects that represents the lineup
206 | team : object
207 | The team object for which to retrieve the monitor players
208 |
209 | Returns
210 | -------
211 | list
212 | A list of strings containing the list of players to monitor, formatted as a list of player names and statuses.
213 | """
214 |
215 | count = 0
216 | players = []
217 | for i in lineup:
218 | # exclude bench and injured players and active or normal players
219 | if i.slot_position != 'BE' and i.slot_position != 'IR' and \
220 | i.injuryStatus != 'ACTIVE' and i.injuryStatus != 'NORMAL' \
221 | and i.game_played == 0:
222 |
223 | count += 1
224 | player = i.position + ' ' + i.name + ' - ' + i.injuryStatus.title().replace('_', ' ')
225 | players += [player]
226 |
227 | if i.slot_position == 'IR' and \
228 | i.injuryStatus != 'INJURY_RESERVE' and i.injuryStatus != 'OUT':
229 |
230 | count += 1
231 | player = i.position + ' ' + i.name + ' - Not IR eligible'
232 | players += [player]
233 |
234 | list = ""
235 | report = ""
236 |
237 | for p in players:
238 | list += p + "\n"
239 |
240 | if count > 0:
241 | s = '%s: \n%s \n' % (team.team_name, list[:-1])
242 | report = [s.lstrip()]
243 |
244 | return report
245 |
246 |
247 | def get_matchups(league, week=None):
248 | """
249 | Retrieve the matchups for a given week in a fantasy football league.
250 |
251 | Parameters
252 | ----------
253 | league: object
254 | The league object for which to retrieve the matchups.
255 | week : int, optional
256 | The week number for which to retrieve the matchups, by default None.
257 |
258 | Returns
259 | -------
260 | str
261 | A string containing the matchups for the given week, formatted as a list of team names and abbreviation.
262 | """
263 |
264 | # Gets current week's Matchups
265 | matchups = league.box_scores(week=week)
266 |
267 | full_names = ['%s vs %s' % (i.home_team.team_name, i.away_team.team_name) for i in matchups if i.away_team]
268 |
269 | abbrevs = ['%4s (%s-%s) vs (%s-%s) %s' % (i.home_team.team_abbrev, i.home_team.wins, i.home_team.losses,
270 | i.away_team.wins, i.away_team.losses, i.away_team.team_abbrev) for i in matchups
271 | if i.away_team]
272 |
273 | text = ['Matchups'] + full_names + [''] + abbrevs
274 | return '\n'.join(text)
275 |
276 |
277 | def get_close_scores(league, week=None):
278 | """
279 | Retrieve the projected closest scores (15 points or closer) for a given week in a fantasy football league.
280 |
281 | Parameters
282 | ----------
283 | league: object
284 | The league object for which to retrieve the closest scores.
285 | week : int, optional
286 | The week number for which to retrieve the closest scores, by default None.
287 |
288 | Returns
289 | -------
290 | str
291 | A string containing the projected closest scores for the given week, formatted as a list of team names and abbreviation.
292 | """
293 |
294 | # Gets current projected closest scores (15 points or closer)
295 | box_scores = league.box_scores(week=week)
296 | score = []
297 |
298 | for i in box_scores:
299 | if i.away_team:
300 | away_projected = get_projected_total(i.away_lineup)
301 | home_projected = get_projected_total(i.home_lineup)
302 | diffScore = away_projected - home_projected
303 |
304 | if (abs(diffScore) <= 15 and (not all_played(i.away_lineup) or not all_played(i.home_lineup))):
305 | score += ['%4s %6.2f - %6.2f %s' % (i.home_team.team_abbrev, i.home_projected,
306 | i.away_projected, i.away_team.team_abbrev)]
307 |
308 | if not score:
309 | return ('')
310 | text = ['Projected Close Scores'] + score
311 | return '\n'.join(text)
312 |
313 |
314 | def get_waiver_report(league, faab=False):
315 | """
316 | This function generates a waiver report for a given league.
317 | The report lists all the waiver transactions that occurred on the current day,
318 | including the team that made the transaction, the player added and the player dropped (if applicable).
319 |
320 | Parameters
321 | ----------
322 | league: object
323 | The league object for which the report is being generated
324 | faab : bool, optional
325 | A flag to indicate whether the report should include FAAB amount spent, by default False.
326 |
327 | Returns
328 | -------
329 | str
330 | A string containing the waiver report
331 | """
332 |
333 | # Get the recent activity of the league
334 | activities = league.recent_activity(50)
335 | # Initialize an empty list to store the report
336 | report = []
337 | # Get the current date
338 | today = date.today().strftime('%Y-%m-%d')
339 | text = ''
340 |
341 | # Iterate through each activity
342 | for activity in activities:
343 | actions = activity.actions
344 | # Get the date of the activity
345 | d2 = date.fromtimestamp(activity.date / 1000).strftime('%Y-%m-%d')
346 | # Check if the activity is from today
347 | if d2 == today:
348 | # Check if the activity is a waiver add (not a drop)
349 | if len(actions) == 1 and actions[0][1] == 'WAIVER ADDED':
350 | # Get the team, player name and position
351 | team_name = actions[0][0].team_name
352 | player_name = actions[0][2].name
353 | player_position = actions[0][2].position
354 | if faab:
355 | # Get the FAAB amount spent
356 | faab_amount = actions[0][3]
357 | # Add the transaction to the report
358 | s = f'{team_name} \nADDED {player_position} {player_name} (${faab_amount})\n'
359 | else:
360 | s = f'{team_name} \nADDED {player_position} {player_name}\n'
361 | report += [s.lstrip()]
362 | elif len(actions) > 1:
363 | if actions[0][1] == 'WAIVER ADDED' or actions[1][1] == 'WAIVER ADDED':
364 | if actions[0][1] == 'WAIVER ADDED':
365 | if faab:
366 | s = '%s \nADDED %s %s ($%s)\nDROPPED %s %s\n' % (
367 | actions[0][0].team_name, actions[0][2].position, actions[0][2].name,
368 | actions[0][3], actions[1][2].position, actions[1][2].name)
369 | else:
370 | s = '%s \nADDED %s %s\nDROPPED %s %s\n' % (
371 | actions[0][0].team_name, actions[0][2].position, actions[0][2].name,
372 | actions[1][2].position, actions[1][2].name)
373 | else:
374 | if faab:
375 | s = '%s \nADDED %s %s ($%s)\nDROPPED %s %s\n' % (
376 | actions[0][0].team_name, actions[1][2].position, actions[1][2].name,
377 | actions[1][3], actions[0][2].position, actions[0][2].name)
378 | else:
379 | s = '%s \nADDED %s %s\nDROPPED %s %s\n' % (
380 | actions[0][0].team_name, actions[1][2].position, actions[1][2].name,
381 | actions[0][2].position, actions[0][2].name)
382 | report += [s.lstrip()]
383 |
384 | report.reverse()
385 |
386 | if not report:
387 | report += ['No waiver transactions']
388 | else:
389 | text = ['Waiver Report %s: ' % today] + report
390 |
391 | return '\n'.join(text)
392 |
393 |
394 | def get_power_rankings(league, week=None):
395 | """
396 | This function returns the power rankings of the teams in the league for a specific week,
397 | along with the change in power ranking number and playoff percentage from the previous week.
398 | If the week is not provided, it defaults to the current week.
399 | The power rankings are determined using a 2 step dominance algorithm,
400 | as well as a combination of points scored and margin of victory.
401 | It's weighted 80/15/5 respectively.
402 |
403 | Parameters
404 | ----------
405 | league: object
406 | The league object for which the power rankings are being generated
407 | week : int, optional
408 | The week for which the power rankings are to be returned (default is current week)
409 |
410 | Returns
411 | -------
412 | str
413 | A string representing the power rankings with changes from the previous week
414 | """
415 |
416 | # Check if the week is provided, if not use the previous week
417 | if not week:
418 | week = league.current_week - 1
419 |
420 | p_rank_up_emoji = "🟢"
421 | p_rank_down_emoji = "🔻"
422 | p_rank_same_emoji = "🟰"
423 |
424 | # Get the power rankings for the previous 2 weeks
425 | current_rankings = league.power_rankings(week=week)
426 | previous_rankings = league.power_rankings(week=week-1) if week > 1 else []
427 |
428 | # Normalize the scores
429 | def normalize_rankings(rankings):
430 | if not rankings:
431 | return []
432 | max_score = max(float(score) for score, _ in rankings)
433 | return [(f"{99.99 * float(score) / max_score:.2f}", team) for score, team in rankings]
434 |
435 |
436 | normalized_current_rankings = normalize_rankings(current_rankings)
437 | normalized_previous_rankings = normalize_rankings(previous_rankings)
438 |
439 | # Convert normalized previous rankings to a dictionary for easy lookup
440 | previous_rankings_dict = {team.team_abbrev: score for score, team in normalized_previous_rankings}
441 |
442 | # Prepare the output string
443 | rankings_text = ['Power Rankings (Playoff %)']
444 | for normalized_current_score, current_team in normalized_current_rankings:
445 | team_abbrev = current_team.team_abbrev
446 | rank_change_text = ''
447 |
448 | # Check if the team was present in the normalized previous rankings
449 | if team_abbrev in previous_rankings_dict:
450 | previous_score = previous_rankings_dict[team_abbrev]
451 | rank_change_percent = ((float(normalized_current_score) - float(previous_score)) / float(previous_score)) * 100
452 | rank_change_emoji = p_rank_up_emoji if rank_change_percent > 0 else p_rank_down_emoji if rank_change_percent < 0 else p_rank_same_emoji
453 | rank_change_text = f"[{rank_change_emoji}{abs(rank_change_percent):4.1f}%]"
454 |
455 | rankings_text.append(f"{normalized_current_score}{rank_change_text} ({current_team.playoff_pct:4.1f}) - {team_abbrev}")
456 |
457 | return '\n'.join(rankings_text)
458 |
459 |
460 | def get_starter_counts(league):
461 | """
462 | Get the number of starters for each position
463 |
464 | Parameters
465 | ----------
466 | league : object
467 | The league object for which the starter counts are being generated
468 |
469 | Returns
470 | -------
471 | dict
472 | A dictionary containing the number of players at each position within the starting lineup.
473 | """
474 |
475 | return {pos: cnt for pos, cnt in league.settings.position_slot_counts.items() if pos not in ['BE', 'IR'] and cnt != 0}
476 |
477 |
478 | def best_flex(flexes, player_pool, num):
479 | """
480 | Given a list of flex positions, a dictionary of player pool, and a number of players to return,
481 | this function returns the best flex players from the player pool.
482 |
483 | Parameters
484 | ----------
485 | flexes : list
486 | a list of strings representing the flex positions
487 | player_pool : dict
488 | a dictionary with keys as position and values as a dictionary with player name as key and value as score
489 | num : int
490 | number of players to return from the player pool
491 |
492 | Returns
493 | ----------
494 | best : dict
495 | a dictionary containing the best flex players from the player pool
496 | player_pool : dict
497 | the updated player pool after removing the best flex players
498 | """
499 |
500 | pool = {}
501 | # iterate through each flex position
502 | for flex_position in flexes:
503 | # add players from flex position to the pool
504 | try:
505 | pool = pool | player_pool[flex_position]
506 | except KeyError:
507 | pass
508 | # sort the pool by score in descending order
509 | pool = {k: v for k, v in sorted(pool.items(), key=lambda item: item[1], reverse=True)}
510 | # get the top num players from the pool
511 | best = dict(list(pool.items())[:num])
512 | # remove the best flex players from the player pool
513 | for pos in player_pool:
514 | for p in best:
515 | if p in player_pool[pos]:
516 | player_pool[pos].pop(p)
517 | return best, player_pool
518 |
519 |
520 | def optimal_lineup_score(lineup, starter_counts):
521 | """
522 | This function returns the optimal lineup score based on the provided lineup and starter counts.
523 |
524 | Parameters
525 | ----------
526 | lineup : list
527 | A list of player objects for which the optimal lineup score is being generated
528 | starter_counts : dict
529 | A dictionary containing the number of starters for each position
530 |
531 | Returns
532 | -------
533 | tuple
534 | A tuple containing the optimal lineup score, the provided lineup score, the difference between the two scores,
535 | and the percentage of the provided lineup's score compared to the optimal lineup's score.
536 | """
537 |
538 | best_lineup = {}
539 | position_players = {}
540 |
541 | # get all players and points
542 | score = 0
543 | score_pct = 0
544 | best_score = 0
545 |
546 | for player in lineup:
547 | try:
548 | position_players[player.position][player.name] = player.points
549 | except KeyError:
550 | position_players[player.position] = {}
551 | position_players[player.position][player.name] = player.points
552 | if player.slot_position not in ['BE', 'IR']:
553 | score += player.points
554 |
555 | # sort players by position for points
556 | for position in starter_counts:
557 | try:
558 | position_players[position] = {k: v for k, v in sorted(
559 | position_players[position].items(), key=lambda item: item[1], reverse=True)}
560 | best_lineup[position] = dict(list(position_players[position].items())[:starter_counts[position]])
561 | position_players[position] = dict(list(position_players[position].items())[starter_counts[position]:])
562 | except KeyError:
563 | best_lineup[position] = {}
564 |
565 | # flexes. need to figure out best in other single positions first
566 | for position in starter_counts:
567 | # flex
568 | if 'D/ST' not in position and '/' in position:
569 | flex = position.split('/')
570 | result = best_flex(flex, position_players, starter_counts[position])
571 | best_lineup[position] = result[0]
572 | position_players = result[1]
573 |
574 | # Offensive Player. need to figure out best in other positions first
575 | if 'OP' in starter_counts:
576 | flex = ['RB', 'WR', 'TE', 'QB']
577 | result = best_flex(flex, position_players, starter_counts['OP'])
578 | best_lineup['OP'] = result[0]
579 | position_players = result[1]
580 |
581 | # Defensive Player. need to figure out best in other positions first
582 | if 'DP' in starter_counts:
583 | flex = ['DT', 'DE', 'LB', 'CB', 'S']
584 | result = best_flex(flex, position_players, starter_counts['DP'])
585 | best_lineup['DP'] = result[0]
586 | position_players = result[1]
587 |
588 | for position in best_lineup:
589 | best_score += sum(best_lineup[position].values())
590 |
591 | if best_score != 0:
592 | score_pct = (score / best_score) * 100
593 |
594 | return (best_score, score, best_score - score, score_pct)
595 |
596 |
597 | def optimal_team_scores(league, week=None, full_report=False, recap=False):
598 | """
599 | This function returns the optimal team scores or managers.
600 |
601 | Parameters
602 | ----------
603 | league : object
604 | The league object for which the optimal team scores are being generated
605 | week : int, optional
606 | The week for which the optimal team scores are to be returned (default is the previous week)
607 | full_report : bool, optional
608 | A boolean indicating if a full report should be returned (default is False)
609 |
610 | Returns
611 | -------
612 | str or tuple
613 | If full_report is True, a string representing the full report of the optimal team scores.
614 | If full_report is False, a tuple containing the best and worst manager strings.
615 | """
616 |
617 | if not week:
618 | week = league.current_week - 1
619 | box_scores = league.box_scores(week=week)
620 | results = []
621 | best_scores = {}
622 | starter_counts = get_starter_counts(league)
623 |
624 | for i in box_scores:
625 | if i.home_team != 0:
626 | best_scores[i.home_team] = optimal_lineup_score(i.home_lineup, starter_counts)
627 | if i.away_team != 0:
628 | best_scores[i.away_team] = optimal_lineup_score(i.away_lineup, starter_counts)
629 |
630 | best_scores = {key: value for key, value in sorted(best_scores.items(), key=lambda item: item[1][3], reverse=True)}
631 |
632 | if full_report:
633 | i = 1
634 | for score in best_scores:
635 | s = ['%2d: %4s: %6.2f (%6.2f - %.2f%%)' %
636 | (i, score.team_abbrev, best_scores[score][0],
637 | best_scores[score][1], best_scores[score][3])]
638 | results += s
639 | i += 1
640 |
641 | text = ['Optimal Scores: (Actual - % of optimal)'] + results
642 | return '\n'.join(text)
643 | else:
644 | num_teams = 0
645 | team_names = ''
646 | for score in best_scores:
647 | if best_scores[score][3] > 99.8:
648 | num_teams += 1
649 | team_names += score.team_name + ', '
650 | else:
651 | break
652 |
653 | if num_teams <= 1:
654 | best = next(iter(best_scores.items()))
655 | best_mgr_str = ['🤖 Best Manager 🤖'] + ['%s scored %.2f%% of their optimal score!' % (best[0].team_name, best[1][3])]
656 | else:
657 | team_names = team_names[:-2]
658 | best_mgr_str = ['🤖 Best Managers 🤖'] + [f'{team_names} scored their optimal score!']
659 |
660 | worst = best_scores.popitem()
661 | if recap:
662 | return worst[0].team_abbrev
663 |
664 | worst_mgr_str = ['🤡 Worst Manager 🤡'] + ['%s left %.2f points on their bench. Only scoring %.2f%% of their optimal score.' %
665 | (worst[0].team_name, worst[1][0] - worst[1][1], worst[1][3])]
666 |
667 | return (best_mgr_str + worst_mgr_str)
668 |
669 |
670 | def get_achievers_trophy(league, week=None, recap=False):
671 | """
672 | This function returns the overachiever and underachiever of the league
673 | based on the difference between the projected score and the actual score.
674 |
675 | Parameters
676 | ----------
677 | league: object
678 | The league object for which the overachiever and underachiever are being determined
679 | week : int, optional
680 | The week for which the overachiever and underachiever are to be returned (default is current week)
681 |
682 | Returns
683 | -------
684 | str
685 | A string representing the overachiever and underachiever of the league
686 | """
687 |
688 | box_scores = league.box_scores(week=week)
689 | high_achiever_str = ['📈 Overachiever 📈']
690 | low_achiever_str = ['📉 Underachiever 📉']
691 | best_performance = -9999
692 | worst_performance = 9999
693 | for i in box_scores:
694 | home_performance = i.home_score - i.home_projected
695 | away_performance = i.away_score - i.away_projected
696 |
697 | if i.home_team != 0:
698 | if home_performance > best_performance:
699 | best_performance = home_performance
700 | over_achiever = i.home_team
701 | if home_performance < worst_performance:
702 | worst_performance = home_performance
703 | under_achiever = i.home_team
704 | if i.away_team != 0:
705 | if away_performance > best_performance:
706 | best_performance = away_performance
707 | over_achiever = i.away_team
708 | if away_performance < worst_performance:
709 | worst_performance = away_performance
710 | under_achiever = i.away_team
711 |
712 | if recap:
713 | return over_achiever.team_abbrev, under_achiever.team_abbrev
714 |
715 | if best_performance > 0:
716 | high_achiever_str += ['%s was %.2f points over their projection' % (over_achiever.team_name, best_performance)]
717 | else:
718 | high_achiever_str += ['No team out performed their projection']
719 |
720 | if worst_performance < 0:
721 | low_achiever_str += ['%s was %.2f points under their projection' % (under_achiever.team_name, abs(worst_performance))]
722 | else:
723 | low_achiever_str += ['No team was worse than their projection']
724 |
725 | return (high_achiever_str + low_achiever_str)
726 |
727 |
728 | def get_weekly_score_with_win_loss(league, week=None):
729 | box_scores = league.box_scores(week=week)
730 | weekly_scores = {}
731 | for i in box_scores:
732 | if i.home_team != 0 and i.away_team != 0:
733 | if i.home_score > i.away_score:
734 | weekly_scores[i.home_team] = [i.home_score, 'W']
735 | weekly_scores[i.away_team] = [i.away_score, 'L']
736 | else:
737 | weekly_scores[i.home_team] = [i.home_score, 'L']
738 | weekly_scores[i.away_team] = [i.away_score, 'W']
739 | return dict(sorted(weekly_scores.items(), key=lambda item: item[1], reverse=True))
740 |
741 |
742 | def get_lucky_trophy(league, week=None, recap=False):
743 | """
744 | This function takes in a league object and an optional week parameter. It retrieves the box scores for the specified league and week, and creates a dictionary with the weekly scores for each team. The teams are sorted in descending order by their scores, and the team with the lowest score and won is determined to be the lucky team for the week. The team with the highest score and lost is determined to be the unlucky team for the week. The function returns a list containing the lucky and unlucky teams, along with their records for the week.
745 | Parameters:
746 | league (object): A league object containing information about the league and its teams.
747 | week (int, optional): The week for which the box scores should be retrieved. If no week is specified, the current week will be used.
748 | Returns:
749 | list: A list containing the lucky and unlucky teams, along with their records for the week.
750 | """
751 | weekly_scores = get_weekly_score_with_win_loss(league, week=week)
752 | losses = 0
753 | unlucky_record = ''
754 | lucky_record = ''
755 | num_teams = len(weekly_scores) - 1
756 |
757 | for t in weekly_scores:
758 | if weekly_scores[t][1] == 'L':
759 | unlucky_team = t
760 | unlucky_record = str(num_teams - losses) + '-' + str(losses)
761 | break
762 | losses += 1
763 |
764 | wins = 0
765 | weekly_scores = dict(sorted(weekly_scores.items(), key=lambda item: item[1]))
766 | for t in weekly_scores:
767 | if weekly_scores[t][1] == 'W':
768 | lucky_team = t
769 | lucky_record = str(wins) + '-' + str(num_teams - wins)
770 | break
771 | wins += 1
772 |
773 | if recap:
774 | return lucky_team.team_abbrev, unlucky_team.team_abbrev, weekly_scores
775 |
776 | lucky_str = ['🍀 Lucky 🍀']+['%s was %s against the league, but still got the win' % (lucky_team.team_name, lucky_record)]
777 | unlucky_str = ['😡 Unlucky 😡']+['%s was %s against the league, but still took an L' % (unlucky_team.team_name, unlucky_record)]
778 | return (lucky_str + unlucky_str)
779 |
780 |
781 | def get_trophies(league, week=None, recap=False):
782 | """
783 | Returns trophies for the highest score, lowest score, closest score, and biggest win.
784 |
785 | Parameters
786 | ----------
787 | league : object
788 | The league object for which the trophies are to be returned
789 | week : int, optional
790 | The week for which the trophies are to be returned (default is current week)
791 |
792 | Returns
793 | -------
794 | str
795 | A string representing the trophies
796 | """
797 | if not week:
798 | week = league.current_week - 1
799 |
800 | matchups = league.box_scores(week=week)
801 | low_score = 99999999
802 | high_score = -1
803 | closest_score = 99999999
804 | biggest_blowout = -1
805 |
806 | for i in matchups:
807 | if i.home_team != 0:
808 | if i.home_score > high_score:
809 | high_score = i.home_score
810 | high_team = i.home_team
811 | if i.home_score < low_score:
812 | low_score = i.home_score
813 | low_team = i.home_team
814 | if i.away_team != 0:
815 | if i.away_score > high_score:
816 | high_score = i.away_score
817 | high_team = i.away_team
818 | if i.away_score < low_score:
819 | low_score = i.away_score
820 | low_team = i.away_team
821 |
822 | if i.away_team != 0 and i.home_team != 0:
823 | if i.away_score - i.home_score != 0 and \
824 | abs(i.away_score - i.home_score) < closest_score:
825 | closest_score = abs(i.away_score - i.home_score)
826 | if i.away_score - i.home_score < 0:
827 | close_winner = i.home_team
828 | close_loser = i.away_team
829 | else:
830 | close_winner = i.away_team
831 | close_loser = i.home_team
832 | if abs(i.away_score - i.home_score) > biggest_blowout:
833 | biggest_blowout = abs(i.away_score - i.home_score)
834 | if i.away_score - i.home_score < 0:
835 | ownerer = i.home_team
836 | blown_out = i.away_team
837 | else:
838 | ownerer = i.away_team
839 | blown_out = i.home_team
840 |
841 | if (recap):
842 | return high_team.team_abbrev, low_team.team_abbrev, blown_out.team_abbrev, close_winner.team_abbrev
843 |
844 | high_score_str = ['👑 High score 👑']+['%s with %.2f points' % (high_team.team_name, high_score)]
845 | low_score_str = ['💩 Low score 💩']+['%s with %.2f points' % (low_team.team_name, low_score)]
846 | close_score_str = ['😅 Close win 😅']+['%s barely beat %s by %.2f points' %
847 | (close_winner.team_name, close_loser.team_name, closest_score)]
848 | blowout_str = ['😱 Blow out 😱']+['%s blew out %s by %.2f points' % (ownerer.team_name, blown_out.team_name, biggest_blowout)]
849 |
850 | text = ['Trophies of the week:'] + high_score_str + low_score_str + blowout_str + close_score_str + \
851 | get_lucky_trophy(league, week) + get_achievers_trophy(league, week) + optimal_team_scores(league, week)
852 | return '\n'.join(text)
853 |
--------------------------------------------------------------------------------
/gamedaybot/espn/scheduler.py:
--------------------------------------------------------------------------------
1 | from apscheduler.schedulers.blocking import BlockingScheduler
2 | from gamedaybot.espn.espn_bot import espn_bot
3 | from gamedaybot.espn.env_vars import get_env_vars
4 |
5 |
6 | def scheduler():
7 | """
8 | This function is used to schedule jobs to send messages.
9 |
10 | Parameters
11 | ----------
12 | None
13 |
14 | Returns
15 | -------
16 | None
17 | """
18 | data = get_env_vars()
19 | game_timezone = 'America/New_York'
20 | sched = BlockingScheduler(job_defaults={'misfire_grace_time': 15 * 60})
21 | ff_start_date = data['ff_start_date']
22 | ff_end_date = data['ff_end_date']
23 | my_timezone = data['my_timezone']
24 |
25 | # close scores (within 15.99 points): monday evening at 6:30pm east coast time.
26 | # power rankings: tuesday evening at 6:30pm local time.
27 | # trophies: tuesday morning at 7:30am local time.
28 | # standings: wednesday morning at 7:30am local time.
29 | # waiver report: wednesday morning at 7:31am local time. (optional)
30 | # matchups: thursday evening at 7:30pm east coast time.
31 | # score update: friday, monday, and tuesday morning at 7:30am local time.
32 | # player monitor report: sunday morning at 7:30am local time.
33 | # score update: sunday at 4pm, 8pm east coast time.
34 |
35 | sched.add_job(espn_bot, 'cron', ['get_close_scores'], id='close_scores',
36 | day_of_week='mon', hour=18, minute=30, start_date=ff_start_date, end_date=ff_end_date,
37 | timezone=game_timezone, replace_existing=True)
38 | sched.add_job(espn_bot, 'cron', ['get_power_rankings'], id='power_rankings',
39 | day_of_week='tue', hour=18, minute=30, start_date=ff_start_date, end_date=ff_end_date,
40 | timezone=my_timezone, replace_existing=True)
41 | sched.add_job(espn_bot, 'cron', ['get_final'], id='final',
42 | day_of_week='tue', hour=7, minute=30, start_date=ff_start_date, end_date=ff_end_date,
43 | timezone=my_timezone, replace_existing=True)
44 | sched.add_job(espn_bot, 'cron', ['get_standings'], id='standings',
45 | day_of_week='wed', hour=7, minute=30, start_date=ff_start_date, end_date=ff_end_date,
46 | timezone=my_timezone, replace_existing=True)
47 | sched.add_job(espn_bot, 'cron', ['get_waiver_report'], id='waiver_report',
48 | day_of_week='wed', hour=7, minute=31, start_date=ff_start_date, end_date=ff_end_date,
49 | timezone=my_timezone, replace_existing=True)
50 |
51 | if data['daily_waiver']:
52 | sched.add_job(
53 | espn_bot, 'cron', ['get_waiver_report'],
54 | id='waiver_report', day_of_week='mon, tue, thu, fri, sat, sun', hour=7, minute=31, start_date=ff_start_date,
55 | end_date=ff_end_date, timezone=my_timezone, replace_existing=True)
56 |
57 | sched.add_job(espn_bot, 'cron', ['get_matchups'], id='matchups',
58 | day_of_week='thu', hour=19, minute=30, start_date=ff_start_date, end_date=ff_end_date,
59 | timezone=game_timezone, replace_existing=True)
60 | sched.add_job(espn_bot, 'cron', ['get_scoreboard_short'], id='scoreboard1',
61 | day_of_week='fri,mon', hour=7, minute=30, start_date=ff_start_date, end_date=ff_end_date,
62 | timezone=my_timezone, replace_existing=True)
63 |
64 | if data['monitor_report']:
65 | sched.add_job(espn_bot, 'cron', ['get_monitor'], id='monitor',
66 | day_of_week='sun', hour=7, minute=30, start_date=ff_start_date, end_date=ff_end_date,
67 | timezone=my_timezone, replace_existing=True)
68 |
69 | sched.add_job(espn_bot, 'cron', ['get_scoreboard_short'], id='scoreboard2',
70 | day_of_week='sun', hour='16,20', start_date=ff_start_date, end_date=ff_end_date,
71 | timezone=game_timezone, replace_existing=True)
72 |
73 | print("Ready!")
74 | sched.start()
75 |
--------------------------------------------------------------------------------
/gamedaybot/espn/season_recap.py:
--------------------------------------------------------------------------------
1 | import os
2 | # import pandas as pd
3 | # import dataframe_image as dfi
4 | if os.environ.get("AWS_EXECUTION_ENV") is not None:
5 | import espn.functionality as espn
6 | else:
7 | # For local use
8 | import sys
9 | sys.path.insert(1, os.path.abspath('.'))
10 | import gamedaybot.espn.functionality as espn
11 |
12 |
13 | def trophy_recap(league):
14 | """
15 | This function takes in a league object and returns a string representing the trophies earned by each team in the league.
16 |
17 | Parameters
18 | ----------
19 | league : object
20 | A league object from the ESPN Fantasy API.
21 |
22 | Returns
23 | -------
24 | str
25 | A string that contains the team names and the number of trophies earned for each team
26 | """
27 |
28 | ICONS = ['👑', '💩', '😱', '😅', '🍀', '😡', '📈', '📉', '🤡']
29 | legend = ['*LEGEND*', '👑: Most Points', '💩: Least Points', '😱: Blown out', '😅: Close wins', '🍀: Lucky',
30 | '😡: Unlucky', '📈: Most over projection', '📉: Most under projection', '🤡: Most points left on bench']
31 | team_trophies = {}
32 | team_names = []
33 |
34 | for team in league.teams:
35 | # Initialize trophy count for each team
36 | team_trophies[team.team_abbrev] = [0 for i in range(len(ICONS))]
37 | team_names.append(team.team_abbrev)
38 |
39 | for week in range(1, league.current_week):
40 | # Get high score, low score, blown out, and close win trophies
41 | high_score_team, low_score_team, blown_out_team, close_win_team = espn.get_trophies(league=league, week=week, recap=True)
42 | team_trophies[high_score_team][0] += 1
43 | team_trophies[low_score_team][1] += 1
44 | team_trophies[blown_out_team][2] += 1
45 | team_trophies[close_win_team][3] += 1
46 |
47 | # Get lucky and unlucky trophies
48 | lucky_team, unlucky_team, scores = espn.get_lucky_trophy(league=league, week=week, recap=True)
49 | team_trophies[lucky_team][4] += 1
50 | team_trophies[unlucky_team][5] += 1
51 |
52 | # Get overachiever and underachiever trophies
53 | overachiever_team, underachiever_team = espn.get_achievers_trophy(league=league, week=week, recap=True)
54 | team_trophies[overachiever_team][6] += 1
55 | team_trophies[underachiever_team][7] += 1
56 |
57 | # Get most points left on bench trophy
58 | best_manager_team = espn.optimal_team_scores(league=league, week=week, recap=True)
59 | team_trophies[best_manager_team][8] += 1
60 |
61 | result = 'Season Recap!\n'
62 | result += "Team".ljust(7, ' ')
63 | for icon in ICONS:
64 | result += icon + ' '
65 | result += '\n'
66 | for team_name, trophies in team_trophies.items():
67 | result += f"{team_name.ljust(5, ' ')}: {trophies}\n"
68 | result += '\n'.join(legend)
69 |
70 | # Pretty picture
71 | ### Libraries make lambda size too big
72 | # df = pd.DataFrame.from_dict(team_trophies, orient='index', columns=ICONS)
73 | # df_styled = df.style.background_gradient(cmap='Greens')
74 | # dfi.export(df_styled, '/tmp/season_recap.png')
75 | return (result)
76 |
77 |
78 | def win_matrix(league):
79 | """
80 | This function takes in a league and returns a string of the standings if every team played every other team every week.
81 | The standings are sorted by winning percentage, and the string includes the team abbreviation, wins, and losses.
82 |
83 | Parameters
84 | ----------
85 | league : object
86 | A league object from the ESPN Fantasy API.
87 |
88 | Returns
89 | -------
90 | str
91 | A string of the standings in the format of "position. team abbreviation (wins-losses)"
92 | """
93 |
94 | team_record = {team.team_abbrev: [0, 0] for team in league.teams}
95 |
96 | for week in range(1, league.current_week):
97 | scores = espn.get_weekly_score_with_win_loss(league=league, week=week)
98 | losses = 0
99 | for team in scores:
100 | team_record[team.team_abbrev][0] += len(scores) - 1 - losses
101 | team_record[team.team_abbrev][1] += losses
102 | losses += 1
103 |
104 | team_record = dict(sorted(team_record.items(), key=lambda item: item[1][0] / item[1][1], reverse=True))
105 |
106 | standings_txt = ["Standings if everyone played every team every week"]
107 | pos = 1
108 | for team in team_record:
109 | standings_txt += [f"{pos:2}. {team:4} ({team_record[team][0]}-{team_record[team][1]})"]
110 | pos += 1
111 |
112 | return '\n'.join(standings_txt)
113 |
--------------------------------------------------------------------------------
/gamedaybot/utils/util.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | import os
3 | from typing import List
4 |
5 |
6 | def str_to_bool(check: str) -> bool:
7 | """
8 | Converts a string to a boolean value.
9 |
10 | Parameters
11 | ----------
12 | check : str
13 | The string to be converted to a boolean value.
14 |
15 | Returns
16 | -------
17 | bool
18 | The boolean value of the string.
19 | """
20 | try:
21 | return check.strip().lower() in ("yes", "true", "t", "1")
22 | except:
23 | return False
24 |
25 |
26 |
27 |
28 | def str_limit_check(text: str, limit: int) -> List[str]:
29 | """
30 | Splits a string into parts of a maximum length.
31 |
32 | Parameters
33 | ----------
34 | text : str
35 | The text to be split.
36 | limit : int
37 | The maximum length of each split string part.
38 |
39 | Returns
40 | -------
41 | split_str : List[str]
42 | A list of strings split by the maximum length.
43 | """
44 | if not isinstance(text, str):
45 | raise TypeError("Input must be a string")
46 | if limit <= 0:
47 | raise ValueError("Limit must be greater than 0")
48 |
49 | # Special case: For empty strings and strings with only spaces or newlines
50 | if len(text.strip()) == 0:
51 | return [""]
52 |
53 | split_str = []
54 | remaining_text = text.strip()
55 |
56 | while len(remaining_text) > 0:
57 | if len(remaining_text) > limit:
58 | part_one = remaining_text[:limit]
59 | last_newline = part_one.rfind('\n')
60 |
61 | # Remove extra newline if it's the last character
62 | if last_newline == len(part_one) - 1:
63 | last_newline -= 1
64 |
65 | # If a newline exists within the limit, split there
66 | if last_newline != -1:
67 | part_one = remaining_text[:last_newline]
68 | remaining_text = remaining_text[last_newline + 1:]
69 | else:
70 | remaining_text = remaining_text[limit:]
71 |
72 | # Only strip if this isn't the first part (to pass the 'test_str_limit_check_over_limit' test)
73 | if split_str:
74 | split_str.append(part_one.strip())
75 | else:
76 | split_str.append(part_one)
77 | else:
78 | split_str.append(remaining_text.strip())
79 | remaining_text = ""
80 |
81 | # Remove any empty strings that might be produced due to stripping
82 | split_str = [s for s in split_str if s]
83 |
84 | return split_str
85 |
86 |
87 | def str_to_datetime(date_str: str) -> datetime:
88 | """
89 | Converts a string in the format of 'YYYY-MM-DD' to a datetime object.
90 |
91 | Parameters
92 | ----------
93 | date_str : str
94 | The string to be converted to a datetime object in 'YYYY-MM-DD' format.
95 |
96 | Returns
97 | -------
98 | datetime
99 | The datetime object created from the input string.
100 |
101 | Raises
102 | ------
103 | TypeError
104 | If the input is not a string.
105 | ValueError
106 | If the input does not match the expected date format.
107 | """
108 | if not isinstance(date_str, str):
109 | raise TypeError("Input must be a string")
110 |
111 | date_format = "%Y-%m-%d"
112 | try:
113 | return datetime.strptime(date_str.strip(), date_format)
114 | except ValueError:
115 | raise ValueError("Invalid date format. Use 'YYYY-MM-DD' format.")
116 |
117 |
118 | def currently_in_season(season_start_date=None, season_end_date=None, current_date=None):
119 | """
120 | Check if the current date is during the football season.
121 |
122 | Parameters
123 | ----------
124 | season_start_date : str, optional
125 | The start date of the season in the format "YYYY-MM-DD", by default None.
126 | season_end_date : str, optional
127 | The end date of the season in the format "YYYY-MM-DD", by default None.
128 | current_date : datetime, optional
129 | The current date to compare against the season range, by default None.
130 |
131 | Returns
132 | -------
133 | bool
134 | True if the current date is within the range of dates for the football season, False otherwise.
135 |
136 | Raises
137 | ------
138 | ValueError
139 | If the season start or end date is not in the correct format "YYYY-MM-DD".
140 | If the current_date is not a datetime object.
141 | """
142 |
143 | if not current_date:
144 | current_date = datetime.now()
145 |
146 | if not season_start_date:
147 | try:
148 | season_start_date = str(os.environ["START_DATE"])
149 | except KeyError:
150 | raise ValueError("Season start date is not provided and not found in environment variables.")
151 |
152 | if not season_end_date:
153 | try:
154 | season_end_date = str(os.environ["END_DATE"])
155 | except KeyError:
156 | raise ValueError("Season end date is not provided and not found in environment variables.")
157 |
158 | season_start_date = str_to_datetime(season_start_date)
159 | season_end_date = str_to_datetime(season_end_date)
160 |
161 | return season_start_date <= current_date <= season_end_date
162 |
--------------------------------------------------------------------------------
/requirements-test.txt:
--------------------------------------------------------------------------------
1 | pytest
2 | pytest-cov
3 | codecov
4 | requests_mock
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | urllib3<=2.2.3
2 | flake8==3.3.0
3 | apscheduler>=3.3.0,<4.0.0
4 | requests>=2.0.0,<3.0.0
5 | espn_api>=0.38.1
6 | datetime
7 |
--------------------------------------------------------------------------------
/runtime.txt:
--------------------------------------------------------------------------------
1 | python-3.9.13
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | max-line-length = 120
3 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup(
4 | name='gamedaybot',
5 |
6 | packages=['gamedaybot'],
7 |
8 | include_package_data=True,
9 |
10 | version='0.3.1',
11 |
12 | description='ESPN fantasy football Chat Bot',
13 |
14 | author='Dean Carlson',
15 |
16 | author_email='deantcarlson@gmail.com',
17 |
18 | install_requires=['urllib3<=2.2.3', 'espn_api>=0.38.1', 'requests>=2.0.0,<3.0.0', 'apscheduler>=3.3.0,<4.0.0', 'datetime'],
19 |
20 | url='https://github.com/dtcarls/fantasy_football_chat_bot',
21 |
22 | classifiers=[
23 | 'Natural Language :: English',
24 | 'Operating System :: OS Independent',
25 | 'Programming Language :: Python :: 3',
26 | ]
27 | )
28 |
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import requests_mock
3 |
4 |
5 | @pytest.fixture
6 | def mock_requests():
7 | with requests_mock.Mocker() as m:
8 | yield m
9 |
--------------------------------------------------------------------------------
/tests/dry_run_all_functions.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | sys.path.insert(1, os.path.abspath('.'))
4 |
5 | from espn_api.football import League
6 | import gamedaybot.espn.season_recap as recap
7 | import gamedaybot.espn.functionality as espn
8 | from gamedaybot.chat.discord import Discord
9 | from gamedaybot.chat.slack import Slack
10 | from gamedaybot.chat.groupme import GroupMe
11 |
12 | # LEAGUE_ID = os.environ["LEAGUE_ID"]
13 | # LEAGUE_YEAR = os.environ["LEAGUE_YEAR"]
14 |
15 | ## Manually populate
16 | LEAGUE_ID = 164483
17 | LEAGUE_YEAR = 2023
18 |
19 | league = League(league_id=LEAGUE_ID, year=LEAGUE_YEAR)
20 | print(espn.get_scoreboard_short(league))
21 | print(espn.get_projected_scoreboard(league))
22 | print(espn.get_standings(league))
23 | print(espn.get_close_scores(league))
24 | print(espn.get_monitor(league))
25 | print(espn.get_matchups(league))
26 | print(espn.get_power_rankings(league))
27 | print(espn.get_trophies(league))
28 | print(espn.optimal_team_scores(league, full_report=True))
29 |
30 | print(recap.win_matrix(league))
31 | print(recap.trophy_recap(league))
32 |
33 | try:
34 | swid = os.environ["SWID"]
35 | except KeyError:
36 | swid = '{1}'
37 | try:
38 | espn_s2 = os.environ["ESPN_S2"]
39 | except KeyError:
40 | espn_s2 = '1'
41 |
42 | if swid != '{1}' and espn_s2 != '1':
43 | league = League(league_id=LEAGUE_ID, year=LEAGUE_YEAR, espn_s2=espn_s2, swid=swid)
44 | print(espn.get_waiver_report(league))
45 | print(espn.get_waiver_report(league, True))
46 |
47 | # bot = GroupMe(os.environ['BOT_ID'])
48 | # bot.send_message(recap.trophy_recap(league), file_path='/tmp/season_recap.png')
49 | # bot.send_message("hi", file_path='/tmp/season_recap.png')
50 | # bot.send_message("Testing")
51 |
52 | # discord_bot = Discord(os.environ['DISCORD_WEBHOOK_URL'])
53 | # discord_bot.send_message(recap.trophy_recap(league), file_path='/tmp/season_recap.png')
54 | # discord_bot.send_message("Testing")
55 |
56 | # slack_bot = Slack(os.environ['SLACK_WEBHOOK_URL'])
57 | # slack_bot.send_message(recap.trophy_recap(league), file_path='/tmp/season_recap.png')
58 | # slack_bot.send_message("Testing")
59 |
--------------------------------------------------------------------------------
/tests/test_discord.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sys
3 | import os
4 | sys.path.insert(1, os.path.abspath('.'))
5 | from gamedaybot.chat.discord import (Discord, DiscordException, )
6 |
7 |
8 | @pytest.mark.usefixtures("mock_requests")
9 | class TestDiscord:
10 | '''Test DiscordBot class'''
11 |
12 | def setup_method(self):
13 | self.url = "https://discordapp.com/api/webhooks/123/abc"
14 | self.test_bot = Discord(self.url)
15 | self.test_text = "This is a test."
16 |
17 | def test_send_message(self, mock_requests):
18 | '''Does the message send successfully?'''
19 | mock_requests.post(self.url, status_code=204)
20 | assert self.test_bot.send_message(self.test_text).status_code == 204
21 |
22 | def test_bad_bot_id(self, mock_requests):
23 | '''Does the expected error raise when a bot id is incorrect?'''
24 | mock_requests.post(self.url, status_code=404)
25 | with pytest.raises(DiscordException):
26 | self.test_bot.send_message(self.test_text)
27 |
--------------------------------------------------------------------------------
/tests/test_groupme.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sys
3 | import os
4 | sys.path.insert(1, os.path.abspath('.'))
5 | from gamedaybot.chat.groupme import (GroupMe, GroupMeException, )
6 |
7 |
8 | @pytest.mark.usefixtures("mock_requests")
9 | class TestGroupMeBot:
10 | '''Test GroupMeBot class'''
11 |
12 | def setup_method(self):
13 | self.test_bot = GroupMe("123456")
14 | self.test_text = "This is a test."
15 |
16 | def test_send_message(self, mock_requests):
17 | '''Does the message send successfully?'''
18 | mock_requests.post("https://api.groupme.com/v3/bots/post", status_code=202)
19 | assert self.test_bot.send_message(self.test_text).status_code == 202
20 |
21 | def test_bad_bot_id(self, mock_requests):
22 | '''Does the expected error raise when a bot id is incorrect?'''
23 | mock_requests.post("https://api.groupme.com/v3/bots/post", status_code=404)
24 | with pytest.raises(GroupMeException):
25 | self.test_bot.send_message(self.test_text)
26 |
--------------------------------------------------------------------------------
/tests/test_slack.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sys
3 | import os
4 | sys.path.insert(1, os.path.abspath('.'))
5 | from gamedaybot.chat.slack import (Slack, SlackException, )
6 |
7 |
8 | @pytest.mark.usefixtures("mock_requests")
9 | class TestSlack:
10 | '''Test SlackBot class'''
11 |
12 | def setup_method(self):
13 | self.url = "https://hooks.slack.com/services/A1B2C3/ABC1ABC2/abcABC1abcABC2"
14 | self.test_bot = Slack(self.url)
15 | self.test_text = "This is a test."
16 |
17 | def test_send_message(self, mock_requests):
18 | '''Does the message send successfully?'''
19 | mock_requests.post(self.url, status_code=200)
20 | assert self.test_bot.send_message(self.test_text).status_code == 200
21 |
22 | def test_bad_bot_id(self, mock_requests):
23 | '''Does the expected error raise when a bot id is incorrect?'''
24 | mock_requests.post(self.url, status_code=404)
25 | with pytest.raises(SlackException):
26 | self.test_bot.send_message(self.test_text)
27 |
--------------------------------------------------------------------------------
/tests/test_utils.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | import pytest
3 | import sys
4 | import os
5 | sys.path.insert(1, os.path.abspath('.'))
6 | import gamedaybot.utils.util as util
7 |
8 |
9 | class TestStringToBool:
10 | ############ For `str_to_bool`
11 | # Test cases for valid True values
12 | def test_str_to_bool_yes(self):
13 | assert util.str_to_bool("yes") == True
14 |
15 | def test_str_to_bool_true(self):
16 | assert util.str_to_bool("true") == True
17 |
18 | def test_str_to_bool_t(self):
19 | assert util.str_to_bool("t") == True
20 |
21 | def test_str_to_bool_one(self):
22 | assert util.str_to_bool("1") == True
23 |
24 | # Test cases for case insensitivity
25 | def test_str_to_bool_yes_caps(self):
26 | assert util.str_to_bool("YES") == True
27 |
28 | def test_str_to_bool_true_mixed_case(self):
29 | assert util.str_to_bool("TrUe") == True
30 |
31 | # Test cases for valid False values
32 | def test_str_to_bool_no(self):
33 | assert util.str_to_bool("no") == False
34 |
35 | def test_str_to_bool_false(self):
36 | assert util.str_to_bool("false") == False
37 |
38 | def test_str_to_bool_f(self):
39 | assert util.str_to_bool("f") == False
40 |
41 | def test_str_to_bool_zero(self):
42 | assert util.str_to_bool("0") == False
43 |
44 | # Test cases for random string values
45 | def test_str_to_bool_random_string(self):
46 | assert util.str_to_bool("random") == False
47 |
48 | # Test cases for empty string
49 | def test_str_to_bool_empty_string(self):
50 | assert util.str_to_bool("") == False
51 |
52 | # Test cases for numbers other than '1' and '0'
53 | def test_str_to_bool_two(self):
54 | assert util.str_to_bool("2") == False
55 |
56 | # Test cases for special characters
57 | def test_str_to_bool_special_characters(self):
58 | assert util.str_to_bool("!@#$%^&*()") == False
59 |
60 | # Test cases for spaces
61 | def test_str_to_bool_spaces(self):
62 | assert util.str_to_bool(" ") == False
63 |
64 | # Test cases for None
65 | def test_str_to_bool_none(self):
66 | assert util.str_to_bool(None) == False
67 |
68 | # Test cases for number
69 | def test_str_to_bool_int(self):
70 | assert util.str_to_bool(123) == False
71 |
72 | # Test cases for leading/trailing whitespaces
73 | def test_str_to_bool_leading_whitespace(self):
74 | assert util.str_to_bool(" true ") == True
75 |
76 | def test_str_to_bool_trailing_whitespace(self):
77 | assert util.str_to_bool("true ") == True
78 |
79 | class TestStringLimitCheck:
80 | ############ For `str_limit_check`
81 | def test_str_limit_check_within_limit(self):
82 | assert util.str_limit_check("a" * 200, 250) == ["a" * 200]
83 |
84 | def test_str_limit_check_at_limit(self):
85 | assert util.str_limit_check("a" * 250, 250) == ["a" * 250]
86 |
87 | def test_str_limit_check_over_limit(self):
88 | long_str = (
89 | "Waiver Report 2022-12-14: \nPAIN TRAIN "
90 | "\nADDED QB Trevor Lawrence ($0)\nDROPPED QB Kyler Murray\n\n"
91 | "Mightnt i the Grissle \nADDED WR Curtis Samuel ($11)\nDROPPED WR Kadarius Toney\n\n"
92 | "PAIN TRAIN \nADDED QB Kirk Cousins ($0)\nDROPPED RB Travis Homer\n\n"
93 | "Adam's Injuried Meatsaber \nADDED TE Evan Engram ($20)\nDROPPED TE Foster Moreau\n\n"
94 | "PAIN TRAIN \nADDED D/ST Chiefs D/ST ($6)\nDROPPED D/ST Ravens D/ST"
95 | )
96 | expected_output = [
97 | 'Waiver Report 2022-12-14: \nPAIN TRAIN \nADDED QB Trevor Lawrence ($0)\nDROPPED QB Kyler Murray\n\nMightnt i the Grissle \nADDED WR Curtis Samuel ($11)\nDROPPED WR Kadarius Toney\n\nPAIN TRAIN \nADDED QB Kirk Cousins ($0)\nDROPPED RB Travis Homer\n',
98 | "Adam's Injuried Meatsaber \nADDED TE Evan Engram ($20)\nDROPPED TE Foster Moreau\n\nPAIN TRAIN \nADDED D/ST Chiefs D/ST ($6)\nDROPPED D/ST Ravens D/ST"
99 | ]
100 | assert util.str_limit_check(long_str, 250) == expected_output
101 |
102 | def test_str_limit_check_empty_string(self):
103 | assert util.str_limit_check("", 5) == [""]
104 |
105 | def test_str_limit_check_zero_limit(self):
106 | with pytest.raises(ValueError):
107 | util.str_limit_check("hello", 0)
108 |
109 | def test_str_limit_check_negative_limit(self):
110 | with pytest.raises(ValueError):
111 | util.str_limit_check("hello", -5)
112 |
113 | def test_str_limit_check_split_on_newline(self):
114 | assert util.str_limit_check("hello\nworld", 8) == ["hello", "world"]
115 |
116 | def test_str_limit_check_string_with_only_newlines(self):
117 | assert util.str_limit_check("\n\n\n\n\n", 3) == [""]
118 |
119 | def test_str_limit_check_string_with_multiple_spaces(self):
120 | assert util.str_limit_check(" ", 3) == [""]
121 |
122 | def test_str_limit_check_string_with_multiple_spaces_and_newline(self):
123 | assert util.str_limit_check(" \n ", 3) == [""]
124 |
125 | def test_str_limit_check_string_with_multiple_trailing_spaces(self):
126 | assert util.str_limit_check("hello world ", 11) == ["hello world"]
127 |
128 | def test_str_limit_check_string_with_multiple_preceeding_spaces(self):
129 | assert util.str_limit_check(" hello world", 11) == ["hello world"]
130 |
131 | def test_str_limit_check_string_with_multiple_trailing_spaces_with_newline(self):
132 | assert util.str_limit_check("hello world \n ", 11) == ["hello world"]
133 |
134 | def test_str_limit_check_string_with_multiple_preceeding_spaces_with_newline(self):
135 | assert util.str_limit_check(" \n hello world", 11) == ["hello world"]
136 |
137 | def test_str_limit_check_non_string_input(self):
138 | with pytest.raises(TypeError):
139 | util.str_limit_check(12345, 5)
140 |
141 | def test_str_limit_check_non_integer_limit(self):
142 | with pytest.raises(TypeError):
143 | util.str_limit_check("hello", "five")
144 |
145 | class TestStringToDatetime:
146 | ############ For `str_to_datetime`
147 | def test_str_to_datetime_valid_date(self):
148 | assert util.str_to_datetime("2022-12-14") == datetime(2022, 12, 14)
149 |
150 | def test_str_to_datetime_invalid_date_format(self):
151 | with pytest.raises(ValueError):
152 | util.str_to_datetime("12-14-2022")
153 |
154 | def test_str_to_datetime_invalid_date(self):
155 | with pytest.raises(ValueError):
156 | util.str_to_datetime("2022-13-14")
157 |
158 | def test_str_to_datetime_invalid_month(self):
159 | with pytest.raises(ValueError):
160 | util.str_to_datetime("2022-06-31")
161 |
162 | def test_str_to_datetime_invalid_leap_year(self):
163 | with pytest.raises(ValueError):
164 | util.str_to_datetime("2022-02-29")
165 |
166 | def test_str_to_datetime_incomplete_date(self):
167 | with pytest.raises(ValueError):
168 | util.str_to_datetime("2022-09")
169 |
170 | def test_str_to_datetime_non_string_input(self):
171 | with pytest.raises(TypeError):
172 | util.str_to_datetime(123)
173 |
174 | def test_str_to_datetime_whitespace_in_date_string(self):
175 | assert util.str_to_datetime(" 2022-12-14 ") == datetime(2022, 12, 14)
176 | assert util.str_to_datetime("\n2022-12-14\n") == datetime(2022, 12, 14)
177 |
178 | def test_str_to_datetime_leap_year(self):
179 | assert util.str_to_datetime("2020-02-29") == datetime(2020, 2, 29)
180 |
181 | def test_str_to_datetime_empty_string(self):
182 | with pytest.raises(ValueError):
183 | util.str_to_datetime("")
184 |
185 | def test_str_to_datetime_date_with_time(self):
186 | with pytest.raises(ValueError):
187 | util.str_to_datetime("2023-09-08 12:34:56")
188 |
189 | def test_str_to_datetime_string_representation(self):
190 | with pytest.raises(ValueError):
191 | util.str_to_datetime("September 8, 2023")
192 |
193 |
194 | class TestCurrentlyInSeason:
195 | ############ For `currently_in_season`
196 | def test_currently_in_season_within_season(self):
197 | assert util.currently_in_season("2022-09-08", "2023-01-09", datetime(2022, 12, 1)) == True
198 |
199 | def test_currently_in_season_before_start_date(self):
200 | assert util.currently_in_season("2022-09-08", "2023-01-09", datetime(2022, 6, 30)) == False
201 |
202 | def test_currently_in_season_after_end_date(self):
203 | assert util.currently_in_season("2022-09-08", "2023-01-09", datetime(2023, 1, 10)) == False
204 |
205 | def test_currently_in_season_on_start_date(self):
206 | assert util.currently_in_season("2022-09-08", "2023-01-09", datetime(2022, 9, 8)) == True
207 |
208 | def test_currently_in_season_on_end_date(self):
209 | assert util.currently_in_season("2022-09-08", "2023-01-09", datetime(2023, 1, 9)) == True
210 |
211 | def test_currently_in_season_valid(self):
212 | assert util.currently_in_season("2022-09-01", "2022-12-31", datetime(2022, 10, 15)) == True
213 |
214 | def test_currently_in_season_before_season(self):
215 | assert util.currently_in_season("2022-09-01", "2022-12-31", datetime(2022, 8, 15)) == False
216 |
217 | def test_currently_in_season_after_season(self):
218 | assert util.currently_in_season("2022-09-01", "2022-12-31", datetime(2023, 2, 15)) == False
219 |
220 | def test_currently_in_season_invalid_start_date_format(self):
221 | with pytest.raises(ValueError):
222 | util.currently_in_season("2022/09/01", "2022-12-31", datetime(2022, 10, 15))
223 |
224 | def test_currently_in_season_invalid_end_date_format(self):
225 | with pytest.raises(ValueError):
226 | util.currently_in_season("2022-09-01", "Dec 31, 2022", datetime(2022, 10, 15))
227 |
228 | def test_currently_in_season_non_string_start_date(self):
229 | with pytest.raises(TypeError):
230 | util.currently_in_season(123, "2022-12-31", datetime(2022, 10, 15))
231 |
232 | def test_currently_in_season_non_string_end_date(self):
233 | with pytest.raises(ValueError):
234 | util.currently_in_season("2022-09-01", None, datetime(2022, 10, 15))
235 |
--------------------------------------------------------------------------------