diff --git a/cogs/admins.py b/cogs/admins.py index 37ed869..a19d81d 100644 --- a/cogs/admins.py +++ b/cogs/admins.py @@ -65,11 +65,11 @@ class Admins(commands.Cog): logging.error(f'Error blasting a message: {type(e)}: {e}') await interaction.response.send_message(content=f'Uh oh\n\n{type(e)}: {e}') - @commands.command(name='sendstats', help='all, batting, pitching') - @commands.is_owner() - async def send_stats_command(self, ctx, which='all'): - trans_cog = self.bot.get_cog('Transactions') - await trans_cog.send_stats_to_sheets(which=which) + # @commands.command(name='sendstats', help='all, batting, pitching') + # @commands.is_owner() + # async def send_stats_command(self, ctx, which='all'): + # trans_cog = self.bot.get_cog('Transactions') + # await trans_cog.send_stats_to_sheets(which=which) @commands.command(name='test', hidden=True) @commands.is_owner() diff --git a/cogs/transactions.py b/cogs/transactions.py index 98f2572..07e9cb9 100644 --- a/cogs/transactions.py +++ b/cogs/transactions.py @@ -2,9 +2,9 @@ import re import copy from helpers import * -from db_calls import * +from db_calls import db_get, db_patch, get_team_by_owner, get_team_by_abbrev, get_player_by_name, patch_player from discord.ext import commands, tasks -OFFSEASON_FLAG = False +OFFSEASON_FLAG = True class SBaTransaction: @@ -123,70 +123,90 @@ class SBaTransaction: async def get_player_moves(self, player, this_week): if this_week: - return await get_transactions( - self.current['season'], - week_start=self.current['week'], - player_id=player['id'] - ) + t_query = await db_get('transactions', params=[ + ('season', self.current['season']), ('week_start', self.current['week']), + ('week_end', self.current['season']), ('player_id', player['id']) + ]) + return t_query['transactions'] else: - return await get_transactions( - self.current['season'], - week_start=self.effective_week, - player_id=player['id'] - ) + t_query = await db_get('transactions', params=[ + ('season', self.current['season']), ('week_start', self.effective_week), + ('week_end', self.effective_week), ('player_id', player['id']) + ]) + return t_query['transactions'] async def check_major_league_errors(self, team): wara = 0 mil_wara = 0 this_team = self.teams[team]['team'] - team_roster = await get_players(self.current['season'], this_team['abbrev']) - mil_roster = await get_players(self.current['season'], f'{this_team["abbrev"]}MiL') + # team_roster = await get_players(self.current['season'], this_team['abbrev']) + t_query = await db_get('players', params=[ + ('season', self.current['season']), ('team_id', this_team['id']) + ]) + team_roster = t_query['players'] + + ml_query = await db_get('teams', params=[ + ('season', self.current['season']), ('team_abbrev', f'{this_team["abbrev"]}MiL') + ]) + # mil_roster = await get_players(self.current['season'], f'{this_team["abbrev"]}MiL') + m_query = await db_get('players', params=[ + ('season', self.current['season']), ('team_id', ml_query['teams'][0]) + ]) + mil_roster = m_query['players'] for player in team_roster: - wara += team_roster[player]['wara'] + wara += player['wara'] for player in mil_roster: - mil_wara += mil_roster[player]['wara'] + mil_wara += player['wara'] if self.effective_week > self.current['week']: - set_moves = await get_transactions( - self.current['season'], team_abbrev=this_team['abbrev'], week_start=self.effective_week, - week_end=self.effective_week - ) - freeze_moves = await get_transactions( - self.current['season'], team_abbrev=this_team['abbrev'], week_start=self.effective_week, - week_end=self.effective_week, frozen=True - ) - moves = {**set_moves, **freeze_moves} + # set_moves = await get_transactions( + # self.current['season'], team_abbrev=this_team['abbrev'], week_start=self.effective_week, + # week_end=self.effective_week + # ) + t_query = await db_get('transactions', params=[ + ('season', self.current['season']), ('week_start', self.effective_week), + ('week_end', self.effective_week), ('team_abbrev', this_team['abbrev']) + ]) + set_moves = t_query['transactions'] + # freeze_moves = await get_transactions( + # self.current['season'], team_abbrev=this_team['abbrev'], week_start=self.effective_week, + # week_end=self.effective_week, frozen=True + # ) + t_query = await db_get('transactions', params=[ + ('season', self.current['season']), ('week_start', self.effective_week), + ('week_end', self.effective_week), ('team_abbrev', this_team['abbrev']) + ]) + freeze_moves = t_query['transactions'] + moves = set_moves + freeze_moves for x in moves: # If player is joining this team, add to roster and add WARa - if moves[x]['newteam'] == this_team: - team_roster[moves[x]['player']['name']] = moves[x]['player'] - wara += moves[x]['player']['wara'] + if x['newteam'] == this_team: + team_roster.append(x['player']) + wara += x['player']['wara'] # If player is joining MiL team, add to roster and add WARa - elif moves[x]['newteam']['id'] == this_team['id'] + 2: - mil_roster[moves[x]['player']['name']] = moves[x]['player'] - mil_wara += moves[x]['player']['wara'] + elif x['newteam']['abbrev'] == f'{this_team["abbrev"]}MiL': + mil_roster.append(x['player']) + mil_wara += x['player']['wara'] # If player is leaving this team, remove from roster and subtract WARa - if moves[x]['oldteam'] == this_team: - # del team_roster[moves[x]['player']['name']] - team_roster.pop(moves[x]['player']['name'], None) - wara -= moves[x]['player']['wara'] + if x['oldteam'] == this_team: + team_roster.remove(x['player']) + wara -= x['player']['wara'] # If player is leaving MiL team, remove from roster and subtract WARa - elif moves[x]['oldteam']['id'] == this_team['id'] + 2: - # del team_roster[moves[x]['player']['name']] - mil_roster.pop(moves[x]['player']['name'], None) - mil_wara -= moves[x]['player']['wara'] + elif x['oldteam']['abbrev'] == f'{this_team["abbrev"]}MiL': + mil_roster.remove(x['player']) + mil_wara -= x['player']['wara'] for x in self.players: # If player is joining this team, add to roster and add WARa if self.players[x]['to'] == this_team: - team_roster[self.players[x]['player']['name']] = self.players[x]['player'] + team_roster.append(self.players[x]['player']) wara += self.players[x]['player']['wara'] # If player is joining MiL team, add to roster and add WARa elif self.players[x]['to']['abbrev'] == f'{this_team["abbrev"]}MiL': - mil_roster[self.players[x]['player']['name']] = self.players[x]['player'] + mil_roster.append(self.players[x]['player']) mil_wara += self.players[x]['player']['wara'] # If player is joining IL team, remove from roster and cut WARa elif self.players[x]['to']['abbrev'] == f'{this_team["abbrev"]}IL': @@ -194,14 +214,14 @@ class SBaTransaction: # If player is leaving this team next week, remove from roster and subtract WARa if self.players[x]['player']['team'] == this_team: - team_roster.pop(self.players[x]['player']['name'], None) + team_roster.remove(self.players[x]['player']) # 06-13: COMMENTED OUT TO RESOLVE MID-WEEK IL REPLACEMENT BEING SENT BACK DOWN # if self.effective_week != self.current['week']: wara -= self.players[x]['player']['wara'] # If player is leaving MiL team next week, remove from roster and subtract WARa if self.players[x]['player']['team']['abbrev'] == f'{this_team["abbrev"]}MiL': - mil_roster.pop(self.players[x]['player']['name'], None) + mil_roster.remove(self.players[x]['player']) if self.effective_week != self.current['week']: mil_wara -= self.players[x]['player']['wara'] @@ -273,10 +293,11 @@ class SBaTransaction: 'frozen': frozen }) - await post_transactions(moves) + await db_post('transactions', payload={'count': len(moves), 'moves': moves}) - for x in self.picks: - await patch_draftpick(self.picks[x]['pick']['id'], owner_id=self.picks[x]['to']['id']) + # TO BE UPDATED IF PICK DRAFTING RETURNS + # for x in self.picks: + # await patch_draftpick(self.picks[x]['pick']['id'], owner_id=self.picks[x]['to']['id']) return moveid @@ -324,21 +345,21 @@ class Transactions(commands.Cog): if now.weekday() == 0 and now.hour == 6 and not current['freeze']: # Fall/Winter current['week'] += 1 if OFFSEASON_FLAG: - if not self.trade_season: - await patch_current(week=current['week']) - await self.run_transactions(current) - stars = f'{"":*<26}' - freeze_message = f'```\n' \ - f'{stars}\n' \ - f' IT\'S TRADE SZN BITCHES\n' \ - f'{stars}\n```' - logging.info(f'Freeze string:\n\n{freeze_message}') - await send_to_channel(self.bot, 'sba-network-news', freeze_message) - self.trade_season = True + pass + # if not self.trade_season: + # await db_patch('current', object_id=current['id'], params=[('week', current['week'])]) + # await self.run_transactions(current) + # stars = f'{"":*<26}' + # freeze_message = f'```\n' \ + # f'{stars}\n' \ + # f' IT\'S TRADE SZN BITCHES\n' \ + # f'{stars}\n```' + # logging.info(f'Freeze string:\n\n{freeze_message}') + # await send_to_channel(self.bot, 'sba-network-news', freeze_message) + # self.trade_season = True else: - await patch_current(week=current['week'], freeze=True) + await db_patch('current', object_id=current['id'], params=[('week', current['week']), ('freeze', True)]) await self.run_transactions(current) - await self.update_roster_sheet(current['season']) logging.info(f'Building freeze string') week_num = f'Week {current["week"]}' @@ -354,7 +375,7 @@ class Transactions(commands.Cog): # elif now.weekday() == 5 and now.hour == 5 and current['freeze']: # Spring/Summer elif now.weekday() == 5 and now.hour == 6 and current['freeze']: # Fall/Winter if not OFFSEASON_FLAG: - await patch_current(freeze=False) + await db_patch('current', object_id=current['id'], params=[('freeze', False)]) week_num = f'Week {current["week"]}' stars = f'{"":*<30}' @@ -367,25 +388,39 @@ class Transactions(commands.Cog): self.trade_season = False async def run_transactions(self, current): - all_moves = await get_transactions(current['season'], week_start=current['week'], week_end=current['week']) - if len(all_moves) == 0: + m_query = await db_get('transactions', params=[ + ('season', current['season']), ('week_start', current['week']), ('week_end', current['week']) + ]) + if m_query['count'] == 0: return + all_moves = m_query['transactions'] - for move in [*all_moves.values()]: - try: - if (move['newteam']['abbrev'][-3:] == 'MiL' and move['oldteam']['abbrev'] == 'FA') or \ - move['newteam']['abbrev'][-2:] == 'IL' or move['newteam']['abbrev'].lower() == 'fa': - dem_week = current['week'] - else: - dem_week = current['week'] + 1 + # for move in [*all_moves.values()]: + # try: + # if (move['newteam']['abbrev'][-3:] == 'MiL' and move['oldteam']['abbrev'] == 'FA') or \ + # move['newteam']['abbrev'][-2:] == 'IL' or move['newteam']['abbrev'].lower() == 'fa': + # dem_week = current['week'] + # else: + # dem_week = current['week'] + 1 + # + # await patch_player( + # move['player']['id'], + # team_id=move['newteam']['id'], + # demotion_week=dem_week + # ) + # except Exception as e: + # await send_to_channel(self.bot, 'commissioners-office', f'Error running move:\n{move["moveid"]}') - await patch_player( - move['player']['id'], - team_id=move['newteam']['id'], - demotion_week=dem_week - ) - except Exception as e: - await send_to_channel(self.bot, 'commissioners-office', f'Error running move:\n{move["moveid"]}') + for x in all_moves: + if (x['newteam']['abbrev'][-3:] == 'MiL' and x['oldteam']['abbrev'] == 'FA') or \ + x['newteam']['abbrev'][-2:] == 'IL' or x['newteam']['abbrev'] == 'FA': + dem_week = current['week'] + else: + dem_week = current['week'] + 1 + + x['player']['team'] = x['newteam'] + x['player']['demotion_week'] = dem_week + await patch_player(x['player']) async def notify_cancel(self, trans_data): team = trans_data[1] @@ -402,131 +437,155 @@ class Transactions(commands.Cog): await gm_two.send(cancel_text) async def process_freeze_moves(self, current): - all_moves = await get_transactions( - season=current['season'], - week_start=current['week'], - week_end=current['week'] + 1, - frozen=True - ) - if len(all_moves) == 0: + # all_moves = await get_transactions( + # season=current['season'], + # week_start=current['week'], + # week_end=current['week'] + 1, + # frozen=True + # ) + m_query = await db_get('transactions', params=[ + ('season', current['season']), ('week_start', current['week']), ('week_end', current['week'] + 1), + ('frozen', True) + ]) + if m_query['count'] == 0: logging.warning(f'No transactions to process for the freeze in week {current["week"]}') - else: - logging.info(f'freeze / all_moves: {len(all_moves)}') + return - # {'player name': [[Player, TeamAdding, moveid], [Player, OtherTeamAdding, moveid]]} - added_players = {} - contested_players = {} + moves = m_query['transactions'] + logging.info(f'freeze / all_moves: {len(moves)}') - for move in [*all_moves.values()]: - if move['newteam']['abbrev'][-3:] == 'MiL': - new_team = await get_one_team(move['newteam']['abbrev'][:-3], timeout=15) - else: - new_team = move['newteam'] - team_record = await get_team_record(new_team, week_num=current["week"]) - tiebreaker = team_record["pct"] + (random.randint(10000, 99999) * .00000001) - if move["player"]["name"] not in added_players.keys(): - added_players[move["player"]["name"]] = [[move["player"], move["newteam"], tiebreaker, move["moveid"]]] - else: - added_players[move["player"]["name"]].append( - [move["player"], move["newteam"], tiebreaker, move["moveid"]] - ) - logging.info(f'freeze / added_players: {added_players.keys()}') + # {'player name': [[Player, TeamAdding, moveid], [Player, OtherTeamAdding, moveid]]} + added_players = {} + contested_players = {} - # Check added_players for keys (player names) with more than one move in their list - for name in added_players: - if len(added_players[name]) > 1: - contested_players[name] = added_players[name] - logging.info(f'freeze / contested_players: {contested_players.keys()}') - - # Determine winner for contested players, mark moveid cancelled for loser - def tiebreaker(val): - logging.info(f'tiebreaker: {val}') - return val[2] - - for guy in contested_players: - contested_players[guy].sort(key=tiebreaker) - first = True - logging.info(f'Contested Player: {contested_players[guy]}\n\n') - for x in contested_players[guy]: - logging.info(f'First: {first} / x: {x}\n\n') - if not first: - await patch_transaction(move_id=x[3], cancelled=True, frozen=False) - await self.notify_cancel(x) - else: - first = False - - # Post transactions that are not cancelled - final_moves = await get_transactions( - season=current['season'], - week_start=current["week"], - week_end=current["week"] + 1, - frozen=True - ) - - these_ids = [] - for x in final_moves: - if final_moves[x]["moveid"] not in these_ids: - these_ids.append(final_moves[x]["moveid"]) - - # TODO: not sure I like this method of running moves - for move_id in these_ids: - await patch_transaction(move_id, frozen=False) - await self.post_move_to_transaction_log(move_id) - await self.send_move_to_sheets(move_id) - - # # In case there were SIL moves that go this week, run transactions - # await self.run_transactions(current) - - async def send_move_to_sheets(self, move_id): - return - current = await db_get('current') - sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') - trans_tab = sheets.open_by_key(SBA_ROSTER_KEY).worksheet_by_title('Transactions') - all_vals = [] - all_moves = await get_transactions( - season=current['season'], - move_id=move_id - ) - - counter = 0 - for move in [*all_moves.values()]: - all_vals.append([ - move['player']['name'], - move['oldteam']['sname'], - move['newteam']['sname'], - move['week'], - current['transcount'] + counter + for move in moves: + if move['newteam']['abbrev'][-3:] == 'MiL': + new_team = await get_team_by_abbrev(move['newteam']['abbrev'][:-3], current['season']) + else: + new_team = move['newteam'] + # team_record = await get_team_record(new_team, week_num=current["week"]) + r_query = await db_get('standings', params=[ + ('season', current['season']), ('team_abbrev', new_team['abbrev']) ]) - counter += 1 + win_pct = r_query['standings'][0]['wins'] / ( + r_query['standings'][0]['wins'] + r_query['standings'][0]['losses']) - try: - trans_tab.update_values( - crange=f'A{current["transcount"] + 3}', - values=all_vals - ) - await patch_current(transcount=current['transcount'] + counter) - except Exception as e: - await send_to_channel(self.bot, 'commissioners-office', f'Failed sending move {move_id} to sheets') + tiebreaker = win_pct + (random.randint(10000, 99999) * .00000001) + if move["player"]["name"] not in added_players.keys(): + added_players[move["player"]["name"]] = [[move["player"], move["newteam"], tiebreaker, move["moveid"]]] + else: + added_players[move["player"]["name"]].append( + [move["player"], move["newteam"], tiebreaker, move["moveid"]] + ) + logging.info(f'freeze / added_players: {added_players.keys()}') + + # Check added_players for keys (player names) with more than one move in their list + for name in added_players: + if len(added_players[name]) > 1: + contested_players[name] = added_players[name] + logging.info(f'freeze / contested_players: {contested_players.keys()}') + + # Determine winner for contested players, mark moveid cancelled for loser + def tiebreaker(val): + logging.info(f'tiebreaker: {val}') + return val[2] + + for guy in contested_players: + contested_players[guy].sort(key=tiebreaker) + first = True + logging.info(f'Contested Player: {contested_players[guy]}\n\n') + for x in contested_players[guy]: + logging.info(f'First: {first} / x: {x}\n\n') + if not first: + await db_patch('transactions', object_id=x[3], params=[('frozen', False), ('cancelled', True)]) + # await patch_transaction(move_id=x[3], cancelled=True, frozen=False) + await self.notify_cancel(x) + else: + first = False + + # Post transactions that are not cancelled + # final_moves = await get_transactions( + # season=current['season'], + # week_start=current["week"], + # week_end=current["week"] + 1, + # frozen=True + # ) + m_query = await db_get('transactions', params=[ + ('season', current['season']), ('week_start', current['week']), ('week_end', current['week'] + 1), + ('frozen', True) + ]) + final_moves = m_query['transactions'] + + these_ids = [] + for x in final_moves: + if x["moveid"] not in these_ids: + these_ids.append(x["moveid"]) + + # TODO: not sure I like this method of running moves + for move_id in these_ids: + # await patch_transaction(move_id, frozen=False) + await db_patch('transactions', object_id=move_id, params=[('frozen', False)]) + await self.post_move_to_transaction_log(move_id) + + # async def send_move_to_sheets(self, move_id): + # return + # current = await db_get('current') + # sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') + # trans_tab = sheets.open_by_key(SBA_ROSTER_KEY).worksheet_by_title('Transactions') + # all_vals = [] + # all_moves = await get_transactions( + # season=current['season'], + # move_id=move_id + # ) + # + # counter = 0 + # for move in [*all_moves.values()]: + # all_vals.append([ + # move['player']['name'], + # move['oldteam']['sname'], + # move['newteam']['sname'], + # move['week'], + # current['transcount'] + counter + # ]) + # counter += 1 + # + # try: + # trans_tab.update_values( + # crange=f'A{current["transcount"] + 3}', + # values=all_vals + # ) + # await patch_current(transcount=current['transcount'] + counter) + # except Exception as e: + # await send_to_channel(self.bot, 'commissioners-office', f'Failed sending move {move_id} to sheets') async def post_move_to_transaction_log(self, move_id): current = await db_get('current') - all_moves = await get_transactions( - season=current['season'], - move_id=move_id - ) + # all_moves = await get_transactions( + # season=current['season'], + # move_id=move_id + # ) + m_query = await db_get('transactions', params=[ + ('season', current['season']), ('move_id', move_id) + ]) + all_moves = m_query['transactions'] this_team = None week_num = None move_string = '' - for move in [*all_moves.values()]: - if not this_team: + for move in all_moves: + if this_team is None: + if move['newteam']['abbrev'] != 'FA' and 'IL' not in move['newteam']['abbrev']: + this_team = move['newteam'] + else: + this_team = move['oldteam'] + if move['oldteam']['abbrev'] != 'FA' and 'IL' not in move['oldteam']['abbrev']: - this_team = await get_one_team(move['oldteam']['id']) - elif move['newteam']['abbrev'] != 'FA' and 'IL' not in move['newteam']['abbrev']: - this_team = await get_one_team(move['newteam']['id']) - if not week_num: + this_team = move['oldteam'] + + if week_num is None: week_num = move['week'] + move_string += f'**{move["player"]["name"]}** ({move["player"]["wara"]}) from ' \ f'{move["oldteam"]["abbrev"]} to {move["newteam"]["abbrev"]}\n' @@ -536,97 +595,97 @@ class Transactions(commands.Cog): await send_to_channel(self.bot, 'transaction-log', embed=embed) - async def send_stats_to_sheets(self, channel='commissioners-office', which='all'): - current = await db_get('current') - b_stats = None - p_stats = None + # async def send_stats_to_sheets(self, channel='commissioners-office', which='all'): + # current = await db_get('current') + # b_stats = None + # p_stats = None + # + # if which == 'all' or which == 'batting': + # await send_to_channel(self.bot, channel, 'Collecting batting stats...') + # b_stats = await get_battingstat(current['season'], timeout=90) + # + # if which == 'all' or which == 'pitching': + # await send_to_channel(self.bot, channel, 'Collecting pitching stats...') + # p_stats = await get_pitchingstat(current['season'], timeout=90) + # + # sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') + # if b_stats: + # await send_to_channel(self.bot, channel, f'Preparing batting stats ({len(b_stats)} lines found)...') + # batting_stats = [] + # + # for x in [*b_stats.values()]: + # batting_stats.append([ + # x['player']['name'], x['team']['abbrev'], x['pos'], x['pa'], x['ab'], x['run'], x['hit'], x['rbi'], + # x['double'], x['triple'], x['hr'], x['bb'], x['so'], x['hbp'], x['sac'], x['ibb'], x['gidp'], + # x['sb'], x['cs'], x['xch'], x['xhit'], x['error'], x['pb'], x['sbc'], x['csc'], x['week'], + # x['game'], f'{x["week"]}.{x["game"]}' + # ]) + # await patch_current(bstatcount=len(batting_stats)) + # await send_to_channel(self.bot, channel, f'Sending {len(batting_stats)} batting lines...') + # sheets.open_by_key(SBA_STATS_KEY).worksheet_by_title('Batting Data').update_values( + # crange='A2', + # values=batting_stats + # ) + # await send_to_channel(self.bot, channel, f'Batting stats have been sent') + # elif which == 'all' or which == 'batting': + # await send_to_channel(self.bot, channel, 'No batting stats found') + # + # if p_stats: + # await send_to_channel(self.bot, channel, f'Preparing pitching stats ({len(p_stats)} lines found)...') + # pitching_stats = [] + # + # for x in [*p_stats.values()]: + # pitching_stats.append([ + # x['player']['name'], x['team']['abbrev'], x['ip'], x['hit'], x['run'], x['erun'], x['so'], x['bb'], + # x['hbp'], x['wp'], x['balk'], x['hr'], 1 if x['gs'] else 0, 1 if x['win'] else 0, + # 1 if x['loss'] else 0, 1 if x['hold'] else 0, 1 if x['sv'] else 0, 1 if x['bsv'] else 0, x['week'], + # x['game'], f'{x["week"]}.{x["game"]}' + # ]) + # await patch_current(pstatcount=len(pitching_stats)) + # await send_to_channel(self.bot, channel, f'Sending {len(pitching_stats)} pitching lines...') + # sheets.open_by_key(SBA_STATS_KEY).worksheet_by_title('Pitching Data').update_values( + # crange='A2', + # values=pitching_stats + # ) + # await send_to_channel(self.bot, channel, f'Pitching stats have been sent') + # elif which == 'all' or which == 'pitching': + # await send_to_channel(self.bot, channel, 'No pitching stats found') - if which == 'all' or which == 'batting': - await send_to_channel(self.bot, channel, 'Collecting batting stats...') - b_stats = await get_battingstat(current['season'], timeout=90) - - if which == 'all' or which == 'pitching': - await send_to_channel(self.bot, channel, 'Collecting pitching stats...') - p_stats = await get_pitchingstat(current['season'], timeout=90) - - sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') - if b_stats: - await send_to_channel(self.bot, channel, f'Preparing batting stats ({len(b_stats)} lines found)...') - batting_stats = [] - - for x in [*b_stats.values()]: - batting_stats.append([ - x['player']['name'], x['team']['abbrev'], x['pos'], x['pa'], x['ab'], x['run'], x['hit'], x['rbi'], - x['double'], x['triple'], x['hr'], x['bb'], x['so'], x['hbp'], x['sac'], x['ibb'], x['gidp'], - x['sb'], x['cs'], x['xch'], x['xhit'], x['error'], x['pb'], x['sbc'], x['csc'], x['week'], - x['game'], f'{x["week"]}.{x["game"]}' - ]) - await patch_current(bstatcount=len(batting_stats)) - await send_to_channel(self.bot, channel, f'Sending {len(batting_stats)} batting lines...') - sheets.open_by_key(SBA_STATS_KEY).worksheet_by_title('Batting Data').update_values( - crange='A2', - values=batting_stats - ) - await send_to_channel(self.bot, channel, f'Batting stats have been sent') - elif which == 'all' or which == 'batting': - await send_to_channel(self.bot, channel, 'No batting stats found') - - if p_stats: - await send_to_channel(self.bot, channel, f'Preparing pitching stats ({len(p_stats)} lines found)...') - pitching_stats = [] - - for x in [*p_stats.values()]: - pitching_stats.append([ - x['player']['name'], x['team']['abbrev'], x['ip'], x['hit'], x['run'], x['erun'], x['so'], x['bb'], - x['hbp'], x['wp'], x['balk'], x['hr'], 1 if x['gs'] else 0, 1 if x['win'] else 0, - 1 if x['loss'] else 0, 1 if x['hold'] else 0, 1 if x['sv'] else 0, 1 if x['bsv'] else 0, x['week'], - x['game'], f'{x["week"]}.{x["game"]}' - ]) - await patch_current(pstatcount=len(pitching_stats)) - await send_to_channel(self.bot, channel, f'Sending {len(pitching_stats)} pitching lines...') - sheets.open_by_key(SBA_STATS_KEY).worksheet_by_title('Pitching Data').update_values( - crange='A2', - values=pitching_stats - ) - await send_to_channel(self.bot, channel, f'Pitching stats have been sent') - elif which == 'all' or which == 'pitching': - await send_to_channel(self.bot, channel, 'No pitching stats found') - - async def update_roster_sheet(self, season): - logging.info(f'calling the db') - # csv_data = db_get('players', api_ver=3, params=[('season', 6), ('csv', True)], as_csv=True) - # csv = DataFrame(csv_data).to_csv(header=False, index=False) - # csv = pandas.read_csv(csv_data) - - ap = await db_get('players', api_ver=3, timeout=8, params=[('season', season)]) - player_data = [ - ['name', 'sWAR', 'image', 'vanity_card', 'team_abbrev', 'inj_rat', 'pos_1', 'pos_2', 'pos_3', 'pos_4', - 'pos_5', 'pos_6', 'pos_7', 'pos_8', 'last_game', 'last_game2', 'il_return', 'dem_week', 'strat_code', - 'bbref_id'] - ] - for x in ap: - player_data.append([ - ap[x]['name'], ap[x]['wara'], ap[x]['image'], ap[x]['vanity_card'], ap[x]['team']['abbrev'], - ap[x]['injury_rating'], ap[x]['pos_1'], ap[x]['pos_2'], ap[x]['pos_3'], ap[x]['pos_4'], ap[x]['pos_5'], - ap[x]['pos_6'], ap[x]['pos_7'], ap[x]['pos_8'], ap[x]['last_game'], ap[x]['last_game2'], - ap[x]['il_return'], ap[x]['demotion_week'], ap[x]['strat_code'], ap[x]['bbref_id'] - ]) - # logging.info(f'\n\nCSV:\n{player_data}\n') - # auth sheets - logging.info(f'authorizing sheets') - sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json', retries=1) - # get sheet - logging.info(f'getting sheet') - master_sheet = sheets.open_by_key(SBA_ROSTER_KEY) - # get worksheet - logging.info(f'getting worksheet') - roster_sheet = master_sheet.worksheet_by_title('API Import') - - logging.info(f'updating values') - roster_sheet.update_values( - crange='A1', - values=player_data - ) + # async def update_roster_sheet(self, season): + # logging.info(f'calling the db') + # # csv_data = db_get('players', api_ver=3, params=[('season', 6), ('csv', True)], as_csv=True) + # # csv = DataFrame(csv_data).to_csv(header=False, index=False) + # # csv = pandas.read_csv(csv_data) + # + # ap = await db_get('players', api_ver=3, timeout=8, params=[('season', season)]) + # player_data = [ + # ['name', 'sWAR', 'image', 'vanity_card', 'team_abbrev', 'inj_rat', 'pos_1', 'pos_2', 'pos_3', 'pos_4', + # 'pos_5', 'pos_6', 'pos_7', 'pos_8', 'last_game', 'last_game2', 'il_return', 'dem_week', 'strat_code', + # 'bbref_id'] + # ] + # for x in ap: + # player_data.append([ + # ap[x]['name'], ap[x]['wara'], ap[x]['image'], ap[x]['vanity_card'], ap[x]['team']['abbrev'], + # ap[x]['injury_rating'], ap[x]['pos_1'], ap[x]['pos_2'], ap[x]['pos_3'], ap[x]['pos_4'], ap[x]['pos_5'], + # ap[x]['pos_6'], ap[x]['pos_7'], ap[x]['pos_8'], ap[x]['last_game'], ap[x]['last_game2'], + # ap[x]['il_return'], ap[x]['demotion_week'], ap[x]['strat_code'], ap[x]['bbref_id'] + # ]) + # # logging.info(f'\n\nCSV:\n{player_data}\n') + # # auth sheets + # logging.info(f'authorizing sheets') + # sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json', retries=1) + # # get sheet + # logging.info(f'getting sheet') + # master_sheet = sheets.open_by_key(SBA_ROSTER_KEY) + # # get worksheet + # logging.info(f'getting worksheet') + # roster_sheet = master_sheet.worksheet_by_title('API Import') + # + # logging.info(f'updating values') + # roster_sheet.update_values( + # crange='A1', + # values=player_data + # ) @staticmethod def on_team_il(team, player): @@ -644,7 +703,6 @@ class Transactions(commands.Cog): async def run_transactions_helper_command(self, ctx): current = await db_get('current') await self.run_transactions(current) - await self.update_roster_sheet(current['season']) await ctx.send(new_rand_conf_gif()) @commands.command(name='process_freeze') @@ -652,7 +710,6 @@ class Transactions(commands.Cog): async def process_freeze_helper_command(self, ctx): current = await db_get('current') await self.process_freeze_moves(current) - await self.update_roster_sheet(current['season']) await ctx.send(random_conf_gif()) @commands.command(name='trade', help='Trade players') @@ -733,7 +790,7 @@ class Transactions(commands.Cog): return else: try: - next_team = await get_one_team(resp) + next_team = await get_team_by_abbrev(resp, current['season']) except ValueError: await trade.send('Who the fuck even is that? Try again.') else: @@ -764,7 +821,8 @@ class Transactions(commands.Cog): pass else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, trade.channel, self.bot, resp, player_cog.player_list.keys()) ) except ValueError: @@ -792,7 +850,7 @@ class Transactions(commands.Cog): await trade.timed_delete() else: try: - dest_team = await get_one_team(resp) + dest_team = await get_team_by_abbrev(resp, current['season']) except ValueError: await trade.send(f'{await get_emoji(ctx, "facepalm")} They aren\'t even part of ' f'this trade. Come on.') @@ -916,7 +974,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, trade.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -936,7 +995,7 @@ class Transactions(commands.Cog): # await trade.send(f'Oof. {player["name"]} cannot be dropped until week ' # f'{player["demotion_week"]}.') else: - dest_team = await get_one_team('FA') + dest_team = await get_team_by_abbrev('FA', current['season']) await trade.add_player(player, dest_team) await trade.show_moves() @@ -1000,237 +1059,241 @@ class Transactions(commands.Cog): logging.error(f'Couldn\'t ping chaos for a trade') await trade.timed_delete() - @commands.command(name='picktrade', help='Trade draft picks', hidden=True) - @commands.is_owner() - async def pick_trade_command(self, ctx): - current = await db_get('current') - - if current['week'] < -2: - await ctx.send(await get_emoji(ctx, 'oof', False)) - await ctx.send(f'Patience, grasshopper. Trades open up Monday.') - return - if not OFFSEASON_FLAG: - await ctx.send(await get_emoji(ctx, 'oof', False)) - await ctx.send(f'You\'ll have to wait, hoss. No pick trades until the offseason.') - return - - team = await get_team_by_owner(current['season'], ctx.author.id) - team_role = get_team_role(ctx, team) - player_cog = self.bot.get_cog('Players') - - # Create trade channel - overwrites = {ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False), - team_role: discord.PermissionOverwrite(read_messages=True), - ctx.guild.me: discord.PermissionOverwrite(read_messages=True)} - - try: - # t_channel = await ctx.guild.create_text_channel( - # f'{team["abbrev"]}-trade', - # overwrites=overwrites, - # category=discord.utils.get(ctx.guild.categories, name=f'Transactions') - # ) - t_channel = await create_channel( - ctx, - channel_name=f'{team["abbrev"]}-trade', - category_name=f'Transactions', - everyone_read=False, - read_send_roles=team_role - ) - except Exception as e: - await ctx.send(f'{e}\n\n' - f'Discord is having issues creating private channels right now. Please try again later.') - return - - # Create trade and post to channel - trade = SBaTransaction(t_channel, current, 'trade', first_team=team, team_role=team_role) - await trade.send(f'Let\'s start here, {team_role.mention}.') - await ctx.send(f'Take my hand... {trade.channel.mention}') - intro = await trade.send( - 'Alrighty, let\'s collect the pick trades. Once they are all entered, each of the teams involved ' - 'will need to confirm the trade.' - ) - await intro.pin() - - # Add teams loop - while True: - prompt = 'Are you adding a team to this deal? (Yes/No)' - this_q = Question(self.bot, trade.channel, prompt, 'yesno', 30) - resp = await this_q.ask(trade.get_gms(self.bot)) - - if resp is None: - await trade.send('RIP this move. Maybe next time.') - await trade.timed_delete() - return - elif not resp: - break - else: - this_q.prompt = 'Please enter the team\'s abbreviation.' - this_q.qtype = 'text' - resp = await this_q.ask(trade.get_gms(self.bot)) - - if not resp: - await trade.send('RIP this move. Maybe next time.') - await trade.timed_delete() - return - else: - try: - next_team = await get_one_team(resp) - except ValueError: - await trade.send('Who the fuck even is that? Try again.') - else: - next_team_role = get_team_role(ctx, next_team) - overwrites[next_team_role] = discord.PermissionOverwrite(read_messages=True) - await trade.channel.edit(overwrites=overwrites) - trade.add_team(next_team, next_team_role) - await trade.send(f'Welcome to the trade, {next_team_role.mention}!') - - # Get pick trades - while True: - prompt = f'Are you trading any draft picks?' - this_q = Question(self.bot, trade.channel, prompt, 'yesno', 300) - resp = await this_q.ask(trade.get_gms(self.bot)) - effective_season = current['season'] if OFFSEASON_FLAG else current['season'] + 1 - team_season = current['season'] - - if resp is None: - await trade.send('RIP this move. Maybe next time.') - await trade.timed_delete() - return - elif not resp: - break - else: - # Get first pick - this_q.prompt = 'Enter the overall pick number being traded.' - this_q.qtype = 'int' - resp = await this_q.ask(trade.get_gms(self.bot)) - - if not resp: - await trade.send('RIP this move. Maybe next time.') - await trade.timed_delete() - return - else: - try: - first_pick = await get_one_draftpick_byoverall( - effective_season, - overall=resp - ) - except Exception as e: - await trade.send(f'Frick, I couldn\'t find pick #{resp}.') - else: - this_q.prompt = 'Now enter the return pick\'s overall pick number.' - resp = await this_q.ask(trade.get_gms(self.bot)) - - if not resp: - await trade.send('RIP this move. Maybe next time.') - await trade.timed_delete() - return - else: - try: - second_pick = await get_one_draftpick_byoverall( - effective_season, - overall=resp - ) - except Exception as e: - await trade.send(f'Frick, I couldn\'t find pick #{resp}.') - else: - team_getting_first_pick = second_pick['owner'] - team_getting_second_pick = first_pick['owner'] - - if not trade.included_team(first_pick['owner']): - await trade.send( - f'Ope. **{first_pick["owner"]["abbrev"]}** currently holds ' - f'{first_pick["origowner"]["abbrev"]} {first_pick["round"]} and are not part ' - f'of this deal so let\'s try this again.' - ) - else: - if not trade.included_team(second_pick['owner']): - await trade.send( - f'Imma let you finish, but **{second_pick["owner"]["abbrev"]}** currently ' - f'holds {second_pick["origowner"]["abbrev"]} {second_pick["round"]} and ' - f'are not part of this deal so let\'s try this again.' - ) - else: - await trade.add_pick(first_pick, team_getting_first_pick) - await trade.add_pick(second_pick, team_getting_second_pick) - - await trade.show_moves() - - # Check for empty move - if len(trade.players) + len(trade.picks) == 0: - await trade.send(f'This has been fun. Come again and maybe do something next time.') - await trade.timed_delete() - return - - # Check legality for all teams - errors = [] - for team in trade.teams: - data = await trade.check_major_league_errors(team) - logging.warning(f'Done checking data - checking WARa now ({data["wara"]}') - - if data['wara'] > 38.001: - errors.append(f'- {trade.teams[team]["team"]["abbrev"]} would have {data["wara"]:.2f} WARa') - - logging.warning(f'Now checking roster {len(data["roster"])}') - if len(data['roster']) > 26: - errors.append(f'- {trade.teams[team]["team"]["abbrev"]} would have {len(data["roster"])} players') - - logging.warning(f'Any errors? {errors}') - if data['wara'] > 38.001 or len(data['roster']) > 26: - roster_string = '' - for x in data['roster']: - roster_string += f'{data["roster"][x]["wara"]: >5} - {data["roster"][x]["name"]}\n' - errors.append(f'- This is the roster I have for {trade.teams[team]["team"]["abbrev"]}:\n' - f'```\n{roster_string}```') - - if len(errors) > 0: - error_message = '\n'.join(errors) - await trade.send(f'Yikes. I\'m gonna put the kibosh on this trade. Below is why:\n\n{error_message}') - await trade.timed_delete() - return - - # Ask for each team's explict confirmation - for team in trade.teams: - this_q.prompt = f'{trade.teams[team]["role"].mention}\nDo you accept this trade?' - this_q.qtype = 'yesno' - resp = await this_q.ask(trade.get_gms(self.bot, team)) - - if not resp: - await trade.send('RIP this move. Maybe next time.') - await trade.timed_delete() - return - else: - await trade.show_moves() - - # Run moves - trans_id = await trade.send_transaction() - - await send_to_channel(self.bot, 'sba-network-news', embed=await trade.show_moves(here=False)) - await self.send_move_to_sheets(trans_id) - - await trade.send(f'All done! Your transaction id is: {trans_id}') - try: - choas = get_role(ctx, 'CHOAS ALERT') - await send_to_channel(self.bot, f'season-{current["season"]}-chat', f'{choas.mention}') - except Exception as e: - logging.error('I was not able to ping CHOAS ALERT') - await trade.timed_delete() + # @commands.command(name='picktrade', help='Trade draft picks', hidden=True) + # @commands.is_owner() + # async def pick_trade_command(self, ctx): + # current = await db_get('current') + # + # if current['week'] < -2: + # await ctx.send(await get_emoji(ctx, 'oof', False)) + # await ctx.send(f'Patience, grasshopper. Trades open up Monday.') + # return + # if not OFFSEASON_FLAG: + # await ctx.send(await get_emoji(ctx, 'oof', False)) + # await ctx.send(f'You\'ll have to wait, hoss. No pick trades until the offseason.') + # return + # + # team = await get_team_by_owner(current['season'], ctx.author.id) + # team_role = get_team_role(ctx, team) + # player_cog = self.bot.get_cog('Players') + # + # # Create trade channel + # overwrites = {ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False), + # team_role: discord.PermissionOverwrite(read_messages=True), + # ctx.guild.me: discord.PermissionOverwrite(read_messages=True)} + # + # try: + # # t_channel = await ctx.guild.create_text_channel( + # # f'{team["abbrev"]}-trade', + # # overwrites=overwrites, + # # category=discord.utils.get(ctx.guild.categories, name=f'Transactions') + # # ) + # t_channel = await create_channel( + # ctx, + # channel_name=f'{team["abbrev"]}-trade', + # category_name=f'Transactions', + # everyone_read=False, + # read_send_roles=team_role + # ) + # except Exception as e: + # await ctx.send(f'{e}\n\n' + # f'Discord is having issues creating private channels right now. Please try again later.') + # return + # + # # Create trade and post to channel + # trade = SBaTransaction(t_channel, current, 'trade', first_team=team, team_role=team_role) + # await trade.send(f'Let\'s start here, {team_role.mention}.') + # await ctx.send(f'Take my hand... {trade.channel.mention}') + # intro = await trade.send( + # 'Alrighty, let\'s collect the pick trades. Once they are all entered, each of the teams involved ' + # 'will need to confirm the trade.' + # ) + # await intro.pin() + # + # # Add teams loop + # while True: + # prompt = 'Are you adding a team to this deal? (Yes/No)' + # this_q = Question(self.bot, trade.channel, prompt, 'yesno', 30) + # resp = await this_q.ask(trade.get_gms(self.bot)) + # + # if resp is None: + # await trade.send('RIP this move. Maybe next time.') + # await trade.timed_delete() + # return + # elif not resp: + # break + # else: + # this_q.prompt = 'Please enter the team\'s abbreviation.' + # this_q.qtype = 'text' + # resp = await this_q.ask(trade.get_gms(self.bot)) + # + # if not resp: + # await trade.send('RIP this move. Maybe next time.') + # await trade.timed_delete() + # return + # else: + # try: + # next_team = await get_team_by_abbrev(resp, current['season']) + # except ValueError: + # await trade.send('Who the fuck even is that? Try again.') + # else: + # next_team_role = get_team_role(ctx, next_team) + # overwrites[next_team_role] = discord.PermissionOverwrite(read_messages=True) + # await trade.channel.edit(overwrites=overwrites) + # trade.add_team(next_team, next_team_role) + # await trade.send(f'Welcome to the trade, {next_team_role.mention}!') + # + # # Get pick trades + # while True: + # prompt = f'Are you trading any draft picks?' + # this_q = Question(self.bot, trade.channel, prompt, 'yesno', 300) + # resp = await this_q.ask(trade.get_gms(self.bot)) + # effective_season = current['season'] if OFFSEASON_FLAG else current['season'] + 1 + # team_season = current['season'] + # + # if resp is None: + # await trade.send('RIP this move. Maybe next time.') + # await trade.timed_delete() + # return + # elif not resp: + # break + # else: + # # Get first pick + # this_q.prompt = 'Enter the overall pick number being traded.' + # this_q.qtype = 'int' + # resp = await this_q.ask(trade.get_gms(self.bot)) + # + # if not resp: + # await trade.send('RIP this move. Maybe next time.') + # await trade.timed_delete() + # return + # else: + # try: + # first_pick = await get_one_draftpick_byoverall( + # effective_season, + # overall=resp + # ) + # except Exception as e: + # await trade.send(f'Frick, I couldn\'t find pick #{resp}.') + # else: + # this_q.prompt = 'Now enter the return pick\'s overall pick number.' + # resp = await this_q.ask(trade.get_gms(self.bot)) + # + # if not resp: + # await trade.send('RIP this move. Maybe next time.') + # await trade.timed_delete() + # return + # else: + # try: + # second_pick = await get_one_draftpick_byoverall( + # effective_season, + # overall=resp + # ) + # except Exception as e: + # await trade.send(f'Frick, I couldn\'t find pick #{resp}.') + # else: + # team_getting_first_pick = second_pick['owner'] + # team_getting_second_pick = first_pick['owner'] + # + # if not trade.included_team(first_pick['owner']): + # await trade.send( + # f'Ope. **{first_pick["owner"]["abbrev"]}** currently holds ' + # f'{first_pick["origowner"]["abbrev"]} {first_pick["round"]} and are not part ' + # f'of this deal so let\'s try this again.' + # ) + # else: + # if not trade.included_team(second_pick['owner']): + # await trade.send( + # f'Imma let you finish, but **{second_pick["owner"]["abbrev"]}** currently ' + # f'holds {second_pick["origowner"]["abbrev"]} {second_pick["round"]} and ' + # f'are not part of this deal so let\'s try this again.' + # ) + # else: + # await trade.add_pick(first_pick, team_getting_first_pick) + # await trade.add_pick(second_pick, team_getting_second_pick) + # + # await trade.show_moves() + # + # # Check for empty move + # if len(trade.players) + len(trade.picks) == 0: + # await trade.send(f'This has been fun. Come again and maybe do something next time.') + # await trade.timed_delete() + # return + # + # # Check legality for all teams + # errors = [] + # for team in trade.teams: + # data = await trade.check_major_league_errors(team) + # logging.warning(f'Done checking data - checking WARa now ({data["wara"]}') + # + # if data['wara'] > 38.001: + # errors.append(f'- {trade.teams[team]["team"]["abbrev"]} would have {data["wara"]:.2f} WARa') + # + # logging.warning(f'Now checking roster {len(data["roster"])}') + # if len(data['roster']) > 26: + # errors.append(f'- {trade.teams[team]["team"]["abbrev"]} would have {len(data["roster"])} players') + # + # logging.warning(f'Any errors? {errors}') + # if data['wara'] > 38.001 or len(data['roster']) > 26: + # roster_string = '' + # for x in data['roster']: + # roster_string += f'{data["roster"][x]["wara"]: >5} - {data["roster"][x]["name"]}\n' + # errors.append(f'- This is the roster I have for {trade.teams[team]["team"]["abbrev"]}:\n' + # f'```\n{roster_string}```') + # + # if len(errors) > 0: + # error_message = '\n'.join(errors) + # await trade.send(f'Yikes. I\'m gonna put the kibosh on this trade. Below is why:\n\n{error_message}') + # await trade.timed_delete() + # return + # + # # Ask for each team's explict confirmation + # for team in trade.teams: + # this_q.prompt = f'{trade.teams[team]["role"].mention}\nDo you accept this trade?' + # this_q.qtype = 'yesno' + # resp = await this_q.ask(trade.get_gms(self.bot, team)) + # + # if not resp: + # await trade.send('RIP this move. Maybe next time.') + # await trade.timed_delete() + # return + # else: + # await trade.show_moves() + # + # # Run moves + # trans_id = await trade.send_transaction() + # + # await send_to_channel(self.bot, 'sba-network-news', embed=await trade.show_moves(here=False)) + # await self.send_move_to_sheets(trans_id) + # + # await trade.send(f'All done! Your transaction id is: {trans_id}') + # try: + # choas = get_role(ctx, 'CHOAS ALERT') + # await send_to_channel(self.bot, f'season-{current["season"]}-chat', f'{choas.mention}') + # except Exception as e: + # logging.error('I was not able to ping CHOAS ALERT') + # await trade.timed_delete() @commands.command(name='dropadd', aliases=['drop', 'add', 'adddrop', 'longil'], help='FA/MiL moves') @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) async def drop_add_command(self, ctx): current = await db_get('current') team = await get_team_by_owner(current['season'], ctx.author.id) - team_schedule = await get_schedule( - current['season'], - team_abbrev1=team["abbrev"], - week_start=current['week'] + 1, - week_end=current['week'] + 1, - ) + # team_schedule = await get_schedule( + # current['season'], + # team_abbrev1=team["abbrev"], + # week_start=current['week'] + 1, + # week_end=current['week'] + 1, + # ) + s_query = await db_get('schedules', params=[ + ('season', current['season']), ('team_abbrev', team['abbrev']), ('week_start', current['week'] + 1), + ('week_end', current['week'] + 1) + ]) team_role = get_team_role(ctx, team) player_cog = self.bot.get_cog('Players') poke_role = get_role(ctx, 'Pokétwo') - if len(team_schedule) == 0 and not OFFSEASON_FLAG and current['week'] != 22: + if s_query['count'] == 0 and not OFFSEASON_FLAG and current['week'] != 22: await ctx.send('It looks like your season is over so transactions are locked.') return @@ -1281,7 +1344,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, dropadd.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -1294,8 +1358,8 @@ class Transactions(commands.Cog): f'{await get_emoji(ctx, "dead")} Let\'s try that again.' ) else: - fa_team = await get_one_team('FA') - dest_team = await get_one_team(f'{team["abbrev"]}MiL') + fa_team = await get_team_by_abbrev('FA', current['season']) + dest_team = await get_team_by_abbrev(f'{team["abbrev"]}MiL', current['season']) if not dropadd.included_team(player['team']) and player['team'] != fa_team: await t_channel.send(f'It looks like {player["name"]} is on {player["team"]["abbrev"]} ' f'so I can\'t let you do that.') @@ -1334,7 +1398,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, dropadd.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -1354,7 +1419,7 @@ class Transactions(commands.Cog): else: await dropadd.add_player(player, team) else: - fa_team = await get_one_team('FA') + fa_team = await get_team_by_abbrev('FA', current['season']) if player['team'] != fa_team and not self.on_team_il(team, player): await t_channel.send(f'It looks like {player["name"]} is on {player["team"]["abbrev"]} ' f'so I can\'t let you do that.') @@ -1394,7 +1459,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, dropadd.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -1416,7 +1482,7 @@ class Transactions(commands.Cog): await dropadd.send(f'Oof. {player["name"]} cannot be dropped until week ' f'{player["demotion_week"]}.') else: - dest_team = await get_one_team('FA') + dest_team = await get_team_by_abbrev('FA', current['season']) await dropadd.add_player(player, dest_team) await dropadd.show_moves() @@ -1493,6 +1559,14 @@ class Transactions(commands.Cog): return team = await get_team_by_owner(current['season'], ctx.author.id) + s_query = await db_get('schedules', params=[ + ('season', current['season']), ('team_abbrev', team['abbrev']), ('week_start', current['week'] + 1), + ('week_end', current['week'] + 1) + ]) + if s_query['count'] == 0 and current['week'] != 22: + await ctx.send('It looks like your season is over so transactions are locked.') + return + team_role = get_team_role(ctx, team) player_cog = self.bot.get_cog('Players') poke_role = get_role(ctx, 'Pokétwo') @@ -1542,7 +1616,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, dropadd.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -1559,7 +1634,7 @@ class Transactions(commands.Cog): await t_channel.send(f'It looks like {player["name"]} is on {player["team"]["abbrev"]} ' f'so I can\'t let you do that.') else: - dest_team = await get_one_team(f'{team["abbrev"]}IL') + dest_team = await get_team_by_abbrev(f'{team["abbrev"]}IL', current['season']) await dropadd.add_player(player, dest_team) await dropadd.show_moves() @@ -1587,7 +1662,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, dropadd.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -1631,7 +1707,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, dropadd.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -1651,7 +1728,7 @@ class Transactions(commands.Cog): # await dropadd.send(f'Oof. {player["name"]} cannot be dropped until week ' # f'{player["demotion_week"]}.') else: - dest_team = await get_one_team(f'{team["abbrev"]}MiL') + dest_team = await get_team_by_abbrev(f'{team["abbrev"]}MiL', current['season']) await dropadd.add_player(player, dest_team) await dropadd.show_moves() @@ -1679,7 +1756,8 @@ class Transactions(commands.Cog): return else: try: - player = await get_one_player( + player = await get_player_by_name( + current['season'], await fuzzy_player_search(ctx, dropadd.channel, self.bot, resp, player_cog.player_list.keys()) ) @@ -1699,7 +1777,7 @@ class Transactions(commands.Cog): # await dropadd.send(f'Oof. {player["name"]} cannot be dropped until week ' # f'{player["demotion_week"]}.') else: - dest_team = await get_one_team('FA') + dest_team = await get_team_by_abbrev('FA', current['season']) await dropadd.add_player(player, dest_team) await dropadd.show_moves() @@ -1762,7 +1840,6 @@ class Transactions(commands.Cog): ) await send_to_channel(self.bot, 'transaction-log', embed=await dropadd.show_moves(here=False)) - await self.update_roster_sheet(current['season']) await dropadd.send(f'All done! Your transaction id is: {trans_id}') await dropadd.timed_delete() @@ -1772,19 +1849,29 @@ class Transactions(commands.Cog): async def my_moves_command(self, ctx): current = await db_get('current') team = await get_team_by_owner(current['season'], ctx.author.id) - set_moves = await get_transactions( - current['season'], - team_abbrev=team['abbrev'], - week_start=current['week']+1, - week_end=current['week']+1 - ) - frozen_moves = await get_transactions( - current['season'], - team_abbrev=team['abbrev'], - week_start=current['week']+1, - week_end=current['week']+1, - frozen=True - ) + # set_moves = await get_transactions( + # current['season'], + # team_abbrev=team['abbrev'], + # week_start=current['week']+1, + # week_end=current['week']+1 + # ) + t_query = await db_get('transactions', params=[ + ('season', current['season']), ('week_start', current['week']), + ('week_end', current['season']), ('team_abbrev', team['abbrev']) + ]) + set_moves = t_query['transactions'] + # frozen_moves = await get_transactions( + # current['season'], + # team_abbrev=team['abbrev'], + # week_start=current['week']+1, + # week_end=current['week']+1, + # frozen=True + # ) + t_query = await db_get('transactions', params=[ + ('season', current['season']), ('week_start', current['week']), + ('week_end', current['season']), ('team_abbrev', team['abbrev']), ('frozen', True) + ]) + frozen_moves = t_query['transactions'] logging.info(f'Num Moves: {len(set_moves)}') embed = get_team_embed(f'{team["lname"]} Guaranteed Transactions', team=team) @@ -1793,21 +1880,21 @@ class Transactions(commands.Cog): frozen = {} for x in set_moves: - if set_moves[x]["moveid"] not in guaranteed.keys(): - guaranteed[set_moves[x]["moveid"]] = [] + if x["moveid"] not in guaranteed.keys(): + guaranteed[x["moveid"]] = [] - guaranteed[set_moves[x]["moveid"]].append( - f'**{set_moves[x]["player"]["name"]}** ({set_moves[x]["player"]["wara"]}) from ' - f'{set_moves[x]["oldteam"]["abbrev"]} to {set_moves[x]["newteam"]["abbrev"]}\n' + guaranteed[x["moveid"]].append( + f'**{x["player"]["name"]}** ({x["player"]["wara"]}) from ' + f'{x["oldteam"]["abbrev"]} to {x["newteam"]["abbrev"]}\n' ) for x in frozen_moves: - if frozen_moves[x]["moveid"] not in frozen.keys(): + if x["moveid"] not in frozen.keys(): frozen[frozen_moves[x]["moveid"]] = [] - frozen[frozen_moves[x]["moveid"]].append( - f'**{frozen_moves[x]["player"]["name"]}** ({frozen_moves[x]["player"]["wara"]}) from ' - f'{frozen_moves[x]["oldteam"]["abbrev"]} to {frozen_moves[x]["newteam"]["abbrev"]}\n' + frozen[x["moveid"]].append( + f'**{x["player"]["name"]}** ({x["player"]["wara"]}) from ' + f'{x["oldteam"]["abbrev"]} to {x["newteam"]["abbrev"]}\n' ) if len(guaranteed) > 0: @@ -1825,15 +1912,17 @@ class Transactions(commands.Cog): @commands.command(name='legal', help='Check roster legality') @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) - async def legal_command(self, ctx, *team_abbrev): + async def legal_command(self, ctx, team_abbrev: str): current = await db_get('current') if team_abbrev: - this_team = await get_one_team(team_abbrev[0]) + this_team = await get_team_by_abbrev(team_abbrev, current['season']) else: this_team = await get_team_by_owner(current['season'], ctx.author.id) - this_week_team = await get_team_roster(this_team, 'current') - next_week_team = await get_team_roster(this_team, 'next') + # this_week_team = await get_team_roster(this_team, 'current') + # next_week_team = await get_team_roster(this_team, 'next') + this_week_team = await db_get(f'teams/{this_team["id"]}/roster/current') + next_week_team = await db_get(f'teams/{this_team["id"]}/roster/next') count = 0 all_players = [] @@ -1887,67 +1976,12 @@ class Transactions(commands.Cog): await ctx.send(content=None, embed=embed) count += 1 - @commands.command(name='import', hidden=True) - @commands.is_owner() - async def import_command(self, ctx, sheet_id, tab_name, test=False): - # Get data from Sheets - async with ctx.typing(): - sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') - try: - data_sheet = sheets.open_by_key(sheet_id).worksheet_by_title(tab_name) - if test: - raw_data = data_sheet.get_values('A2', 'C5') - else: - raw_data = data_sheet.get_values('A2', 'C1100') - except Exception as e: - logging.error(f'{e}') - await ctx.send(f'Yikes. I need a grown-up to read this. I don\'t know what it means:\n\n{e}') - return - else: - await ctx.send(f'Noice - got it! Give me a minute to go through this data...') - - error_players = [] - tba_players = [] - fa_team = await get_one_team('FA', 5) - - async with ctx.typing(): - for row in raw_data: - if row[0] != '': - name = row[0] - swar = row[2] - - try: - old_player = await get_one_player(name) - except ValueError: - error_players.append(name) - else: - new_player = copy.deepcopy(old_player) - new_player['wara'] = swar - new_player['season'] = 5 - new_player['team_id'] = fa_team['id'] - del new_player['il_return'] - del new_player['demotion_week'] - del new_player['last_game'] - del new_player['last_game2'] - tba_players.append(new_player) - - await ctx.send(f'Okay, just read through that sheet. I\'ve got {len(tba_players)} players to add and have ' - f'the following errors: {", ".join(error_players)}') - - logging.info(f'tba_players:\n{tba_players}') - - if len(tba_players) > 0: - async with ctx.typing(): - done = await post_players(tba_players) - if done: - await ctx.send('All done!') - @commands.command(name='tomil', help='Post-draft demotions') @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) async def to_mil_command(self, ctx, *player_list): current = await db_get('current') team = await get_team_by_owner(current['season'], owner_id=ctx.author.id) - il_team = await get_one_team(f'{team["abbrev"]}MiL') + il_team = await get_team_by_abbrev(f'{team["abbrev"]}MiL', current['season']) if current['week'] != 0: logging.info('entering the thot check') @@ -1979,7 +2013,7 @@ class Transactions(commands.Cog): try: player_name = await fuzzy_player_search(ctx, ctx.channel, self.bot, x, player_cog.player_list.keys()) - player = await get_one_player(player_name) + player = await get_player_by_name(current['season'], player_name) except Exception as e: logging.error(f'Could not demote {x} for {team["abbrev"]}: {e}') errors.append(x) @@ -2002,7 +2036,7 @@ class Transactions(commands.Cog): await react_and_reply(ctx, '🖕', 'Thanks for that. So much fun.') return - await post_transactions(moves) + await db_post('transactions', payload={'count': len(moves), 'moves': moves}) embed = get_team_embed(f'Pre-Season Demotions', team) embed.add_field(name='Demotions', value=output_string, inline=False) await send_to_channel(self.bot, 'transaction-log', content=None, embed=embed) @@ -2030,14 +2064,6 @@ class Transactions(commands.Cog): f'{e}\n\nLooks like you didn\'t apologize hard enough. I can\'t role you back up.') await react_and_reply(ctx, '💖', 'You are too kind.') - @commands.command(name='force_roster', help='Mod: Force update roster sheet') - async def force_roster_command(self, ctx): - current = await db_get('current') - message = await ctx.send('On it...') - fake_move = SBaTransaction(ctx.channel, current, 'dropadd') - await self.update_roster_sheet(season=current['season']) - await message.edit(content=new_rand_conf_gif()) - async def setup(bot): await bot.add_cog(Transactions(bot))