-
Notifications
You must be signed in to change notification settings - Fork 49
/
main.py
418 lines (369 loc) · 17.3 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
__author__ = "Wren J. R. (uberfastman)"
__email__ = "uberfastman@uberfastman.dev"
import getopt
import os
import re
import subprocess
import sys
import time
from pathlib import Path
from typing import Union
import colorama
from colorama import Fore, Style
from integrations.discord import DiscordIntegration
from integrations.drive import GoogleDriveIntegration
from integrations.groupme import GroupMeIntegration
from integrations.slack import SlackIntegration
from report.builder import FantasyFootballReport
from utilities.app import check_github_for_updates
from utilities.logger import get_logger
from utilities.settings import settings
colorama.init()
logger = get_logger()
NFL_SEASON_LENGTH = 18
def main(argv):
logger.debug(f"Running fantasy football metrics weekly report app with arguments:\n{argv}")
dependencies = []
with open(Path(__file__).parent / "requirements.txt", "r") as reqs:
for line in reqs.readlines():
if not line.startswith("#"):
dependencies.append(line.strip())
installed_dependencies = subprocess.check_output(["pip", "freeze"]).decode("utf-8")
missing_dependency_count = 0
for dependency in dependencies:
dependency_is_installed = installed_dependencies.find(dependency) != -1
if not dependency_is_installed:
missing_dependency_count += 1
dependency_package = re.split("\\W+", dependency)[0]
logger.error(
f"MISSING DEPENDENCY: {dependency_package}. Please run `pip install {dependency_package}` and retry "
f"the report generation."
)
if missing_dependency_count > 0:
logger.error(
f"MISSING {missing_dependency_count} " + ("DEPENDENCY" if missing_dependency_count == 1 else "DEPENDENCIES")
)
sys.exit(1)
usage_str = (
"\n"
"Fantasy Football Report application usage:\n"
"\n"
" python main.py [optional_parameters]\n"
"\n"
" Options:\n"
" -h, --help Print command line usage message.\n"
" -d, --use-default Run the report using the default settings without user input prompts.\n"
"\n"
" Generate report:\n"
" -f, --fantasy-platform <platform> Fantasy football platform on which league for report is hosted. Currently supports: \"yahoo\", \"fleaflicker\" \n"
" -l, --league-id <league_id> Fantasy Football league ID.\n"
" -w, --week <chosen_week> Chosen week for which to generate report.\n"
" -k, --start-week <league_start_week> League start week (if league started later than week 1).\n"
" -g, --game-id <chosen_game_id> Chosen fantasy game id for which to generate report. Defaults to \"nfl\", which is interpreted as the current season if using Yahoo.\n"
" -y, --year <chosen_year> Chosen year (season) of the league for which a report is being generated.\n"
"\n"
" Settings:\n"
" -s, --save-data Save all retrieved data locally for faster future report generation.\n"
" -r, --refresh-web-data Refresh all web data from external APIs (such as bad boy and beef data).\n"
" -p, --playoff-prob-sims Number of Monte Carlo playoff probability simulations to run.\n"
" -b, --break-ties Break ties in metric rankings.\n"
" -q, --disqualify-ce Automatically disqualify teams ineligible for coaching efficiency metric.\n"
"\n"
" For Developers:\n"
" -o, --offline Run OFFLINE for development. Must have previously run report with -s option.\n"
" -t, --test Generate TEST report.\n"
)
try:
opts, args = getopt.getopt(argv, "hdf:l:w:k:g:y:srp:bqout")
except getopt.GetoptError:
print(usage_str)
sys.exit(2)
options_dict = {}
for opt, arg in opts:
# help/manual
if opt in ("-h", "--help"):
print(usage_str)
sys.exit(0)
# automatically run the report using the default settings without user input prompts
elif opt in ("-d", "--use-default"):
options_dict["use_default"] = True
# generate report
elif opt in ("-f", "--fantasy-platform"):
options_dict["platform"] = arg
elif opt in ("-l", "--league-id"):
options_dict["league_id"] = arg
elif opt in ("-w", "--week"):
if int(arg) < 1 or int(arg) > NFL_SEASON_LENGTH:
logger.error(f"Please select a valid week number from 1 to {NFL_SEASON_LENGTH}.")
options_dict["week"] = select_week()
else:
options_dict["week"] = int(arg)
elif opt in ("-k", "--start-week"):
options_dict["start_week"] = int(arg)
elif opt in ("-g", "--game-id"):
options_dict["game_id"] = arg
elif opt in ("-y", "--year"):
options_dict["year"] = int(arg)
# report settings
elif opt in ("-s", "--save-data"):
options_dict["save_data"] = True
elif opt in ("-r", "--refresh-web-data"):
options_dict["refresh_web_data"] = True
elif opt in ("-p", "--playoff-prob-sims"):
options_dict["playoff_prob_sims"] = int(arg)
elif opt in ("-b", "--break-ties"):
options_dict["break_ties"] = True
elif opt in ("-q", "--disqualify-ce"):
options_dict["dq_ce"] = True
# for developers
elif opt in ("-o", "--offline"):
options_dict["offline"] = True
elif opt in ("-u", "--skip-uploads"):
options_dict["offline"] = True
elif opt in ("-t", "--test"):
options_dict["test"] = True
return options_dict
def select_league(use_default: bool, week: int, start_week: int, platform: str,
league_id: Union[str, None], game_id: Union[int, str], season: int, refresh_web_data: bool,
playoff_prob_sims: int, break_ties: bool, dq_ce: bool, save_data: bool,
offline: bool, test: bool) -> FantasyFootballReport:
# set "use default" environment variable for access by fantasy football platforms
if use_default:
os.environ["USE_DEFAULT"] = "1"
if not league_id:
if not use_default:
time.sleep(0.25)
selection = input(
f"{Fore.YELLOW}Generate report for default league? "
f"({Fore.GREEN}y{Fore.YELLOW}/{Fore.RED}n{Fore.YELLOW}) -> {Style.RESET_ALL}"
).lower()
else:
logger.info("Use-default is set to \"true\". Automatically running the report for the default league.")
selection = "y"
else:
selection = "selected"
if selection == "y":
if not week:
week_for_report = select_week(use_default)
else:
week_for_report = week
return FantasyFootballReport(
week_for_report=week_for_report,
platform=platform,
game_id=game_id,
season=season,
start_week=start_week,
refresh_web_data=refresh_web_data,
playoff_prob_sims=playoff_prob_sims,
break_ties=break_ties,
dq_ce=dq_ce,
save_data=save_data,
offline=offline,
test=test
)
elif selection == "n":
league_id = input(
f"{Fore.YELLOW}What is the league ID of the league for which you want to generate a report? "
f"-> {Style.RESET_ALL}"
)
if not week:
week_for_report = select_week()
else:
week_for_report = week
try:
return FantasyFootballReport(
week_for_report=week_for_report,
platform=platform,
league_id=league_id,
game_id=game_id,
season=season,
start_week=start_week,
refresh_web_data=refresh_web_data,
playoff_prob_sims=playoff_prob_sims,
break_ties=break_ties,
dq_ce=dq_ce,
save_data=save_data,
offline=offline,
test=test
)
except IndexError:
logger.error("The league ID you have selected is not valid.")
select_league(
use_default, week, start_week, platform, None, game_id, season, refresh_web_data,
playoff_prob_sims, break_ties, dq_ce, save_data, offline, test
)
elif selection == "selected":
if not week:
week_for_report = select_week(use_default)
else:
week_for_report = week
return FantasyFootballReport(
week_for_report=week_for_report,
platform=platform,
league_id=league_id,
game_id=game_id,
season=season,
start_week=start_week,
refresh_web_data=refresh_web_data,
playoff_prob_sims=playoff_prob_sims,
break_ties=break_ties,
dq_ce=dq_ce,
save_data=save_data,
offline=offline,
test=test
)
else:
logger.warning("You must select either \"y\" or \"n\".")
time.sleep(0.25)
select_league(
use_default, week, start_week, platform, None, game_id, season, refresh_web_data,
playoff_prob_sims, break_ties, dq_ce, save_data, offline, test
)
def select_week(use_default: bool = False) -> Union[int, None]:
if not use_default:
time.sleep(0.25)
selection = input(
f"{Fore.YELLOW}Generate report for default week? ({Fore.GREEN}y{Fore.YELLOW}/{Fore.RED}n{Fore.YELLOW}) "
f"-> {Style.RESET_ALL}"
).lower()
else:
logger.info(
"Use-default is set to \"true\". Automatically running the report for the default (most recent) week."
)
selection = "y"
if selection == "y":
return None
elif selection == "n":
chosen_week = int(input(
f"{Fore.YELLOW}For which week would you like to generate a report? "
f"({Fore.GREEN}1{Fore.YELLOW} - {Fore.GREEN}{NFL_SEASON_LENGTH}{Fore.YELLOW}) -> {Style.RESET_ALL}"
).lower())
if 0 < chosen_week <= NFL_SEASON_LENGTH:
return chosen_week
else:
logger.warning(f"Please select a valid week number between 1 and {NFL_SEASON_LENGTH}.")
time.sleep(0.25)
select_week(use_default)
else:
logger.warning("You must select either \"y\" or \"n\".")
time.sleep(0.25)
select_week(use_default)
# RUN FANTASY FOOTBALL REPORT PROGRAM
if __name__ == "__main__":
options = main(sys.argv[1:])
logger.debug(f"Fantasy football metrics weekly report app settings options:\n{options}")
if settings.check_for_updates:
# check to see if the current app is behind any commits, and provide option to update and re-run if behind
up_to_date = check_github_for_updates(options.get("use_default", False))
report = select_league(
options.get("use_default", False),
options.get("week", None),
options.get("start_week", None),
options.get("platform", None),
options.get("league_id", None),
options.get("game_id", None),
options.get("year", None),
options.get("refresh_web_data", False),
options.get("playoff_prob_sims", None),
options.get("break_ties", False),
options.get("dq_ce", False),
options.get("save_data", False),
options.get("offline", False),
options.get("test", False))
report_pdf: Path = report.create_pdf_report()
upload_message = ""
if settings.integration_settings.google_drive_upload_bool:
if not options.get("skip_uploads", False) and not options.get("test", False):
google_drive_integration = GoogleDriveIntegration(report.league.week_for_report)
# upload PDF to Google Drive
upload_message = google_drive_integration.upload_file(report_pdf)
logger.info(upload_message)
else:
logger.info(f"Report NOT uploaded to Google Drive with options: {options}")
if settings.integration_settings.slack_post_bool:
if not options.get("skip_uploads", False) and not options.get("test", False):
slack_integration = SlackIntegration(report.league.week_for_report)
# post PDF or link to PDF to Slack
slack_response = None
post_or_file = settings.integration_settings.slack_post_or_file
if post_or_file == "post":
if settings.integration_settings.google_drive_upload_bool:
# post shareable link to uploaded Google Drive PDF on Slack
slack_response = slack_integration.post_message(upload_message)
else:
logger.warning("Unable to post Google Drive link to Slack when GOOGLE_DRIVE_UPLOAD_BOOL=False.")
elif post_or_file == "file":
# upload PDF report directly to Slack
slack_response = slack_integration.upload_file(report_pdf)
else:
logger.warning(
f"The \".env\" file contains unsupported Slack setting: "
f"SLACK_POST_OR_FILE={post_or_file}. Please choose \"post\" or \"file\" and try again."
)
sys.exit(1)
if slack_response and slack_response.get("ok"):
logger.info(f"Report {str(report_pdf)} successfully posted to Slack!")
else:
logger.error(
f"Report {str(report_pdf)} was NOT posted to Slack with error: {slack_response}"
)
else:
logger.info(f"Report NOT posted to Slack with options: {options}")
if settings.integration_settings.groupme_post_bool:
if not options.get("skip_uploads", False) and not options.get("test", False):
groupme_integration = GroupMeIntegration(report.league.week_for_report)
# post PDF or link to PDF to GroupMe
groupme_response = None
post_or_file = settings.integration_settings.groupme_post_or_file
if post_or_file == "post":
if settings.integration_settings.google_drive_upload_bool:
# post shareable link to uploaded Google Drive PDF on GroupMe
groupme_response = groupme_integration.post_message(upload_message)
else:
logger.warning("Unable to post Google Drive link to GroupMe when GOOGLE_DRIVE_UPLOAD_BOOL=False.")
elif post_or_file == "file":
# upload PDF report directly to GroupMe
groupme_response = groupme_integration.upload_file(report_pdf)
else:
logger.warning(
f"The \".env\" file contains unsupported GroupMe setting: "
f"GROUPME_POST_OR_FILE={post_or_file}. Please choose \"post\" or \"file\" and try again."
)
sys.exit(1)
if groupme_response == 202 or groupme_response["meta"]["code"] == 201:
logger.info(f"Report {str(report_pdf)} successfully posted to GroupMe!")
else:
logger.error(
f"Report {str(report_pdf)} was NOT posted to GroupMe with error: {groupme_response}"
)
else:
logger.info(f"Report NOT posted to GroupMe with options: {options}")
if settings.integration_settings.discord_post_bool:
if not options.get("skip_uploads", False) and not options.get("test", False):
discord_integration = DiscordIntegration(report.league.week_for_report)
# post PDF or link to PDF to Discord
discord_response = None
post_or_file = settings.integration_settings.discord_post_or_file
if post_or_file == "post":
if settings.integration_settings.google_drive_upload_bool:
# post shareable link to uploaded Google Drive PDF on Discord
discord_response = discord_integration.post_message(upload_message)
else:
logger.warning("Unable to post Google Drive link to Discord when GOOGLE_DRIVE_UPLOAD_BOOL=False.")
elif post_or_file == "file":
# upload PDF report directly to Discord
discord_response = discord_integration.upload_file(report_pdf)
else:
logger.warning(
f"The \".env\" file contains unsupported Discord setting: "
f"DISCORD_POST_OR_FILE={post_or_file}. Please choose \"post\" or \"file\" and try again."
)
sys.exit(1)
if discord_response and discord_response.get("type") == 0:
logger.info(f"Report {str(report_pdf)} successfully posted to Discord!")
else:
logger.error(
f"Report {str(report_pdf)} was NOT posted to Discord with error: {discord_response}"
)
else:
logger.info(f"Report NOT posted to Discord with options: {options}")