def initial_setup(): # read in private league settings from config.py league_id = config.league_id year = config.year # credentials to let us see a private league espn_s2 = config.espn_s2 swid = config.swid # get league info from ESPN league = League(league_id,year,espn_s2,swid) # define some variables for convenience global scoreboard global teams global settings global power_rankings scoreboard = league.scoreboard() teams = league.teams settings = league.settings power_rankings = league.power_rankings
def matchups_handler(msg): league = League(LEAGUE_ID, YEAR) return get_matchups(league)
from espnff import League, Team league_id = 413011 # random league that works: 125878 year = 2017 league = League(league_id, year) for team in league.teams: print(team) #for team in league.teams: # print(team.owner) team1 = league.teams[0] print(team1.points_for) print(team1.schedule) print(type(team1)) #print(team1.get_roster(week=5))
def bot_main(function): try: bot_id = os.environ["BOT_ID"] except KeyError: bot_id = 1 try: webhook_url = os.environ["WEBHOOK_URL"] except KeyError: webhook_url = 1 league_id = os.environ["LEAGUE_ID"] try: year = os.environ["LEAGUE_YEAR"] except KeyError: year = 2018 bot = GroupMeBot(bot_id) slack_bot = SlackBot(webhook_url) league = League(league_id, year) test = False if test: print(get_matchups(league)) print(get_scoreboard(league)) print(get_scoreboard_short(league)) print(get_close_scores(league)) print(get_power_rankings(league)) print(get_trophies(league)) print(get_survivor_results(league)) function = "get_final" #bot.send_message(get_trophies(league)) bot.send_message("test complete") slack_bot.send_message("test complete") if function == "get_matchups": text = get_matchups(league) bot.send_message(text) slack_bot.send_message(text) elif function == "get_scoreboard": text = get_scoreboard(league) bot.send_message(text) slack_bot.send_message(text) elif function == "get_scoreboard_short": text = get_scoreboard_short(league) bot.send_message(text) slack_bot.send_message(text) elif function == "get_close_scores": text = get_close_scores(league) bot.send_message(text) slack_bot.send_message(text) elif function == "get_power_rankings": text = get_power_rankings(league) bot.send_message(text) slack_bot.send_message(text) elif function == "get_trophies": text = get_trophies(league) bot.send_message(text) slack_bot.send_message(text) elif function == "get_survivor_results": text = get_survivor_results(league) bot.send_message(text) slack_bot.send_message(text) elif function == "get_final": text = "Final " + get_scoreboard_short(league, True) text = text + "\n\n" + get_trophies(league) text = text + "\n\n" + get_survivor_results(league) if test: print(text) else: bot.send_message(text) slack_bot.send_message(text) elif function == "init": try: text = os.environ["INIT_MSG"] bot.send_message(text) slack_bot.send_message(text) except KeyError: #do nothing here, empty init message pass else: text = "Something happened. HALP" bot.send_message(text) slack_bot.send_message(text)
def rank(): return render_template('ranks.html', league=League(1140354, 2017).power_rankings(week=3))
def get_league(self, league_id, year): """Fetch the League object, passing auth_s2 and auth_swid for a private league.""" return League(league_id, year, self.__auth_s2, self.__auth_swid)
def createLeagueObject(leagueId, year=getCurrentYear()): return League(leagueId, year)
def __init__(self, year, leagueID, cookie1, cookie2): self.projQB = pd.DataFrame() self.projRB = pd.DataFrame() self.projWR = pd.DataFrame() self.projTE = pd.DataFrame() self.league_id = leagueID self.year = year self.league = League(self.league_id, self.year, espn_s2=cookie1, swid=cookie2) self.teams = self.league.teams ''' self.teams[0].keepers = {'Josh Gordon':6,'JuJu Smith-Schuster':6} self.teams[1].keepers = {'David Johnson':16,'Michael Thomas':11} self.teams[2].keepers = {'Jordan Howard':11,'Marvin Jones':6} self.teams[3].keepers = {'Adam Thielen':7,'Dalvin Cook':42} self.teams[4].keepers = {'DeAndre Hopkins':42,'Melvin Gordon':15} self.teams[5].keepers = {'Joe Mixon':32,'Travis Kelce':23} self.teams[6].keepers = {'Ezekiel Elliott':56,'Jerick McKinnon':6} self.teams[7].keepers = {'Devonta Freeman':16,'Todd Gurley':53} self.teams[8].keepers = {'Leonard Fournette':43,'Keenan Allen':32} self.teams[9].keepers = {'Alvin Kamara':6,'Kareem Hunt':16} self.teams[0].tradeCosts = -15 self.teams[2].tradeCosts = -5 ''' self.settings = self.league.settings self.regSeason = self.settings.reg_season_count self.numTeams = self.settings.team_count self.numKeepers = self.settings.keeper_count self.rosterConstr = self.settings.roster self.auctionCap = 200 self.keeperCost = 0 self.tradeCosts = 0 self.numKept = 0 self.scoring = { 'pYards': 0.04, 'Int': -2, 'pTD': 4, 'p2PT': 2, 'rshYards': 0.1, 'rshTD': 6, 'rsh2PT': 2, 'recYards': 0.1, 'recTD': 6, 'rec': 0.5, 'rec2PT': 2, 'KRTD': 6, 'FRTD': 6, 'PRTD': 6, 'intTD': 6, 'fumL': -2, 'BPTD': 6, 'ret2PT': 2, 'sfty': 1 } self.positions = ['QB', 'RB', 'WR', 'TE'] self.projQB = pd.read_csv("projQB.csv", index_col='Player') self.projQB.dropna(inplace=True) self.projQB['YDS'] = self.projQB['YDS'].str.replace(',', '') self.projQB.ix[:, 1:] = self.projQB.ix[:, 1:].astype(float) self.projRB = pd.read_csv("projRB.csv", index_col='Player') self.projRB.dropna(inplace=True) self.projRB['YDS'] = self.projRB['YDS'].str.replace(',', '') self.projRB.ix[:, 1:] = self.projRB.ix[:, 1:].astype(float) self.projWR = pd.read_csv("projWR.csv", index_col='Player') self.projWR.dropna(inplace=True) self.projWR['YDS'] = self.projWR['YDS'].str.replace(',', '') self.projWR.ix[:, 1:] = self.projWR.ix[:, 1:].astype(float) self.projTE = pd.read_csv("projTE.csv", index_col='Player') self.projTE.dropna(inplace=True) self.projTE['YDS'] = self.projTE['YDS'].str.replace(',', '') self.projTE.ix[:, 1:] = self.projTE.ix[:, 1:].astype(float) ''' for team in range(0,len(self.teams)): self.keeperCost+=sum(self.teams[team].keepers.values()) self.tradeCosts+=self.teams[team].tradeCosts self.numKept+=len(self.teams[team].keepers.keys()) for keeper in self.teams[team].keepers: if keeper in self.projQB.index: self.projQB.drop(keeper,axis =0, inplace = True) elif keeper in self.projRB.index: self.projRB.drop(keeper,axis = 0, inplace = True) elif keeper in self.projWR.index: self.projWR.drop(keeper,axis=0, inplace = True) elif keeper in self.projTE.index: self.projTE.drop(keeper, axis = 0, inplace = True) else: print (keeper) print("you f****d up Aaron") ''' self.freeMoney = (self.numTeams * 200) + (self.tradeCosts) - self.keeperCost - ( (len(self.rosterConstr.keys()) - 1) * self.numTeams) + (self.numKept * self.numTeams) #print (self.rosterConstr) pass
# Import table printing from prettytable import PrettyTable # Import the league class and set the ID from espnff import League league_id = 1743204 league_id = 1743205 # Output information to file output = open('output.txt', 'w') # An array for the years years = [2014, 2015, 2016, 2017] # Output league name s = "######################\n## " + League( league_id, 2018).settings.name + " ##\n######################\n" output.writelines(s) # For loop to go through every year for year in years: league = League(league_id, year) settings = league.settings matchup_count = int(settings.team_count / 2) # Print out year header s = "\n########\n# " + str(year) + " #\n########\n\n" output.writelines(s) # Hold all teams in teams array teams = league.teams
def power_graphs(league_id=None, year=None, espn_s2=None, swid=None, latestWeek=17): if league_id == None: raise Exception('Must enter league ID...Exiting') elif year == None: raise Exception('Must enter league year...Exiting') league = League(league_id, year, espn_s2, swid) wks = [] twks = [] trks = [] def find_index(df, column, find_term): df = df[column][df.index[df[column] == find_term]] return (df.index[0]) for i in range(0, latestWeek): w = i + 1 wk = league.power_rankings(week=w) wk = pd.DataFrame(wk, columns=['Score', 'Team']) wks.append(wk) wk = wks wks = [] for i in range(len(wk)): t = [] s = [] for x in range(len(wk[i])): tb = str(wk[i]['Team'][x]) tb = str(tb)[5:(len(tb) - 1)] t.append(tb) s.append(float(wk[i]['Score'][x])) ts = pd.DataFrame({'Team': t, 'Score': s}) wks.append(ts) for i in range(len(wks)): wks[i].sort_values('Team', inplace=True) wks[i].reset_index(drop=True, inplace=True) wksTeam = [] for i in range(len(wks)): place = [i + 1] place.extend(list(wks[i]['Score'])) wksTeam.append(place) c = ['Week'] c.extend(sorted(t)) ##Change this to fit your league's team names color_dict = { 'Team1': '#00e9ff', 'Team2': '#0083ff', "Team3": '#2e00ff', 'Team4': '#981E32', 'Team5': '#521f6d', 'Team6': '#d8ff00', "Team7": '#002C5F', 'Team8': '#ffa100', 'Team9': '#6d571f', 'Team10': '#ff0000', 'Team11': '#46b230', 'Team12': '#00ff11' } for i in range(len(sorted(t))): color_dict[t[i]] = color_dict['Team' + str(i + 1)] tpd = pd.DataFrame(data=wksTeam, columns=c) tpd.to_csv('wk' + str(len(wksTeam)) + ' power scores.csv', index=False) tpd = pd.read_csv('wk' + str(len(wksTeam)) + ' power scores.csv', index_col='Week') for i in range(len(wks)): test = wks[i].sort_values('Score', ascending=False) twks.append(test.reset_index(drop=True)) for x in range(len(twks)): place = [x + 1] for i in range(len(sorted(t))): place.append(find_index(twks[x], 'Team', sorted(t)[i]) + 1) trks.append(place) ranks = pd.DataFrame(data=trks, columns=c) ranks.to_csv('wk' + str(len(wksTeam)) + ' power rankings.csv', index=False) ranks = pd.read_csv('wk' + str(len(wksTeam)) + ' power rankings.csv', index_col='Week') lines = tpd.plot.line( title='Power Rankings', table=True, use_index=False, color=[color_dict.get(x, '#333333') for x in ranks.columns]) plt.axes().get_xaxis().set_visible(False) plt.legend(bbox_to_anchor=(1.25, 1), loc='upper right', borderaxespad=0.) plt.plot(marker='o') plt.subplots_adjust(0.13, 0.36, 0.81, 0.96, 0.2, 0.2) lines = ranks.plot.line( title='Power Score', table=True, use_index=False, color=[color_dict.get(x, '#333333') for x in ranks.columns]).invert_yaxis() plt.axes().get_xaxis().set_visible(False) plt.legend(bbox_to_anchor=(1.25, 1), loc='upper right', borderaxespad=0.) plt.plot(marker='o') plt.subplots_adjust(0.13, 0.36, 0.81, 0.96, 0.2, 0.2) plt.show()
def bot_main(function): bot_id = str(os.environ["BOT_ID"]) league_id = str(os.environ["LEAGUE_ID"]) try: year = os.environ["LEAGUE_YEAR"] except KeyError: year = 2018 bot = GroupMeBot(bot_id) league = League(league_id, year) test = False if test: print(get_matchups(league)) print(get_scoreboard(league)) print(get_scoreboard_short(league)) print(get_close_scores(league)) print(get_power_rankings(league)) print(get_trophies(league)) function = "get_final" #bot.send_message(get_trophies(league)) if function == "get_matchups": text = get_matchups(league) bot.send_message(text) elif function == "get_scoreboard": text = get_scoreboard(league) bot.send_message(text) elif function == "get_scoreboard_short": text = get_scoreboard_short(league) bot.send_message(text) elif function == "get_close_scores": text = get_close_scores(league) bot.send_message(text) elif function == "get_power_rankings": text = get_power_rankings(league) bot.send_message(text) elif function == "get_trophies": text = get_trophies(league) bot.send_message(text) elif function == "get_final": text = "Final " + get_scoreboard_short(league, True) text = text + "\n\n" + get_trophies(league) if test: print(text) else: bot.send_message(text) elif function == "init": try: text = str(os.environ["INIT_MSG"]) if text == "hide": pass elif text == "power_rankings": text = get_power_rankings(league) bot.send_message(text) else: bot.send_message(text) except KeyError: #do nothing here, empty init message pass else: text = "Something happened. HALP" bot.send_message(text)
def get_league(self, league_id, year): return League(league_id, year, self.__auth_s2, self.__auth_swid)
import django from django.conf import settings TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['.'], }] settings.configure(TEMPLATES=TEMPLATES) django.setup() from django.template.loader import get_template from django.template import Context html_template = get_template('LeagueHistoryTemplate.html') league_id = 118990 #552541 year = 2018 league = League(league_id, 2018) current_teams = league.teams champions = [] top_10_games = [] # get this year's teams and their current records for team in current_teams: team.seasons = [{ "year": 2018, "wins": team.wins, "losses": team.losses, "points_for": team.points_for, "points_against": team.points_against }]
def __init__(self, bot, league_id, year): self.bot = bot self.league_id = 273350 self.year = 2017 self.league = League(league_id, year)
class Stats(): def __init__(self, bot, league_id, year): self.bot = bot self.league_id = 273350 self.year = 2017 self.league = League(league_id, year) 'Pulled the server channel ID to be stored in the database' async def on_server_join(self, server): print("test") print("Joining server: {0.id} ({0.name})".format(server)) 'League Info' @commands.has_permissions(administrator=True) @commands.command(pass_context=True) async def leagueid(self, ctx, *, id: str): try: try: self.league = League(int(id), 2017) except: await bot.say("Unable to find a league with ID \"" + id +"\".") print("New League ID: " + str(self.league.league_id)) await self.bot.say("The league has been changed to: " + self.league.settings.name) except discord.errors.Forbidden: await self.bot.say("Missing Permissions.") 'Team Data Commands' @commands.command() async def teams(self): teamList = [] await self.bot.say("Teams:\n==================") for team in self.league.teams: teamList.append(team.team_name) await self.bot.say('\n '.join(teamList)) @commands.command() async def east(self): eastList = [] await self.bot.say("East Division:\n==================") for team in self.league.teams: if team.division_id == 0: eastList.append(team.team_name) #await self.bot.say(team.team_name) await self.bot.say('\n'.join(eastList)) @commands.command() # @commands.has_permissions(manage_messages=True) async def west(self): westList = [] await self.bot.say("West Division:\n==================") for team in self.league.teams: if team.division_id == 1: westList.append(team.team_name) #await self.bot.say(team.team_name) await self.bot.say('\n'.join(westList)) @commands.command(pass_context=True) async def won(self, ctx, *, name: str): for team in self.league.teams: if team.team_name.lower() == name.lower(): await self.bot.say(team.team_name + " has won " + str(team.wins) + " games!") return elif name.lower() in team.owner.lower(): await self.bot.say(team.owner + "'s team has won " + str(team.wins) + " games!") return await self.bot.say("Hmm...I couldn't find a team or owner named \"" + name + "\".") @commands.command(pass_context=True) async def lost(self, ctx, *, name: str): for team in self.league.teams: if team.team_name.lower() == name.lower(): await self.bot.say(team.team_name + " has lost " + str(team.losses) + " games!") return elif name.lower() in team.owner.lower(): await self.bot.say(team.owner + "'s team has lost " + str(team.losses) + " games!") return await self.bot.say("Hmm...I couldn't find a team or owner named \"" + name + "\".") @commands.command(pass_context=True) async def schedule(self, ctx, *, name: str): for team in self.league.teams: if team.team_name.lower() == name.lower(): await self.bot.say(team.owner + "'s Schedule") await self.bot.say("==========================") await self.bot.say('\n'.join('Week {}:\t{}'.format(*k) for k in enumerate(ctx.message.author.roles, 1))) return elif name.lower() in team.owner.lower(): await self.bot.say(team.owner + "'s Schedule") await self.bot.say("==========================") await self.bot.say('\n'.join('Week {}:\t{}'.format(*k) for k in enumerate(map(attrgetter('owner'), team.schedule), 1))) return await self.bot.say("Hmm...I couldn't find a team or owner named \"" + name + "\".") @commands.command(pass_context=True) async def points_for(self, ctx, *, name: str): for team in self.league.teams: if team.team_name.lower() == name.lower(): await self.bot.say(team.owner + " has scored " + str(team.points_for) + " total points") return elif name.lower() in team.owner.lower(): await self.bot.say(team.owner + " has scored " + str(team.points_for) + " total points") return await self.bot.say("Hmm...I couldn't find a team or owner named \"" + name + "\".") @commands.command(pass_context=True) async def points_against(self, ctx, *, name: str): for team in self.league.teams: if team.team_name.lower() == name.lower(): await self.bot.say(team.owner + " has had " + str(team.points_for) + " total points scored against them.") return elif name.lower() in team.owner.lower(): await self.bot.say(team.owner + " has had " + str(team.points_for) + " total points scored against them.") return await self.bot.say("Hmm...I couldn't find a team or owner named \"" + name + "\".") @commands.command(pass_context=True) async def scores(self, ctx, *, name: str): for team in self.league.teams: if team.team_name.lower() == name.lower(): await self.bot.say(team.owner + "'s Scores\n==========================") await self.bot.say('\n'.join('Week {}:\t{}'.format(*k) for k in enumerate(team.scores, 1))) return elif name.lower() in team.owner.lower(): await self.bot.say(team.owner + "'s Scores\n==========================") await self.bot.say('\n'.join('Week {}:\t{}'.format(*k) for k in enumerate(team.scores, 1))) return await self.bot.say("Hmm...I couldn't find a team or owner named \"" + name + "\".") @commands.command(pass_context=True) async def ranking(self, ctx, *, week_num): 'Need to fix the ranking output' await self.bot.say('\n'.join('{}:\t{}'.format(*k) for k in enumerate(league.power_rankings(week=int(week_num)), 1))) @commands.command() async def scoreboard(self): scoreboard = self.league.scoreboard() counter = 0 await self.bot.say("Current Week Matchups\n==========================") for score in scoreboard: matchup = scoreboard[counter] await self.bot.say(matchup.home_team.owner + ":\t" + str(matchup.home_score) + " pts\tvs.\t" + matchup.away_team.owner + ":\t" + str(matchup.away_score) + "pts ") counter = counter + 1 @commands.command(pass_context=True) async def ping(self, ctx): pingtime = time.time() pingms = await self.bot.say("Pinging... `{}'s` location".format(ctx.message.author.mention)) ping = time.time() - pingtime await self.bot.edit_message(pingms, "The ping time is `%.01f seconds`" % ping)