From 2f9d4c74ae9c79d83f525eb0e0b403a363f6fa34 Mon Sep 17 00:00:00 2001 From: dtcarls Date: Mon, 24 Oct 2022 14:50:19 -0400 Subject: [PATCH 1/7] optimal lineup --- gamedaybot/espn/espn_bot.py | 1 + gamedaybot/espn/functionality.py | 73 ++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/gamedaybot/espn/espn_bot.py b/gamedaybot/espn/espn_bot.py index 9dcf7d2f..4962fc27 100644 --- a/gamedaybot/espn/espn_bot.py +++ b/gamedaybot/espn/espn_bot.py @@ -46,6 +46,7 @@ def espn_bot(function): if waiver_report and swid != '{1}' and espn_s2 != '1': print(espn.get_waiver_report(league, faab)) function = "get_final" + print(espn.best_possible_scores(league)) # bot.send_message("Testing") # slack_bot.send_message("Testing") # discord_bot.send_message("Testing") diff --git a/gamedaybot/espn/functionality.py b/gamedaybot/espn/functionality.py index 96f2a4c8..cedad80b 100644 --- a/gamedaybot/espn/functionality.py +++ b/gamedaybot/espn/functionality.py @@ -277,6 +277,79 @@ def get_luckys(league, week=None): unlucky_str = ['😡 Unlucky 😡']+['%s was %s against the league, but still took an L' % (unlucky_team_name, unlucky_record)] return(lucky_str + unlucky_str) +def get_starter_counts(league): + week = league.current_week - 1 + box_scores = league.box_scores(week=week) + starters = {} + for i in box_scores: + for player in i.home_lineup: + if (player.slot_position != 'BE' and player.slot_position != 'IR'): + try: + starters[player.slot_position] = starters[player.slot_position]+1 + except KeyError: + starters[player.slot_position] = 1 + return starters + +def best_lineup_score(lineup, starter_counts): + best_lineup = {} + position_players = {} + + for position in starter_counts: + position_players[position] = {} + score = 0 + for player in lineup: + if player.position == position: + position_players[position][player.name] = player.points + if player.slot_position not in ['BE', 'IR']: + score += player.points + position_players[position] = {k: v for k, v in sorted(position_players[position].items(), key=lambda item: item[1], reverse=True)} + best_lineup[position] = dict(list(position_players[position].items())[:starter_counts[position]]) + + # flexes. need to figure out best in other positions first + for position in starter_counts: + if 'D/ST' not in position and '/' in position: + flex = position.split('/') + for player in lineup: + if player.position in flex and player.name not in best_lineup[player.position]: + position_players[position][player.name] = player.points + position_players[position] = {k: v for k, v in sorted(position_players[position].items(), key=lambda item: item[1], reverse=True)} + best_lineup[position] = dict(list(position_players[position].items())[:starter_counts[position]]) + + best_score = 0 + for position in best_lineup: + # print(sum(best_lineup[position].values())) + best_score += sum(best_lineup[position].values()) + + score_pct = (score / best_score) * 100 + return (best_score, score, best_score - score, score_pct) + +def best_possible_scores(league, week=None): + if not week: + week = league.current_week - 1 + box_scores = league.box_scores(week=week) + results = [] + best_scores = {} + starter_counts = get_starter_counts(league) + + for i in box_scores: + best_scores[i.home_team] = best_lineup_score(i.home_lineup, starter_counts) + best_scores[i.away_team] = best_lineup_score(i.away_lineup, starter_counts) + + best_scores = {key: value for key, value in sorted(best_scores.items(), key=lambda item: item[1][3], reverse=True)} + + i = 1 + for score in best_scores: + s = ['%d: %s: %.2f (%.2f - %.2f%%)' % (i, score.team_name, best_scores[score][0], best_scores[score][1], best_scores[score][3])] + results += s + i += 1 + + if not results: + return ('') + + text = ['Best Possible Scores: (Actual Score - % of possible)'] + results + + return '\n'.join(text) + def get_achievers(league, week=None): """ Get the teams with biggest difference from projection From 025d4351452bc419e66f5a3cd51cf0cea86a7c6f Mon Sep 17 00:00:00 2001 From: dtcarls Date: Mon, 31 Oct 2022 12:21:45 -0400 Subject: [PATCH 2/7] manager trophy. message formatting. remove unused scan_inactives function. --- gamedaybot/espn/functionality.py | 162 +++++++++++++++---------------- 1 file changed, 76 insertions(+), 86 deletions(-) diff --git a/gamedaybot/espn/functionality.py b/gamedaybot/espn/functionality.py index cedad80b..916af089 100644 --- a/gamedaybot/espn/functionality.py +++ b/gamedaybot/espn/functionality.py @@ -21,15 +21,17 @@ def get_projected_scoreboard(league, week=None): return '\n'.join(text) -def get_standings(league, top_half_scoring, week=None): +def get_standings(league, top_half_scoring=False, week=None): standings_txt = '' teams = league.teams standings = [] if not top_half_scoring: standings = league.standings() - standings_txt = [f"{pos + 1}: {team.team_name} ({team.wins}-{team.losses})" for + standings_txt = [f"{pos + 1:2}: ({team.wins}-{team.losses}) {team.team_name} " for pos, team in enumerate(standings)] else: + # top half scoring can be enabled by default in ESPN now. + # this should generally not be used top_half_totals = {t.team_name: 0 for t in teams} if not week: week = league.current_week @@ -41,7 +43,7 @@ def get_standings(league, top_half_scoring, week=None): standings.append((wins, t.losses, t.team_name)) standings = sorted(standings, key=lambda tup: tup[0], reverse=True) - standings_txt = [f"{pos + 1}: {team_name} ({wins}-{losses}) (+{top_half_totals[team_name]})" for + standings_txt = [f"{pos + 1:2}: {team_name} ({wins}-{losses}) (+{top_half_totals[team_name]})" for pos, (wins, losses, team_name) in enumerate(standings)] text = ["Current Standings:"] + standings_txt @@ -121,34 +123,12 @@ def scan_roster(lineup, team): return report -def scan_inactives(lineup, team): - count = 0 - players = [] - for i in lineup: - if (i.slot_position != 'BE' and i.slot_position != 'IR') \ - and (i.injuryStatus == 'OUT' or i.injuryStatus == 'DOUBTFUL' or i.projected_points <= 0) \ - and i.game_played == 0: - count += 1 - players += ['%s %s - %s, %d pts' % - (i.position, i.name, i.injuryStatus.title().replace('_', ' '), i.projected_points)] - - inactive_list = "" - inactives = "" - for p in players: - inactive_list += p + "\n" - if count > 0: - s = '%s likely inactive starting player(s): \n%s \n' % (team.team_name, inactive_list[:-1]) - inactives = [s.lstrip()] - - return inactives - - -def get_matchups(league, random_phrase, week=None): +def get_matchups(league, random_phrase=False, week=None): # Gets current week's Matchups matchups = league.box_scores(week=week) - score = ['%s(%s-%s) vs %s(%s-%s)' % (i.home_team.team_name, i.home_team.wins, i.home_team.losses, - i.away_team.team_name, i.away_team.wins, i.away_team.losses) for i in matchups + score = ['%4s (%s-%s) vs (%s-%s) %s' % (i.home_team.team_abbrev, i.home_team.wins, i.home_team.losses, + i.away_team.wins, i.away_team.losses, i.away_team.team_abbrev) for i in matchups if i.away_team] text = ['Matchups'] + score @@ -174,7 +154,7 @@ def get_close_scores(league, week=None): return '\n'.join(text) -def get_waiver_report(league, faab): +def get_waiver_report(league, faab=False): activities = league.recent_activity(50) report = [] today = date.today().strftime('%Y-%m-%d') @@ -228,54 +208,11 @@ def get_power_rankings(league, week=None): # It's weighted 80/15/5 respectively power_rankings = league.power_rankings(week=week) - score = ['%s (%.1f) - %s' % (i[0], i[1].playoff_pct, i[1].team_name) for i in power_rankings + score = ['%6s (%.1f) - %s' % (i[0], i[1].playoff_pct, i[1].team_name) for i in power_rankings if i] text = ['Power Rankings (Playoff %)'] + score return '\n'.join(text) -def get_luckys(league, week=None): - box_scores = league.box_scores(week=week) - weekly_scores = {} - for i in box_scores: - if i.home_score > i.away_score: - weekly_scores[i.home_team] = [i.home_score,'W'] - weekly_scores[i.away_team] = [i.away_score,'L'] - else: - weekly_scores[i.home_team] = [i.home_score,'L'] - weekly_scores[i.away_team] = [i.away_score,'W'] - weekly_scores = dict(sorted(weekly_scores.items(), key=lambda item: item[1], reverse=True)) - - # losses = 0 - # for t in weekly_scores: - # print(t.team_name + ': (' + str(len(weekly_scores)-1-losses) + '-' + str(losses) +')') - # losses+=1 - - losses = 0 - unlucky_team_name = '' - unlucky_record = '' - lucky_team_name = '' - lucky_record = '' - num_teams = len(weekly_scores)-1 - - for t in weekly_scores: - if weekly_scores[t][1] == 'L': - unlucky_team_name = t.team_name - unlucky_record = str(num_teams-losses) + '-' + str(losses) - break - losses += 1 - - wins = 0 - weekly_scores = dict(sorted(weekly_scores.items(), key=lambda item: item[1])) - for t in weekly_scores: - if weekly_scores[t][1] == 'W': - lucky_team_name = t.team_name - lucky_record = str(wins) + '-' + str(num_teams - wins) - break - wins += 1 - - lucky_str = ['🍀 Lucky 🍀']+['%s was %s against the league, but still got the win' % (lucky_team_name, lucky_record)] - unlucky_str = ['😡 Unlucky 😡']+['%s was %s against the league, but still took an L' % (unlucky_team_name, unlucky_record)] - return(lucky_str + unlucky_str) def get_starter_counts(league): week = league.current_week - 1 @@ -290,7 +227,8 @@ def get_starter_counts(league): starters[player.slot_position] = 1 return starters -def best_lineup_score(lineup, starter_counts): + +def optimal_lineup_score(lineup, starter_counts): best_lineup = {} position_players = {} @@ -323,7 +261,8 @@ def best_lineup_score(lineup, starter_counts): score_pct = (score / best_score) * 100 return (best_score, score, best_score - score, score_pct) -def best_possible_scores(league, week=None): + +def optimal_team_scores(league, week=None, full_report=False): if not week: week = league.current_week - 1 box_scores = league.box_scores(week=week) @@ -332,25 +271,30 @@ def best_possible_scores(league, week=None): starter_counts = get_starter_counts(league) for i in box_scores: - best_scores[i.home_team] = best_lineup_score(i.home_lineup, starter_counts) - best_scores[i.away_team] = best_lineup_score(i.away_lineup, starter_counts) + best_scores[i.home_team] = optimal_lineup_score(i.home_lineup, starter_counts) + best_scores[i.away_team] = optimal_lineup_score(i.away_lineup, starter_counts) best_scores = {key: value for key, value in sorted(best_scores.items(), key=lambda item: item[1][3], reverse=True)} + if full_report: i = 1 for score in best_scores: - s = ['%d: %s: %.2f (%.2f - %.2f%%)' % (i, score.team_name, best_scores[score][0], best_scores[score][1], best_scores[score][3])] + s = ['%2d: %4s: %.2f (%.2f - %.2f%%)' % (i, score.team_abbrev, best_scores[score][0], best_scores[score][1], best_scores[score][3])] results += s i += 1 - if not results: - return ('') + text = ['Optimal Scores: (Actual - % of optimal)'] + results + return '\n'.join(text) + else: + best = next(iter(best_scores.items())) + best_mgr_str = ['🤖 Best Manager 🤖'] + ['%s scored %.2f%% of their optimal score!' % (best[0].team_name, best[1][3])] - text = ['Best Possible Scores: (Actual Score - % of possible)'] + results + worst = best_scores.popitem() + worst_mgr_str = ['🤡 Worst Manager 🤡'] + ['%s left %.2f points on their bench. Only scoring %.2f%% of their optimal score.' % (worst[0].team_name, worst[1][0]-worst[1][1], worst[1][3])] + return(best_mgr_str + worst_mgr_str) - return '\n'.join(text) -def get_achievers(league, week=None): +def get_achievers_trophy(league, week=None): """ Get the teams with biggest difference from projection """ @@ -381,15 +325,61 @@ def get_achievers(league, week=None): if best_performance > 0: high_achiever_str +=['%s was %.2f points over their projection' % (over_achiever, best_performance)] else: - high_achiever_str += 'No team out performed their projection' + high_achiever_str += ['No team out performed their projection'] if worst_performance < 0: low_achiever_str += ['%s was %.2f points under their projection' % (under_achiever, abs(worst_performance))] else: - low_achiever_str += 'No team was worse than their projection' + low_achiever_str += ['No team was worse than their projection'] return(high_achiever_str + low_achiever_str) + +def get_lucky_trophy(league, week=None): + box_scores = league.box_scores(week=week) + weekly_scores = {} + for i in box_scores: + if i.home_score > i.away_score: + weekly_scores[i.home_team] = [i.home_score,'W'] + weekly_scores[i.away_team] = [i.away_score,'L'] + else: + weekly_scores[i.home_team] = [i.home_score,'L'] + weekly_scores[i.away_team] = [i.away_score,'W'] + weekly_scores = dict(sorted(weekly_scores.items(), key=lambda item: item[1], reverse=True)) + + # losses = 0 + # for t in weekly_scores: + # print(t.team_name + ': (' + str(len(weekly_scores)-1-losses) + '-' + str(losses) +')') + # losses+=1 + + losses = 0 + unlucky_team_name = '' + unlucky_record = '' + lucky_team_name = '' + lucky_record = '' + num_teams = len(weekly_scores)-1 + + for t in weekly_scores: + if weekly_scores[t][1] == 'L': + unlucky_team_name = t.team_name + unlucky_record = str(num_teams-losses) + '-' + str(losses) + break + losses += 1 + + wins = 0 + weekly_scores = dict(sorted(weekly_scores.items(), key=lambda item: item[1])) + for t in weekly_scores: + if weekly_scores[t][1] == 'W': + lucky_team_name = t.team_name + lucky_record = str(wins) + '-' + str(num_teams - wins) + break + wins += 1 + + lucky_str = ['🍀 Lucky 🍀']+['%s was %s against the league, but still got the win' % (lucky_team_name, lucky_record)] + unlucky_str = ['😡 Unlucky 😡']+['%s was %s against the league, but still took an L' % (unlucky_team_name, unlucky_record)] + return(lucky_str + unlucky_str) + + def get_trophies(league, week=None): # Gets trophies for highest score, lowest score, closest score, and biggest win matchups = league.box_scores(week=week) @@ -440,5 +430,5 @@ def get_trophies(league, week=None): close_score_str = ['😅 Close win 😅']+['%s barely beat %s by %.2f points' % (close_winner, close_loser, closest_score)] blowout_str = ['😱 Blow out 😱']+['%s blew out %s by %.2f points' % (ownerer_team_name, blown_out_team_name, biggest_blowout)] - text = ['Trophies of the week:'] + high_score_str + low_score_str + blowout_str + close_score_str + get_luckys(league, week) + get_achievers(league, week) + text = ['Trophies of the week:'] + high_score_str + low_score_str + blowout_str + close_score_str + get_lucky_trophy(league, week) + get_achievers_trophy(league, week) + optimal_team_scores(league, week) return '\n'.join(text) \ No newline at end of file From a4bc4bafbf1de8fc438eb1092f916039e423fe25 Mon Sep 17 00:00:00 2001 From: dtcarls Date: Mon, 31 Oct 2022 13:48:22 -0400 Subject: [PATCH 3/7] manager trophy: allow for ties at the top --- gamedaybot/espn/functionality.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/gamedaybot/espn/functionality.py b/gamedaybot/espn/functionality.py index 916af089..d6a41b23 100644 --- a/gamedaybot/espn/functionality.py +++ b/gamedaybot/espn/functionality.py @@ -286,8 +286,22 @@ def optimal_team_scores(league, week=None, full_report=False): text = ['Optimal Scores: (Actual - % of optimal)'] + results return '\n'.join(text) else: + num_teams = 0 + team_names = '' + for score in best_scores: + if best_scores[score][3] > 99.8: + num_teams += 1 + team_names += score.team_name + ', ' + else: + break + # s = ['%2d: %4s: %.2f (%.2f - %.2f%%)' % (i, score.team_abbrev, best_scores[score][0], best_scores[score][1], best_scores[score][3])] + + if num_teams <= 1: best = next(iter(best_scores.items())) best_mgr_str = ['🤖 Best Manager 🤖'] + ['%s scored %.2f%% of their optimal score!' % (best[0].team_name, best[1][3])] + else: + team_names = team_names[:-2] + best_mgr_str = ['🤖 Best Managers 🤖'] + [f'{team_names} scored their optimal score!'] worst = best_scores.popitem() worst_mgr_str = ['🤡 Worst Manager 🤡'] + ['%s left %.2f points on their bench. Only scoring %.2f%% of their optimal score.' % (worst[0].team_name, worst[1][0]-worst[1][1], worst[1][3])] From 39722f7aacab316c56dc99c7ffe5eccee8aed4fa Mon Sep 17 00:00:00 2001 From: dtcarls Date: Tue, 1 Nov 2022 08:34:16 -0400 Subject: [PATCH 4/7] fix edge case with empty slot for optimal calc. format optimal report --- gamedaybot/espn/functionality.py | 34 +++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/gamedaybot/espn/functionality.py b/gamedaybot/espn/functionality.py index d6a41b23..f8616a2e 100644 --- a/gamedaybot/espn/functionality.py +++ b/gamedaybot/espn/functionality.py @@ -217,15 +217,31 @@ def get_power_rankings(league, week=None): def get_starter_counts(league): week = league.current_week - 1 box_scores = league.box_scores(week=week) - starters = {} + h_starters = {} + h_starter_count = 0 + a_starters = {} + a_starter_count = 0 for i in box_scores: for player in i.home_lineup: if (player.slot_position != 'BE' and player.slot_position != 'IR'): + h_starter_count += 1 try: - starters[player.slot_position] = starters[player.slot_position]+1 + h_starters[player.slot_position] = h_starters[player.slot_position]+1 except KeyError: - starters[player.slot_position] = 1 - return starters + h_starters[player.slot_position] = 1 + # in the rare case when someone has an empty slot we need to check the other team as well + for player in i.away_lineup: + if (player.slot_position != 'BE' and player.slot_position != 'IR'): + a_starter_count += 1 + try: + a_starters[player.slot_position] = a_starters[player.slot_position]+1 + except KeyError: + a_starters[player.slot_position] = 1 + + if a_starter_count > h_starter_count: + return a_starters + else: + return h_starters def optimal_lineup_score(lineup, starter_counts): @@ -277,9 +293,9 @@ def optimal_team_scores(league, week=None, full_report=False): best_scores = {key: value for key, value in sorted(best_scores.items(), key=lambda item: item[1][3], reverse=True)} if full_report: - i = 1 - for score in best_scores: - s = ['%2d: %4s: %.2f (%.2f - %.2f%%)' % (i, score.team_abbrev, best_scores[score][0], best_scores[score][1], best_scores[score][3])] + i = 1 + for score in best_scores: + s = ['%2d: %4s: %6.2f (%6.2f - %.2f%%)' % (i, score.team_abbrev, best_scores[score][0], best_scores[score][1], best_scores[score][3])] results += s i += 1 @@ -297,8 +313,8 @@ def optimal_team_scores(league, week=None, full_report=False): # s = ['%2d: %4s: %.2f (%.2f - %.2f%%)' % (i, score.team_abbrev, best_scores[score][0], best_scores[score][1], best_scores[score][3])] if num_teams <= 1: - best = next(iter(best_scores.items())) - best_mgr_str = ['🤖 Best Manager 🤖'] + ['%s scored %.2f%% of their optimal score!' % (best[0].team_name, best[1][3])] + best = next(iter(best_scores.items())) + best_mgr_str = ['🤖 Best Manager 🤖'] + ['%s scored %.2f%% of their optimal score!' % (best[0].team_name, best[1][3])] else: team_names = team_names[:-2] best_mgr_str = ['🤖 Best Managers 🤖'] + [f'{team_names} scored their optimal score!'] From 23757b02d92c3078e538bc7da9bd88bc3718e84b Mon Sep 17 00:00:00 2001 From: dtcarls Date: Mon, 28 Nov 2022 08:49:27 -0500 Subject: [PATCH 5/7] close scores use projected. matchups message changed. --- gamedaybot/espn/espn_bot.py | 5 +---- gamedaybot/espn/functionality.py | 35 ++++++++++++++++++-------------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/gamedaybot/espn/espn_bot.py b/gamedaybot/espn/espn_bot.py index 5e7cb870..b68bc2fd 100644 --- a/gamedaybot/espn/espn_bot.py +++ b/gamedaybot/espn/espn_bot.py @@ -67,20 +67,17 @@ def espn_bot(function): text = espn.get_close_scores(league) elif function == "get_power_rankings": text = espn.get_power_rankings(league) - # elif function=="get_waiver_report": - # text = get_waiver_report(league) elif function == "get_trophies": text = espn.get_trophies(league) elif function == "get_standings": text = espn.get_standings(league, top_half_scoring) - if waiver_report and swid != '{1}' and espn_s2 != '1': - text += '\n\n' + espn.get_waiver_report(league, faab) elif function == "get_final": # on Tuesday we need to get the scores of last week week = league.current_week - 1 text = "Final " + espn.get_scoreboard_short(league, week=week) text = text + "\n\n" + espn.get_trophies(league, week=week) elif function == "get_waiver_report" and swid != '{1}' and espn_s2 != '1': + faab = league.settings.faab text = espn.get_waiver_report(league, faab) elif function == "init": try: diff --git a/gamedaybot/espn/functionality.py b/gamedaybot/espn/functionality.py index f8616a2e..e3828e51 100644 --- a/gamedaybot/espn/functionality.py +++ b/gamedaybot/espn/functionality.py @@ -4,7 +4,7 @@ def get_scoreboard_short(league, week=None): # Gets current week's scoreboard box_scores = league.box_scores(week=week) - score = ['%4s %6.2f - %6.2f %4s' % (i.home_team.team_abbrev, i.home_score, + score = ['%4s %6.2f - %6.2f %s' % (i.home_team.team_abbrev, i.home_score, i.away_score, i.away_team.team_abbrev) for i in box_scores if i.away_team] text = ['Score Update'] + score @@ -14,7 +14,7 @@ def get_scoreboard_short(league, week=None): def get_projected_scoreboard(league, week=None): # Gets current week's scoreboard projections box_scores = league.box_scores(week=week) - score = ['%4s %6.2f - %6.2f %4s' % (i.home_team.team_abbrev, get_projected_total(i.home_lineup), + score = ['%4s %6.2f - %6.2f %s' % (i.home_team.team_abbrev, get_projected_total(i.home_lineup), get_projected_total(i.away_lineup), i.away_team.team_abbrev) for i in box_scores if i.away_team] text = ['Approximate Projected Scores'] + score @@ -45,7 +45,7 @@ def get_standings(league, top_half_scoring=False, week=None): standings = sorted(standings, key=lambda tup: tup[0], reverse=True) standings_txt = [f"{pos + 1:2}: {team_name} ({wins}-{losses}) (+{top_half_totals[team_name]})" for pos, (wins, losses, team_name) in enumerate(standings)] - text = ["Current Standings:"] + standings_txt + text = ["Current Standings"] + standings_txt return "\n".join(text) @@ -92,7 +92,7 @@ def get_monitor(league): monitor += scan_roster(i.away_lineup, i.away_team) if monitor: - text = ['Starting Players to Monitor: '] + monitor + text = ['Starting Players to Monitor'] + monitor else: text = ['No Players to Monitor this week. Good Luck!'] return '\n'.join(text) @@ -127,30 +127,34 @@ def get_matchups(league, random_phrase=False, week=None): # Gets current week's Matchups matchups = league.box_scores(week=week) - score = ['%4s (%s-%s) vs (%s-%s) %s' % (i.home_team.team_abbrev, i.home_team.wins, i.home_team.losses, + full_names = ['%s vs %s' % (i.home_team.team_name, i.away_team.team_name) for i in matchups if i.away_team] + + abbrevs = ['%4s (%s-%s) vs (%s-%s) %s' % (i.home_team.team_abbrev, i.home_team.wins, i.home_team.losses, i.away_team.wins, i.away_team.losses, i.away_team.team_abbrev) for i in matchups if i.away_team] - text = ['Matchups'] + score - if random_phrase: - text = text + utils.get_random_phrase() + text = ['Matchups'] + full_names + [''] + abbrevs return '\n'.join(text) def get_close_scores(league, week=None): - # Gets current closest scores (15.999 points or closer) - matchups = league.box_scores(week=week) + # Gets current projected closest scores (15.999 points or closer) + box_scores = league.box_scores(week=week) score = [] - for i in matchups: + for i in box_scores: if i.away_team: - diffScore = i.away_score - i.home_score + # diffScore = i.away_score - i.home_score + away_projected = get_projected_total(i.away_lineup) + home_projected = get_projected_total(i.home_lineup) + diffScore = away_projected - home_projected + if (-16 < diffScore <= 0 and not all_played(i.away_lineup)) or (0 <= diffScore < 16 and not all_played(i.home_lineup)): - score += ['%4s %6.2f - %6.2f %4s' % (i.home_team.team_abbrev, i.home_score, - i.away_score, i.away_team.team_abbrev)] + score += ['%4s %6.2f - %6.2f %s' % (i.home_team.team_abbrev, i.home_projected, + i.away_projected, i.away_team.team_abbrev)] if not score: return('') - text = ['Close Scores'] + score + text = ['Projected Close Scores'] + score return '\n'.join(text) @@ -248,6 +252,7 @@ def optimal_lineup_score(lineup, starter_counts): best_lineup = {} position_players = {} + score = 0 for position in starter_counts: position_players[position] = {} score = 0 From 5e0d7bf8ab1b0b3a1babaca7f40c4bb256c9de8c Mon Sep 17 00:00:00 2001 From: dtcarls Date: Mon, 28 Nov 2022 09:03:32 -0500 Subject: [PATCH 6/7] test functions --- gamedaybot/espn/espn_bot.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/gamedaybot/espn/espn_bot.py b/gamedaybot/espn/espn_bot.py index b68bc2fd..d8eab685 100644 --- a/gamedaybot/espn/espn_bot.py +++ b/gamedaybot/espn/espn_bot.py @@ -36,18 +36,18 @@ def espn_bot(function): faab = league.settings.faab if test: - print(espn.get_matchups(league, random_phrase)) print(espn.get_scoreboard_short(league)) print(espn.get_projected_scoreboard(league)) + print(espn.get_standings(league)) + print(espn.get_standings(league, True)) print(espn.get_close_scores(league)) - print(espn.get_power_rankings(league)) - print(espn.get_scoreboard_short(league)) - print(espn.get_standings(league, top_half_scoring)) print(espn.get_monitor(league)) + print(espn.get_matchups(league)) + print(espn.get_power_rankings(league)) + print(espn.get_trophies(league)) + print(espn.optimal_team_scores(league, full_report=True)) if waiver_report and swid != '{1}' and espn_s2 != '1': print(espn.get_waiver_report(league, faab)) - function = "get_final" - print(espn.best_possible_scores(league)) # bot.send_message("Testing") # slack_bot.send_message("Testing") # discord_bot.send_message("Testing") @@ -95,10 +95,6 @@ def espn_bot(function): slack_bot.send_message(message) discord_bot.send_message(message) - if test: - # print "get_final" function - print(text) - if __name__ == '__main__': from gamedaybot.espn.scheduler import scheduler From e59938c9976b01f4140919ec4e8028d674274f9b Mon Sep 17 00:00:00 2001 From: dtcarls Date: Mon, 28 Nov 2022 09:37:19 -0500 Subject: [PATCH 7/7] update readme --- README.md | 138 ++++++++++++++++++++++++------------------------------ 1 file changed, 62 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index bed24436..e1ad292a 100644 --- a/README.md +++ b/README.md @@ -150,11 +150,12 @@ Save the "Webhook URL" on this page ### Heroku setup +**"November 28, 2022, Heroku stopped offering free product plans"** -Heroku is what we will be using to host the chat bot. - -**"Starting November 28, 2022, Heroku plans to stop offering free product plans and plans to start shutting down free dynos and data services."** I offer a hosting service far lower than the new costs of Heroku at https://www.GameDayBot.com/ +
+ Click to expand! +Heroku is what you can use to host the chat bot. Go to https://id.heroku.com/login and sign up or login @@ -175,23 +176,7 @@ Now you will need to setup your environment variables so that it works for your Now we will need to edit these variables (click the pencil to the right of the variable to modify) 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 -- BOT_ID: This is your Bot ID from the GroupMe developers page (REQUIRED IF USING GROUPME) -- SLACK_WEBHOOK_URL: This is your Webhook URL from the Slack App page (REQUIRED IF USING SLACK) -- DISCORD_WEBHOOK_URL: This is your Webhook URL from the Discord Settings page (REQUIRED IF USING DISCORD) -- LEAGUE_ID: This is your ESPN league id (REQUIRED) -- START_DATE: This is when the bot will start paying attention and sending messages to your chat. (2020-09-10 by default) -- END_DATE: This is when the bot will stop paying attention and stop sending messages to your chat. (2020-12-30 by default) -- LEAGUE_YEAR: ESPN League year to look at (2020 by default) -- TIMEZONE: The timezone that the messages will look to send in. (America/New_York by default) -- INIT_MSG: The message that the bot will say when it is started (can be blank or deleted for no message) -- TOP_HALF_SCORING: 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. -- RANDOM_PHRASE: If set to True, when matchups are posted on Tuesday it will also include a random phrase -- MONITOR_REPORT: 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 -- WAIVER_REPORT: If set to True, will provide a waiver report of add/drops. :warning: ESPN_S2 and SWID are required for this to work :warning: -- DAILY_WAIVER: 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: -- ESPN_S2: Used for private leagues. See [Private Leagues Section](#private-leagues) for documentation -- SWID: Used for private leagues. (Can be defined with or without {}) See [Private Leagues Section](#private-leagues) for documentation - +See [Environment Variables Section](#environment-variables) for documentation After you have setup your variables you will need to turn it on. Navigate to the "Resources" tab of your Heroku app Dashboard. 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." @@ -200,45 +185,6 @@ You should see something like below. Click the pencil on the right and toggle th 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. 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. - -#### Private Leagues - -For private league you will need to get your swid and espn_s2. -You can find these two values after logging into your espn fantasy football account on espn's website. -(Chrome Browser) -Right click anywhere on the website and click inspect option. -From there click Application on the top bar. -On the left under Storage section click Cookies then http://fantasy.espn.com. -From there you should be able to find your swid and espn_s2 variables and values. - -## Troubleshooting / FAQ - -**League must be full.** - -The bot isn't working -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. - -How are power ranks calculated? -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 - -Is there a version of this for Yahoo/CBS/NFL/[insert other site]? -No, this would require a significant rework for other sites. - -I'm not getting the init message -Are you sure you flipped the switch in Heroku to activate the worker (the toggle should be blue)? The other common mistake is misconfigured environment variables. - -I keep getting the init message. -Remove your init message and it will stop. The init message is really for first setup to ensure it is working. - -How do I set another timezone? -Specify your variable https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List - -Is there a version of this for Messenger/WhatsApp/[insert other chat]? -No, but I am open to pull requests implementing their API for additional cross platform support. - -My Standings look wrong. I have weird (+1) in it. -TOP_HALF_SCORING: If set to True, when standings are posted on Wednesday it will also include top half scoring wins -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.
## Getting Started for development and testing @@ -270,23 +216,24 @@ python3 setup.py install ``` ### Environment Variables - -- BOT_ID: This is your Bot ID from the GroupMe developers page (REQUIRED IF USING GROUPME) -- SLACK_WEBHOOK_URL: This is your Webhook URL from the Slack App page (REQUIRED IF USING SLACK) -- DISCORD_WEBHOOK_URL: This is your Webhook URL from the Discord Settings page (REQUIRED IF USING DISCORD) -- LEAGUE_ID: This is your ESPN league id (REQUIRED) -- START_DATE: This is when the bot will start paying attention and sending messages to your chat. (2020-09-10 by default) -- END_DATE: This is when the bot will stop paying attention and stop sending messages to your chat. (2020-12-30 by default) -- LEAGUE_YEAR: ESPN League year to look at (2020 by default) -- TIMEZONE: The timezone that the messages will look to send in. (America/New_York by default) -- INIT_MSG: The message that the bot will say when it is started (can be blank or deleted for no message) -- TOP_HALF_SCORING: 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. -- RANDOM_PHRASE: If set to True, when matchups are posted on Tuesday it will also include a random phrase -- MONITOR_REPORT: 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 -- WAIVER_REPORT: If set to True, will provide a waiver report of add/drops. :warning: ESPN_S2 and SWID are required for this to work :warning: -- DAILY_WAIVER: 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: -- ESPN_S2: Used for private leagues. See [Private Leagues Section](#private-leagues) for documentation -- SWID: Used for private leagues. (Can be defined with or without {}) See [Private Leagues Section](#private-leagues) for documentation +|Var|Type|Required|Default|Description| +|---|----|--------|-------|-----------| +|BOT_ID|String|For GroupMe|None|This is your Bot ID from the GroupMe developers page| +|SLACK_WEBHOOK_URL|String|For Slack|None|This is your Webhook URL from the Slack App page| +|DISCORD_WEBHOOK_URL|String|For Discord|None|This is your Webhook URL from the Discord Settings page| +|LEAGUE_ID|String|Yes|None|This is your ESPN league id| +|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.| +|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.| +|LEAGUE_YEAR|String|Yes|Currernt Year (YYYY)|ESPN League year to look at| +|TIMEZONE|String|Yes|America/New_York|The timezone that the messages will look to send in.| +|INIT_MSG|String|No|None|The message that the bot will say when it is started.| +|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.| +|RANDOM_PHRASE|Bool|No|False|If set to True, when matchups are posted on Tuesday it will also include a random phrase| +|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| +|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:| +|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:| +|ESPN_S2|String|For Private leagues|None|Used for private leagues. See [Private Leagues Section](#private-leagues) for documentation| +|SWID|String|For Private leagues|None|Used for private leagues. (Can be defined with or without {}) See [Private Leagues Section](#private-leagues) for documentation| ### Running with Docker @@ -327,3 +274,42 @@ you can run these tests by changing the directory to the `gamedaybot` directory python3 setup.py test ``` + +#### Private Leagues + +For private league you will need to get your swid and espn_s2. +You can find these two values after logging into your espn fantasy football account on espn's website. +(Chrome Browser) +Right click anywhere on the website and click inspect option. +From there click Application on the top bar. +On the left under Storage section click Cookies then http://fantasy.espn.com. +From there you should be able to find your swid and espn_s2 variables and values. +## FAQ + +**League must be full.** + +The bot isn't working + +* 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. + +How are power ranks calculated? + +* 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 + +Is there a version of this for Yahoo/CBS/NFL/[insert other site]? + +* No, this would require a significant rework for other sites. + +How do I set another timezone? + +* Specify your variable https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List + +Is there a version of this for Messenger/WhatsApp/[insert other chat]? + +* No, but I am open to pull requests implementing their API for additional cross platform support. + +My Standings look wrong. I have weird (+1) in it. + +* TOP_HALF_SCORING: If set to True, when standings are posted on Wednesday it will also include top half scoring wins +* 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. +