diff --git a/cogs/players.py b/cogs/players.py index 88de1aa..7f3f050 100644 --- a/cogs/players.py +++ b/cogs/players.py @@ -10,7 +10,8 @@ from discord.app_commands import Choice from db_calls_gameplay import get_one_game from helpers import * -from db_calls import * +from db_calls import db_get, db_patch, db_post, db_delete, get_team_by_abbrev, get_team_by_owner, patch_player, \ + get_player_by_name from typing import Literal @@ -89,24 +90,32 @@ class Players(commands.Cog): self.build_master_player_list.start() - async def cog_command_error(self, ctx, error): - await ctx.send(f'{error}\n\nRun !help to see the command requirements') + # async def cog_command_error(self, ctx, error): + # await ctx.send(f'{error}\n\nRun !help to see the command requirements') - async def slash_error(self, ctx, error): - await ctx.send(f'{error}') + # async def slash_error(self, ctx, error): + # await ctx.send(f'{error}') + + # @commands.Cog.listener() + # async def on_app_command_error(self, interaction, error): + # command = interaction.app_command + # ctx = interaction.context + # + # await ctx.send(f"An error occurred while executing the {command} command: {error}") async def get_dice_embed(self, channel, title, message): + team = None try: + current = await db_get('current') team_abbrev = re.split('-', channel.name) if len(team_abbrev[0]) <= 4 and team_abbrev not in ['the', 'city']: - team = await get_one_team(team_abbrev[0], timeout=1) - else: - team = None + tquery = await db_get('teams', params=[('season', current['season']), ('team_abbrev', team_abbrev[0])]) + if tquery['count'] > 0: + team = tquery['teams'][0] except (ValueError, AttributeError, requests.ReadTimeout) as e: logging.info(f'{type(e)}: {e}') - team = None - if team: + if team is not None: embed = discord.Embed( color=int(team["dice_color"], 16) if team["dice_color"] else int(team["color"], 16) ) @@ -130,18 +139,17 @@ class Players(commands.Cog): logging.info(f'build_master_player_list - guild: {guild}') logging.info(f'build_master_player_list - getting current') - current = await get_current() + current = await db_get('current') logging.info(f'build_master_player_list - getting all_players') - # all_players = await get_players(current['season']) - all_players = await db_get('players', api_ver=2, timeout=8, params=[('season', current['season'])]) + p_query = await db_get('players', timeout=8, params=[('season', current['season'])]) logging.info(f'build_master_player_list - building player_list') - self.player_list = {all_players[player]['name'].lower(): all_players[player]['id'] for player in all_players} + self.player_list = {x['name'].lower(): x['id'] for x in p_query['players']} logging.info(f'player list count: {len(self.player_list)}') logging.debug(f'player list: {self.player_list}') @staticmethod async def update_injuries(ctx): - current = await get_current() + current = await db_get('current') injury_log = discord.utils.get(ctx.guild.text_channels, name='injury-log') # Build new messages @@ -149,7 +157,9 @@ class Players(commands.Cog): # inj_by_week = {'Week 1': [Player Objs], 'Week 2': [Player Objs]} inj_team = {} inj_week = {} - all_injuries = await get_players(current['season'], injured=True) + all_injuries = await db_get('players', params=[ + ('season', current['season']), ('is_injured', True) + ]) for x in all_injuries: player = all_injuries[x] @@ -234,21 +244,18 @@ class Players(commands.Cog): @staticmethod async def game_progress(current): - this_week = await get_schedule( - current['season'], - week_start=current['week'], - week_end=current['week'] - ) - results_this_week = await get_results( - current['season'], - week=current['week'] - ) + s_query = await db_get('schedules', params=[ + ('season', current['season']), ('week_start', current['week']), ('week_end', current['week']) + ]) + r_query = await db_get('results', params=[ + ('season', current['season']), ('week_start', current['week']), ('week_end', current['week']) + ]) game_count = 0 - for x in this_week: - game_count += this_week[x]['gamecount'] + for x in s_query['schedules']: + game_count += x['gamecount'] - return {'games_played': len(results_this_week), 'game_count': game_count} + return {'games_played': r_query['count'], 'game_count': game_count} @commands.Cog.listener(name='on_message') async def on_message_listener(self, message): @@ -328,14 +335,14 @@ class Players(commands.Cog): # return embed @commands.command(name='team', aliases=['roster', 'myboys', 'mybois'], help='Get team overview') - async def team_command(self, ctx, *abbrev): - current = await get_current() + async def team_command(self, ctx, team_abbrev: str = None): + current = await db_get('current') # Get Team - if abbrev: - team = await get_one_team(abbrev[0]) + if team_abbrev is not None: + team = await get_team_by_abbrev(team_abbrev, current['season']) else: - team = await get_team_by_owner(current['season'], ctx.author.id) + team = await get_team_by_owner(season=current['season'], owner_id=ctx.author.id) # Create team embed embed = get_team_embed(f'{team["lname"]} Overview', team) @@ -343,8 +350,11 @@ class Players(commands.Cog): # Get standings if team['abbrev'][-2:].lower() != 'il': try: - team_standings = await get_standings(current['season'], team_abbrev=team['abbrev']) - if team_standings: + s_query = await db_get('standings', params=[ + ('season', current['season']), ('team_abbrev', team['abbrev']) + ]) + if s_query['count'] > 0: + team_standings = s_query['standings'][0] overview_string = f'Record: {team_standings["wins"]}-{team_standings["losses"]} ' \ f'({team_standings["run_diff"]} RD)\n' \ f'Pythag Record: {team_standings["pythag_wins"]}-{team_standings["pythag_losses"]}\n' @@ -370,14 +380,22 @@ class Players(commands.Cog): # Get player info il_players = None if team['abbrev'][-2:].lower() != 'il': - il_players = await get_players(current['season'], team_abbrev=f'{team["abbrev"]}IL', sort='wara-desc') - players = await get_players(current['season'], team_abbrev=team['abbrev'], sort='wara-desc') + il_team = await get_team_by_abbrev(team['abbrev'], current['season']) + p_query = await db_get('players', params=[ + ('season', current['season']), ('team_id', il_team['id']), ('sort', 'cost-desc') + ]) + il_players = p_query['players'] + + p_query = await db_get('players', params=[ + ('season', current['season']), ('team_id', team['id']), ('sort', 'cost-desc') + ]) + players = p_query['players'] il_wara = 0 active_wara = 0 if il_players: for x in il_players: - il_wara += il_players[x]['wara'] + il_wara += x['wara'] if players: count = 0 @@ -385,8 +403,8 @@ class Players(commands.Cog): for x in players: if count < 5: - top_player_string += f'{players[x]["pos_1"]} {players[x]["name"]} ({players[x]["wara"]:.2f})\n' - active_wara += players[x]['wara'] + top_player_string += f'{x["pos_1"]} {x["name"]} ({x["wara"]:.2f})\n' + active_wara += x['wara'] count += 1 embed.add_field(name='Core Players', value=top_player_string) @@ -394,46 +412,42 @@ class Players(commands.Cog): if il_wara > 0: embed.add_field(name='Injured sWAR', value=f'{il_wara:.2f}') - # Get near schedule - team_schedule = await get_schedule( - current['season'], - team_abbrev1=team["abbrev"], - week_start=current['week'], - week_end=current['week']+2 if current['week']+2 > 0 else 2, - ) - if team_schedule: + s_query = await db_get('schedules', params=[ + ('season', current['season']), ('team_abbrev', team['abbrev']), ('week_start', current['week']), + ('week_end', current['week']+2 if current['week']+2 > 0 else 2), ('short_output', False) + ]) + if s_query['count'] > 0: + team_schedule = s_query['schedules'] this_week_string = '' upcoming_string = '' - full_sched = dict(sorted(team_schedule.items(), key=lambda item: item[1]["id"])) + full_sched = sorted(team_schedule, key=lambda y: y['id']) + logging.info(f'full_sched: {full_sched}') for matchup in full_sched: - if full_sched[matchup]['hometeam'] == team: - opp_record = await get_standings( - season=current['season'], - team_abbrev=full_sched[matchup]['awayteam']['abbrev'] - ) - else: - opp_record = await get_standings( - season=current['season'], - team_abbrev=full_sched[matchup]['hometeam']['abbrev'] - ) - if full_sched[matchup]['week'] == current['week']: - if full_sched[matchup]['hometeam'] == team: + st_abbrev = matchup['awayteam']['abbrev'] + if matchup['hometeam'] == team: + st_abbrev = matchup['awayteam']['abbrev'] + + r_query = await db_get('standings', params=[('season', current['season']), ('team_abbrev', st_abbrev)]) + opp_record = None if r_query['count'] == 0 else r_query['standings'][0] + + if matchup['week'] == current['week']: + if matchup['hometeam'] == team: this_week_string += f'Week {current["week"]}: vs ' \ - f'{full_sched[matchup]["awayteam"]["lname"]} ' \ + f'{matchup["awayteam"]["lname"]} ' \ f'({opp_record["wins"]}-{opp_record["losses"]})\n' else: - this_week_string += f'Week {current["week"]}: @ {full_sched[matchup]["hometeam"]["lname"]} ' \ + this_week_string += f'Week {current["week"]}: @ {matchup["hometeam"]["lname"]} ' \ f'({opp_record["wins"]}-{opp_record["losses"]})\n' else: - if full_sched[matchup]['hometeam'] == team: - upcoming_string += f'Week {full_sched[matchup]["week"]}: vs ' \ - f'{full_sched[matchup]["awayteam"]["lname"]} ' \ + if matchup['hometeam'] == team: + upcoming_string += f'Week {matchup["week"]}: vs ' \ + f'{matchup["awayteam"]["lname"]} ' \ f'({opp_record["wins"]}-{opp_record["losses"]})\n' else: - upcoming_string += f'Week {full_sched[matchup]["week"]}: @ ' \ - f'{full_sched[matchup]["hometeam"]["lname"]} ' \ + upcoming_string += f'Week {matchup["week"]}: @ ' \ + f'{matchup["hometeam"]["lname"]} ' \ f'({opp_record["wins"]}-{opp_record["losses"]})\n' if len(this_week_string) > 0: @@ -452,7 +466,8 @@ class Players(commands.Cog): @commands.command(name='player', aliases=['card'], help='Get player overview') async def player_command(self, ctx, *, name): - current = await get_current() + current = await db_get('current') + season = current['season'] name_reg = re.compile(r'(s\d+)* *(.*)', re.IGNORECASE) player_search = name_reg.search(name) @@ -462,35 +477,41 @@ class Players(commands.Cog): # No season is included if not player_search.group(1): - player = await get_one_player( - await fuzzy_player_search(ctx, ctx.channel, self.bot, name, self.player_list.keys()) - ) + p_name = await fuzzy_player_search(ctx, ctx.channel, self.bot, name, self.player_list.keys()) + player = await db_get('players', object_id=self.player_list[p_name]) # Season is included else: season = int(player_search.group(1)[1:]) - try: - player = await get_one_player(player_search.group(2), season=season) - except Exception as e: - logging.error(e) + p_query = await db_get('players', params=[('season', season), ('name', player_search.group(2))]) + if p_query['count'] == 0: async with ctx.typing(): - all_players = await get_players(season) - all_player_names = {all_players[player]['name'].lower(): all_players[player]['id'] for player in all_players} - player = await get_one_player( - await fuzzy_player_search(ctx, ctx.channel, self.bot, player_search.group(2).strip(), all_player_names), - season=season - ) + p_query = await db_get('players', params=[('season', season), ('short_output', True)]) + if p_query['count'] == 0: + await ctx.send(f'I did not find any players in season {season}') + return - embed = await get_player_embed(player, current, ctx) + p_name = await fuzzy_player_search( + ctx, ctx.channel, self.bot, player_search.group(2).strip(), + [x['name'].lower() for x in p_query['players']] + ) + p_query2 = await db_get('players', params=[('season', season), ('name', p_name)]) + player = p_query2['players'][0] - await ctx.send(content=None, embed=embed) + embeds = [await get_player_embed(player, current, ctx, season)] if player['image2']: embed = get_team_embed(f'{player["name"]}', player["team"], thumbnail=False) embed.set_image(url=player['image2']) - await ctx.send(content=None, embed=embed) + embeds.append(embed) + + await ctx.send(content=None, embeds=embeds) @commands.command(name='career', help='Get player\'s career stats') async def career_command(self, ctx, *, name): + await ctx.send(f'That mother fucker Cal hasn\'t updated this command for the new API.') + await ctx.send(random_gif('god dammit')) + return + # Get BattingCareer b = await get_battingcareer(name) # Get PitchingCareer @@ -579,7 +600,11 @@ class Players(commands.Cog): @commands.command(name='schedule', help='This week and next') async def schedule_command(self, ctx, *week: int): - current = await get_current() + await ctx.send(f'That mother fucker Cal hasn\'t updated this command for the new API.') + await ctx.send(random_gif('this idiot')) + return + + current = await db_get('current') if week: schedule_week = week[0] @@ -702,14 +727,22 @@ class Players(commands.Cog): await ctx.send(content=None, embed=embed) @commands.command(name='weather', help='Roll ballpark weather') - async def weather_command(self, ctx, *team_abbrev: str): - current = await get_current() + async def weather_command(self, ctx, team_abbrev=None): + current = await db_get('current') - if team_abbrev: - team = await get_one_team(team_abbrev[0]) + if team_abbrev is not None: + t_query = await db_get('teams', params=[('season', current['season']), ('team_abbrev', team_abbrev)]) else: - team = await get_team_by_owner(current['season'], ctx.author.id) + t_query = await db_get('teams', params=[ + ('season', current['season']), ('team_abbrev', ctx.channel.name.split('-')[0]) + ]) + if t_query['count'] == 0: + t_query = await db_get('teams', params=[('season', current['season']), ('owner_id', ctx.author.id)]) + if t_query['count'] == 0: + await ctx.send(f'I could not find a weather chart for you.') + + team = t_query['teams'][0] d_twenty = random.randint(1, 20) embed = get_team_embed('Weather Chart', team, thumbnail=False) embed.set_image(url=team['stadium']) @@ -719,29 +752,41 @@ class Players(commands.Cog): await ctx.send(content=None, embed=embed) async def get_division_standings(self, current) -> discord.Embed: - div_one = await get_standings(current['season'], league_abbrev='al', division_abbrev='e') - div_two = await get_standings(current['season'], league_abbrev='al', division_abbrev='w') - div_three = await get_standings(current['season'], league_abbrev='nl', division_abbrev='e') - div_four = await get_standings(current['season'], league_abbrev='nl', division_abbrev='w') + d1_query = await db_get('standings', params=[ + ('season', current['season']), ('league_abbrev', 'al'), ('division_abbrev', 'e') + ]) + div_one = d1_query['standings'] + d2_query = await db_get('standings', params=[ + ('season', current['season']), ('league_abbrev', 'al'), ('division_abbrev', 'w') + ]) + div_two = d2_query['standings'] + d3_query = await db_get('standings', params=[ + ('season', current['season']), ('league_abbrev', 'nl'), ('division_abbrev', 'e') + ]) + div_three = d3_query['standings'] + d4_query = await db_get('standings', params=[ + ('season', current['season']), ('league_abbrev', 'nl'), ('division_abbrev', 'w') + ]) + div_four = d4_query['standings'] div_one_standings = f'```\nTeam W-L PCT GB E# RD\n' for team in div_one: - div_one_standings += self.team_stan_line(div_one[team]) + div_one_standings += self.team_stan_line(team) div_one_standings += f'\n```' div_two_standings = f'```\nTeam W-L PCT GB E# RD\n' for team in div_two: - div_two_standings += self.team_stan_line(div_two[team]) + div_two_standings += self.team_stan_line(team) div_two_standings += f'\n```' div_three_standings = f'```\nTeam W-L PCT GB E# RD\n' for team in div_three: - div_three_standings += self.team_stan_line(div_three[team]) + div_three_standings += self.team_stan_line(team) div_three_standings += f'\n```' div_four_standings = f'```\nTeam W-L PCT GB E# RD\n' for team in div_four: - div_four_standings += self.team_stan_line(div_four[team]) + div_four_standings += self.team_stan_line(team) div_four_standings += f'\n```' progress = await self.game_progress(current) @@ -758,17 +803,23 @@ class Players(commands.Cog): return embed async def get_wildcard_standings(self, current) -> discord.Embed: - al_teams = await get_standings(current['season'], league_abbrev='al') - nl_teams = await get_standings(current['season'], league_abbrev='nl') + a_query = await db_get('standings', params=[ + ('season', current['season']), ('league_abbrev', 'al') + ]) + al_teams = a_query['standings'] + n_query = await db_get('standings', params=[ + ('season', current['season']), ('league_abbrev', 'nl') + ]) + nl_teams = n_query['standings'] al_wildcard = f'```\nTeam W-L PCT GB E# RD\n' for team in al_teams: - al_wildcard += self.team_stan_line(al_teams[team], s_type='wc') + al_wildcard += self.team_stan_line(team, s_type='wc') al_wildcard += '```' nl_wildcard = f'```\nTeam W-L PCT GB E# RD\n' for team in nl_teams: - nl_wildcard += self.team_stan_line(nl_teams[team], s_type='wc') + nl_wildcard += self.team_stan_line(team, s_type='wc') nl_wildcard += '```' progress = await self.game_progress(current) @@ -783,10 +834,11 @@ class Players(commands.Cog): return embed async def standings_button_loop(self, ctx, start: Literal['division', 'wildcard']): - current = await get_current() - div_embed = await self.get_division_standings(current) - wc_embed = await self.get_wildcard_standings(current) - logging.info(f'div_embed: {div_embed}\nwc_embed: {wc_embed}') + async with ctx.typing(): + current = await db_get('current') + div_embed = await self.get_division_standings(current) + wc_embed = await self.get_wildcard_standings(current) + logging.info(f'div_embed: {div_embed}\nwc_embed: {wc_embed}') view = Pagination(responders=[ctx.author], timeout=15) view.left_button.label = 'Division' @@ -838,73 +890,6 @@ class Players(commands.Cog): async def wildcard_command(self, ctx): await self.standings_button_loop(ctx, 'wildcard') - # @commands.command(name='setinjury', aliases=['clearinjury'], help='!SetInjury or !ClearInjury') - # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) - # async def set_injury_command(self, ctx, *, player_name): - # await ctx.send('This command has been deprecated. Please use `/setinjury` or `/clearinjury`') - # return - # - # current = await get_current() - # - # player = await get_one_player(player_name) - # - # # Check if player is on owner's team - # team = await get_team_by_owner(current['season'], ctx.author.id) - # if not player['team'] == team and not player['team']['abbrev'][:len(team['abbrev'])] == team['abbrev']: - # await ctx.send(f'Is this some kind of tom foolery? {player["name"]} is on {player["team"]["abbrev"]} aka ' - # f'not your team. I\'m watching you.') - # return - # - # embed = get_team_embed(f'Injury Update', team=team) - # if player['il_return']: - # # Confirm injury is over - # old_injury = player['il_return'] - # prompt = f'{player["name"]}\'s return was set for {player["il_return"]}. Is he eligible to play again?' - # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', 60.0) - # resp = await this_q.ask([ctx.author]) - # if not resp: - # await ctx.send('Okay, let me know when it\'s over.') - # return - # else: - # player['il_return'] = None - # if await patch_player(player['id'], il_return=False): - # embed.add_field( - # name=f'{player["name"]}', - # value=f'{team["sname"]} {player["pos_1"]} {player["name"]}\'s injury ({old_injury}) has ended' - # ) - # # await log_channel.send( - # # f'{player["team"]["sname"]} {player["pos_1"]} {player["name"]}\'s IL stint is over.' - # # ) - # else: - # # Get injury end date - # prompt = f'When is {player["name"]} eligible to play again? (eg: w17g2)' - # this_q = Question(self.bot, ctx.channel, prompt, 'text', 60.0) - # resp = await this_q.ask([ctx.author]) - # injury_pattern = 'wk[0-9]+g[1-7]|w[0-9]+g[1-7]' - # - # if not resp: - # await ctx.send('Tell you hwat. You recount it. Math is hard. Then you can get back to me.') - # return - # elif not re.search(injury_pattern, resp.lower()): - # await ctx.send('I, uh...I was expecting something shorter like this: w12g4. Try again maybe?') - # return - # else: - # date_list = re.split('[a-z]+', resp.lower()) - # return_date = f'w{date_list[1]:0>2}g{date_list[2]}' - # player['il_return'] = return_date - # if await patch_player(player['id'], il_return=return_date): - # embed.add_field( - # name=f'{player["name"]}', - # value=f'{team["sname"]} {player["pos_1"]} {player["name"]} is injured until {return_date}' - # ) - # # await log_channel.send( - # # f'{player["team"]["sname"]} {player["pos_1"]} {player["name"]} can return {player["il_return"]}' - # # ) - # - # await ctx.send(random_salute_gif()) - # await send_to_channel(self.bot, 'sba-network-news', content=None, embed=embed) - # await self.update_injuries(ctx) - @app_commands.command(name='setinjury', description='Set the return date for injured player') @app_commands.guilds(discord.Object(id=os.environ.get('GUILD_ID'))) @app_commands.describe( @@ -916,16 +901,22 @@ class Players(commands.Cog): @app_commands.checks.has_any_role(SBA_PLAYERS_ROLE_NAME) async def set_injury_slash( self, interaction: discord.Interaction, player_name: str, this_week: int, this_game: int, inj_games: int): - current = await get_current() + await interaction.response.defer() + current = await db_get('current') - player = await get_one_player(player_name) + p_query = await db_get('players', params=[('name', player_name), ('season', current['season'])]) + if p_query['count'] == 0: + await interaction.edit_original_response(content=f'I did not find anybody named **{player_name}**.') + return + + player = p_query['players'][0] # Check if player is on owner's team team = await get_team_by_owner(current['season'], interaction.user.id) if not player['team'] == team and not player['team']['abbrev'][:len(team['abbrev'])] == team['abbrev']: - await interaction.response.send_message( - f'Is this some kind of tom foolery? {player["name"]} is on {player["team"]["abbrev"]} aka ' - f'not your team. I\'m watching you.' + await interaction.edit_original_response( + content=f'Is this some kind of tom foolery? {player["name"]} is on {player["team"]["abbrev"]} aka ' + f'not your team. I\'m watching you.' ) return @@ -939,40 +930,47 @@ class Players(commands.Cog): return_game -= 4 return_date = f'w{return_week:>02}g{return_game:>02}' - if await patch_player(player['id'], il_return=return_date): - await patch_current(injury_count=current['injury_count'] + 1) + player['il_return'] = return_date + if await patch_player(player): + await db_patch('current', object_id=current['id'], params=[('injury_count', current['injury_count'] + 1)]) embed = get_team_embed(f'Injury Update', team=team) embed.add_field( name=f'{player["name"]}', value=f'{team["sname"]} {player["pos_1"]} {player["name"]} is injured until {return_date}' ) - await log_injury( - current, {'player': player, 'type': 'new', 'current_game': this_game, 'injury_length': inj_games} - ) - await interaction.response.send_message(random_salute_gif()) + # await log_injury( + # current, {'player': player, 'type': 'new', 'current_game': this_game, 'injury_length': inj_games} + # ) + await interaction.edit_original_response(content=random_salute_gif()) await send_to_channel(self.bot, 'sba-network-news', content=None, embed=embed) await self.update_injuries(interaction) else: - await interaction.response.send_message('Well that didn\'t work.') + await interaction.edit_original_response(content='Well that didn\'t work.') @app_commands.command(name='clearinjury', description='Clear the injury for a player') @app_commands.describe(player_name='Name of injured player') @app_commands.checks.has_any_role(SBA_PLAYERS_ROLE_NAME) async def clear_injury_slash(self, interaction: discord.Interaction, player_name: str): await interaction.response.defer() - current = await get_current() - player = await get_one_player(player_name) + current = await db_get('current') + + p_query = await db_get('players', params=[('name', player_name), ('season', current['season'])]) + if p_query['count'] == 0: + await interaction.response.send_message(f'I did not find anybody named **{player_name}**.') + return + + player = p_query['players'][0] if not player['il_return']: - await interaction.response.send_message('Huh? He isn\'t injured, numb nuts.') + await interaction.edit_original_response(content='Huh? He isn\'t injured, numb nuts.') return team = await get_team_by_owner(current['season'], interaction.user.id) if not player['team'] == team and not player['team']['abbrev'][:len(team['abbrev'])] == team['abbrev']: - await interaction.response.send_message( - f'Is this some kind of tom foolery? {player["name"]} is on {player["team"]["abbrev"]} aka ' - f'not your team. I\'m watching you.' + await interaction.edit_original_response( + content=f'Is this some kind of tom foolery? {player["name"]} is on {player["team"]["abbrev"]} aka ' + f'not your team. I\'m watching you.' ) return @@ -993,17 +991,20 @@ class Players(commands.Cog): content='Okay. Working on it...', view=None ) - if await patch_player(player['id'], il_return=False): - await patch_current(injury_count=current['injury_count'] + 1) + player['il_return'] = None + if await patch_player(player): + await db_patch( + 'current', object_id=current['id'], params=[('injury_count', current['injury_count'] + 1)] + ) embed = get_team_embed(f'Injury Update', team=team) embed.add_field( name=f'{player["name"]}', value=f'{team["sname"]} {player["pos_1"]} {player["name"]}\'s injury ({old_injury}) has ended' ) - await log_injury( - current, {'player': player, 'type': 'clear', 'current_game': None, 'injury_length': None} - ) + # await log_injury( + # current, {'player': player, 'type': 'clear', 'current_game': None, 'injury_length': None} + # ) await interaction.edit_original_response( content=random_conf_gif(), view=None @@ -1011,7 +1012,7 @@ class Players(commands.Cog): await send_to_channel(self.bot, 'sba-network-news', content=None, embed=embed) await self.update_injuries(interaction) else: - await interaction.response.message_update('Well that didn\'t work.') + await interaction.edit_original_response(content='Well that didn\'t work.') else: await interaction.edit_original_response( content='You keep thinking on it.', @@ -1059,1047 +1060,38 @@ class Players(commands.Cog): # await ctx.send('For full rules, see ') await ctx.send('This command has been deprecated - please run `/charts rest`') - @app_commands.command(name='sba-submit', description='Submit scorecard and game result') - @app_commands.checks.has_any_role(SBA_PLAYERS_ROLE_NAME) - async def submit_slash(self, interaction: discord.Interaction, sheet_url: str): - current = await get_current() - - # Go get scorecard - await interaction.response.send_message(content='I\'ll go grab that card now...') - logging.info(f'Checking scorecard {sheet_url}') - - # Try to get card - try: - sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') - scorecard = sheets.open_by_url(sheet_url).worksheet_by_title('Results') - except Exception as e: - logging.error(f'Failed to access scorecard {sheet_url}: {e}') - await interaction.edit_original_response(content='Is that sheet public? I can\'t access it.') - return - - # Get outline data from the sheet - try: - away_bats = scorecard.get_values('A3', 'AK19') - home_bats = scorecard.get_values('A33', 'AK49') - away_arms = scorecard.get_values('A22', 'V30') - home_arms = scorecard.get_values('A52', 'V59') - away_team = await get_one_team(away_arms[0][1]) - home_team = await get_one_team(home_arms[0][1]) - week_num = away_bats[0][35] - game_num = home_bats[0][36] - except Exception as e: - logging.error(f'Failed to read scorecard {sheet_url}: {e}') - await interaction.edit_original_response(content=f'Oof, I got you an error:\n\n{e}.') - return - - # Confirm teams and matchup - this_matchup = await get_schedule( - current['season'], away_abbrev=away_team['abbrev'], home_abbrev=home_team['abbrev'], week_start=week_num, - week_end=week_num - ) - if len(this_matchup) != 1: - await interaction.edit_original_response( - content=f'Hmm...it doesn\'t look like {away_team["abbrev"]} played {home_team["abbrev"]} in ' - f'week {week_num}.' - ) - return - - # Confirm stats for game don't already exist - old_home_bat = await get_battingstat( - season=current['season'], team_abbrev=home_team['abbrev'], week_start=week_num, - week_end=week_num, game_num=game_num) - old_away_bat = await get_battingstat( - season=current['season'], team_abbrev=away_team['abbrev'], week_start=week_num, - week_end=week_num, game_num=game_num) - old_home_arm = await get_pitchingstat( - season=current['season'], team_abbrev=home_team['abbrev'], week_start=week_num, - week_end=week_num, game_num=game_num) - old_away_arm = await get_pitchingstat( - season=current['season'], team_abbrev=away_team['abbrev'], week_start=week_num, - week_end=week_num, game_num=game_num) - - # Confirm submitting GM - if await get_team_by_owner(current['season'], interaction.user.id) not in [home_team, away_team] and \ - interaction.user.id != self.bot.owner_id: - await interaction.edit_original_response( - content=f'{await get_emoji(interaction, "squint")} Only a GM of the two teams can submit scorecards.' - ) - return - - if len(old_home_bat) + len(old_away_bat) + len(old_home_arm) + len(old_away_arm) > 0: - view = Confirm(responders=[interaction.user]) - question = await interaction.channel.send( - f'I already see stats for {away_team["abbrev"]} @ {home_team["abbrev"]} week {week_num} game ' - f'{game_num}. Would you like me to remove those and update with this card?', - view=view - ) - await view.wait() - - if view.value: - logging.info(f'sba-submit - view.value') - this_game = { - 'season': current['season'], - 'week': week_num, - 'game_num': game_num, - 'away_team_id': away_team['id'], - 'home_team_id': home_team['id'] - } - - await question.edit( - content='What a pain in my balls. Let\'s start by deleting the batting stats...', - view=None - ) - if await delete_battingstats(this_game): - await question.edit(content='Batting stats are gone - now the pitching stats...') - - if await delete_pitchingstats(this_game): - await question.edit( - content='Pitching stats are gone - now to recalculate everybody\'s season batting lines...' - ) - - if await recalc_batting_seasons(current['season'], away_team['id']): - if await recalc_batting_seasons(current['season'], home_team['id']): - await question.edit( - content='Batting lines are done - now to recalculate pitching lines...' - ) - - if await recalc_pitching_seasons(current['season'], away_team['id']): - if await recalc_pitching_seasons(current['season'], home_team['id']): - await question.edit( - content='Pitching lines are done - now to recalculate fielding lines...' - ) - - if await recalc_fielding_seasons(current['season'], away_team['id']): - if await recalc_fielding_seasons(current['season'], home_team['id']): - await question.edit( - content=f'All done. Don\'t suck next time ' - f'{await get_emoji(interaction.guild, "lakemonsters")}' - ) - - week_games = await get_results( - current['season'], away_abbrev=away_team['abbrev'], home_abbrev=home_team['abbrev'], week=week_num - ) - this_game = None - for x in week_games: - if week_games[x]['game'] == game_num: - this_game = week_games[x] - break - if this_game: - await delete_result(this_game['id']) - - else: - logging.info(f'sba-submit - view.value "else"') - await interaction.channel.send('Alright, we\'ll call it a day here.') - return - - logging.info(f'sba-submit - reading scorecard') - # Read scorecard - errors = [] - b_counts = {'sbc': 0, 'csc': 0, 'sb': 0, 'cs': 0, 'so': 0, 'bb': 0, 'run': 0, 'rbi': 0, 'xba': 0, 'xbt': 0, - 'raa': 0, 'rto': 0} - p_counts = {'gs': 0, 'win': 0, 'loss': 0, 'so': 0, 'bb': 0, 'run': 0, 'erun': 0, 'ir': 0, 'irs': 0} - positions = ['C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF', 'DH', 'PH', 'PR', 'P'] - pit_nums = [f'{x}' for x in range(20)] - - bat_stats = ['player', 'team', 'pos', 'pa', 'ab', 'run', 'hit', 'rbi', 'double', 'triple', 'hr', 'bb', 'so', - 'hbp', 'sac', 'ibb', 'gidp', 'sb', 'cs', 'bphr', 'bpfo', 'bp1b', 'bplo', 'xba', 'xbt', 'xch', - 'xhit', 'error', 'pb', 'sbc', 'csc', 'roba', 'robs', 'raa', 'rto', 'week', 'game'] - pit_stats = ['player', 'team', 'ip', 'hit', 'run', 'erun', 'so', 'bb', 'hbp', 'wp', 'balk', 'hr', 'ir', 'irs', - 'gs', 'win', 'loss', 'hold', 'sv', 'bsv', 'week', 'game'] - - new_bat_stats = [] - new_pit_stats = [] - final_box_away = {'r': 0, 'h': 0, 'e': 0, 'ip': 0} - final_box_home = {'r': 0, 'h': 0, 'e': 0, 'ip': 0} - final_wp = None - final_lp = None - final_holds = [] - final_sv = None - final_bsv = [] - final_doubles = [] - final_triples = [] - final_homeruns = [] - final_sbs = [] - final_cscs = [] - - # Read batting stats - for group in [away_bats, home_bats]: - for line in group: - if line[0]: - # Dictionary to hold data to be passed to db for BatStat model - this_batter = {'season': current['season']} - - # Keeping count so we can add stat name and data from sheet into this_batter dict - for count in range(len(bat_stats)): - if line[count] != '' and line[count] != '#REF' and line[count] != 0: - this_batter[bat_stats[count]] = line[count] - - # Add this_batter to collection new_bat_stats - try: - this_batter['player_id'] = self.player_list[line[0].lower()] - this_batter['team_id'] = away_team['id'] if line[1].lower() == away_team['abbrev'].lower() \ - else home_team['id'] - # Check for pitcher int in position - if this_batter['pos'] in pit_nums: - this_batter['pos'] = 'P' - this_bat_stat = BatStat.parse_obj(this_batter) - new_bat_stats.append(this_bat_stat.dict()) - - # Get stats for news-ticker - if this_batter['team_id'] == away_team['id']: - final_box_away['r'] += this_bat_stat.run - final_box_away['h'] += this_bat_stat.hit - final_box_away['e'] += this_bat_stat.error - else: - final_box_home['r'] += this_bat_stat.run - final_box_home['h'] += this_bat_stat.hit - final_box_home['e'] += this_bat_stat.error - - if this_bat_stat.double: - final_doubles.append((this_batter['player_id'], this_bat_stat.double)) - if this_bat_stat.triple: - final_triples.append((this_batter['player_id'], this_bat_stat.triple)) - if this_bat_stat.hr: - final_homeruns.append((this_batter['player_id'], this_bat_stat.hr)) - if this_bat_stat.sb: - final_sbs.append((this_batter['player_id'], this_bat_stat.sb)) - if this_bat_stat.csc: - final_cscs.append((this_batter['player_id'], this_bat_stat.csc)) - - except Exception as e: - errors.append(f'{line[0]}: {e}') - - # Read pitching stats - for group in [away_arms, home_arms]: - for line in group: - if line[0]: - # Dictionary to hold data for PitStat model - this_pitcher = {'season': current['season']} - - # Keeping count so we can add stat name and data from sheet into this_pitcher dict - for count in range(len(pit_stats)): - if line[count] != '' and line[count] != '#REF' and line[count] != 0: - this_pitcher[pit_stats[count]] = line[count] - - # Add this_pitcher to collection new_pit_stats - try: - this_pitcher['player_id'] = self.player_list[line[0].lower()] - this_pitcher['team_id'] = away_team['id'] if line[1].lower() == away_team['abbrev'].lower() \ - else home_team['id'] - this_pit_stat = PitStat.parse_obj(this_pitcher) - - # Update IP to an even third - first_digit = f'{this_pit_stat.ip % 1}'[2] - if first_digit == '0': - this_pit_stat.ip = math.floor(this_pit_stat.ip) - elif first_digit in ['1', '3']: - this_pit_stat.ip = math.floor(this_pit_stat.ip) + (1/3) - else: - this_pit_stat.ip = math.floor(this_pit_stat.ip) + (2/3) - - new_pit_stats.append(this_pit_stat.dict()) - - # Get stats for news-ticker - if this_pit_stat.win: - final_wp = this_pit_stat.player_id - if this_pit_stat.loss: - final_lp = this_pit_stat.player_id - if this_pit_stat.sv: - final_sv = this_pit_stat.player_id - if this_pit_stat.bsv: - final_bsv.append(this_pit_stat.player_id) - if this_pit_stat.hold: - final_holds.append(this_pit_stat.player_id) - if this_pitcher['team_id'] == away_team['id']: - final_box_away['ip'] += this_pit_stat.ip - else: - final_box_home['ip'] += this_pit_stat.ip - except Exception as e: - errors.append(f'{line[0]}: {e}') - - # Error checks - await interaction.edit_original_response( - content='Just finished reading the scorecard. Now to look for all of your mistakes...' - ) - for line in new_bat_stats: - b_counts['sbc'] += line['sbc'] - b_counts['csc'] += line['csc'] - b_counts['sb'] += line['sb'] - b_counts['cs'] += line['cs'] - b_counts['so'] += line['so'] - b_counts['bb'] += line['bb'] + line['ibb'] - b_counts['run'] += line['run'] - b_counts['rbi'] += line['rbi'] - b_counts['xba'] += line['xba'] - b_counts['xbt'] += line['xbt'] - b_counts['raa'] += line['raa'] - b_counts['rto'] += line['rto'] - if line['pos'] not in positions: - errors.append(f'{line["pos"]} not a valid position') - for line in new_pit_stats: - logging.info(f'line: {line}') - p_counts['gs'] += line['gs'] - p_counts['win'] += line['win'] - p_counts['loss'] += line['loss'] - p_counts['bb'] += line['bb'] - p_counts['so'] += line['so'] - p_counts['run'] += line['run'] - p_counts['erun'] += line['erun'] - p_counts['ir'] += line['ir'] - p_counts['irs'] += line['irs'] - - if b_counts['sbc'] > b_counts['sb'] + b_counts['cs']: - errors.append(f'There are {b_counts["sbc"]} stolen base attempts (SBa), but {b_counts["sb"]} SB and ' - f'{b_counts["cs"]} CS.') - if b_counts['csc'] > b_counts['cs']: - errors.append(f'There are {b_counts["sbc"]} catcher caught stealings (CSc), but ' - f'{b_counts["cs"]} baserunner CS.') - if b_counts['so'] != p_counts['so']: - errors.append(f'There are {b_counts["so"]} batter strikeouts, but {p_counts["so"]} pitcher strikeouts.') - if b_counts['bb'] != p_counts['bb']: - errors.append(f'There are {b_counts["bb"]} batter walks, but {p_counts["bb"]} pitcher.') - if b_counts['run'] != p_counts['run']: - errors.append(f'There are {b_counts["run"]} batter runs, but {p_counts["run"]} pitcher runs.') - if b_counts['rbi'] > b_counts['run']: - errors.append(f'There are {b_counts["rbi"]} runs batted in, but {b_counts["run"]} runs scored.') - if b_counts['rto'] > b_counts['raa']: - errors.append(f'There are {b_counts["rto"]} runners thrown out, but {b_counts["raa"]} runner ' - f'advance attempts.') - if b_counts['xbt'] > b_counts['xba']: - errors.append(f'There are {b_counts["xbt"]} extra bases taken, but {b_counts["xba"]} extra ' - f'base attempts.') - if p_counts['erun'] > p_counts['run']: - errors.append(f'There are {p_counts["erun"]} earned runs and {p_counts["run"]} total runs. ') - if p_counts['gs'] != 2: - errors.append(f'There should be 2 GS, but I see {p_counts["gs"]} of them.') - if p_counts['win'] != 1: - errors.append(f'There should be 1 W, but I see {p_counts["win"]} of them.') - if p_counts['loss'] != 1: - errors.append(f'There should be 1 L, but I see {p_counts["loss"]} of them.') - if p_counts['irs'] > p_counts['ir']: - errors.append(f'There are {p_counts["irs"]} inherited runners scored and {p_counts["ir"]} ' - f'inherited runners.') - - # Post errors, if any, or post stats to db - if len(errors) > 0: - error_message = '\n- '.join(errors) - await interaction.edit_original_response( - content=f'The following errors were found in your **wk{week_num}g{game_num}** scorecard. ' - f'Please resolve them and resubmit - thanks!\n\n- {error_message}' - ) - logging.error(f'Scorecard errors: {error_message}') - return - else: - bat_conf = await post_battingstats(new_bat_stats) - pit_conf = await post_pitchingstats(new_pit_stats) - - if bat_conf and pit_conf: - await interaction.edit_original_response( - content=f'You did it! I just logged the stats for **wk{week_num}g{game_num}**' - ) - - # Update last games for pitchers - for x in new_pit_stats: - this_pitcher = await get_one_player(x["player_id"]) - game_string = f'{float(x["ip"]):.2}IP w{x["week"]}g{x["game"]}' - await patch_player(this_pitcher['id'], last_game=game_string, last_game2=this_pitcher['last_game']) - else: - await interaction.edit_original_response( - content='So the stats looked okay, but I had an accident when I tried to post them. They ' - 'did not go through.' - ) - - # Post scorecard to weekly archive - card_url = f'<{SBA_BASE_URL}/scorecards/?season={current["season"]}&week={week_num}&game={game_num}' \ - f'&away_abbrev={away_team["abbrev"]}&home_abbrev={home_team["abbrev"]}>' - # try: - # archive_channel = get_channel(interaction, name=f'week-{week_num}-archive') - # logging.info(f'archive_channel: {archive_channel}') - # if not archive_channel: - # archive_channel = await create_channel( - # interaction, - # channel_name=f'week-{week_num}-archive', - # category_name=f'Season {current["season"]} Archives', - # read_send_roles=[get_role(interaction, 'Gameplay Bots')] - # ) - # - # await archive_channel.send( - # f'Game {game_num}: **{away_team["sname"]}** {await team_emoji(interaction, away_team)} ' - # f'{final_box_away["r"]} @ {final_box_home["r"]} ' - # f'{await team_emoji(interaction, home_team)} **{home_team["sname"]}**\n{card_url}') - # except Exception as e: - # await interaction.edit_original_response( - # content='Ope. I wasn\'t able to post this to the archive channel.' - # ) - - # Post box score to news-ticker - - extras = '' - if final_box_home['ip'] > 9: - extras = f' F/{math.floor(final_box_home["ip"])}' - embed = get_team_embed( - f'{away_team["sname"]} {final_box_away["r"]} @ ' - f'{final_box_home["r"]} {home_team["sname"]}{extras}', - team=away_team if final_box_away['r'] > final_box_home['r'] else home_team - ) - embed.description = f'Week {week_num} | Game {game_num}' - - embed.add_field( - name='Box Score', - value=f'```\n' - f'Team | R | H | E |\n' - f'{away_team["abbrev"]: <4} | {final_box_away["r"]: >2} | {final_box_away["h"]: >2} | ' - f'{final_box_away["e"]: >2} |\n' - f'{home_team["abbrev"]: <4} | {final_box_home["r"]: >2} | {final_box_home["h"]: >2} | ' - f'{final_box_home["e"]: >2} |\n' - f'```', - inline=False - ) - - wp = await get_one_player(final_wp) - lp = await get_one_player(final_lp) - if final_sv: - sv = await get_one_player(final_sv) - else: - sv = None - holds = [] - bsvs = [] - for x in final_holds: - holds.append(await get_one_player(x)) - for x in final_bsv: - bsvs.append(await get_one_player(x)) - - pitching_string = f'WP: {wp["name"]}\n' \ - f'LP: {lp["name"]}\n' \ - f'{"HD: " if len(holds) > 0 else ""}' - - hold_string = '' - count = 1 - for x in holds: - hold_string += f'{x["name"]}' - if count < len(holds): - hold_string += ', ' - elif len(holds) > 0: - hold_string += '\n' - count += 1 - pitching_string += hold_string - - if sv: - pitching_string += f'SV: {sv["name"]}' - - embed.add_field(name='Pitching', value=pitching_string, inline=False) - - batting_string = '' - count = 1 - if len(final_doubles) > 0: - batting_string += '2B: ' - - for x in final_doubles: - player = await get_one_player(x[0]) - batting_string += f'{player["name"]}' - - if x[1] > 1: - batting_string += f' {x[1]}' - - if count < len(final_doubles): - batting_string += ', ' - else: - batting_string += '\n' - count += 1 - - count = 1 - if len(final_triples) > 0: - batting_string += '3B: ' - - for x in final_triples: - player = await get_one_player(x[0]) - batting_string += f'{player["name"]}' - - if x[1] > 1: - batting_string += f' {x[1]}' - - if count < len(final_triples): - batting_string += ', ' - else: - batting_string += '\n' - count += 1 - - count = 1 - if len(final_homeruns) > 0: - batting_string += 'HR: ' - - for x in final_homeruns: - player = await get_one_player(x[0]) - batting_string += f'{player["name"]}' - - if x[1] > 1: - batting_string += f' {x[1]}' - - if count < len(final_homeruns): - batting_string += ', ' - else: - batting_string += '\n' - count += 1 - - if len(batting_string) > 0: - embed.add_field(name='Batting', value=batting_string, inline=False) - - baserunning_string = '' - count = 1 - if len(final_sbs) > 0: - baserunning_string += 'SB: ' - - for x in final_sbs: - player = await get_one_player(x[0]) - baserunning_string += f'{player["name"]}' - - if x[1] > 1: - baserunning_string += f' {x[1]}' - - if count < len(final_sbs): - baserunning_string += ', ' - else: - baserunning_string += '\n' - count += 1 - - count = 1 - if len(final_cscs) > 0: - baserunning_string += 'CSc: ' - - for x in final_cscs: - player = await get_one_player(x[0]) - baserunning_string += f'{player["name"]}' - - if x[1] > 1: - baserunning_string += f' {x[1]}' - - if count < len(final_cscs): - baserunning_string += ', ' - else: - baserunning_string += '\n' - count += 1 - - if len(baserunning_string) > 0: - embed.add_field(name='Baserunning', value=baserunning_string, inline=False) - - embed.add_field( - name='Scorecard', - value=f'[Website]({card_url}) / [Sheets]({sheet_url})' - ) - embed.set_footer(text='Please share the highlights!') - - await send_to_channel( - self.bot, - 'sba-network-news', - content=None, - embed=embed - ) - - result = { - 'week': week_num, - 'game': game_num, - 'away_team_id': away_team['id'], - 'home_team_id': home_team['id'], - 'away_score': final_box_away["r"], - 'home_score': final_box_home["r"], - 'season': current['season'], - 'scorecard_url': sheet_url - } - if await post_result(result): - update = await interaction.channel.send('I\'m tallying standings now...') - if await post_standings_recalc(current['season']): - await update.delete() - - # @commands.command(name='submit', help='Submit scorecard') - # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) - # async def submit_command(self, ctx, sheet_url): - # # current = await get_current() - # # - # # # Ask for confirmation to pull card - # # prompt = 'Has your opponent double-checked this card for accuracy? They get pretty whiny when you miss ' \ - # # 'a hold or an RBI. (Yes/No)' - # # this_q = Question(bot=self.bot, channel=ctx.channel, prompt=prompt, qtype='yesno', timeout=30) - # # async with ctx.typing(): - # # if not os.environ.get("TESTING"): - # # await asyncio.sleep(4) - # # resp = await this_q.ask([ctx.author]) - # # - # # if not resp: - # # await ctx.send('Not a problem at all. You folks think it over and come back to me when you\'re sure.') - # # return - # # else: - # # await ctx.message.add_reaction('👀') - # # await ctx.send('Hold my sheets, I\'m going in.') - # # - # # # Go get scorecard - # # logging.info(f'Checking scorecard {sheet_url}') - # # async with ctx.typing(): - # # # Try to get card - # # try: - # # sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') - # # scorecard = sheets.open_by_url(sheet_url).worksheet_by_title('Results') - # # except Exception as e: - # # logging.error(f'Failed to open scorecard {sheet_url} with this error: {e}') - # # await ctx.message.add_reaction('❌') - # # await ctx.send(f'{ctx.message.author.mention}, I can\'t access that sheet.') - # # return - # # - # # # Get outline data from the sheet - # # try: - # # away_bats = scorecard.get_values('A3', 'AK19') - # # home_bats = scorecard.get_values('A33', 'AK49') - # # away_arms = scorecard.get_values('A22', 'V29') - # # home_arms = scorecard.get_values('A52', 'V59') - # # away_team = await get_one_team(away_arms[0][1]) - # # home_team = await get_one_team(home_arms[0][1]) - # # week_num = away_bats[0][35] - # # game_num = home_bats[0][36] - # # except Exception as e: - # # logging.error(f'Failed to read scorecard {sheet_url} with this error: {e}') - # # await ctx.message.add_reaction('❌') - # # await ctx.send(f'Yikes. I ran into an error reading this card. This could be ugly:\n\n{e}') - # # return - # # - # # # Confirm teams and matchup - # # this_matchup = await get_schedule( - # # current['season'], away_abbrev=away_team['abbrev'], home_abbrev=home_team['abbrev'], week_start=week_num, - # # week_end=week_num - # # ) - # # if len(this_matchup) != 1: - # # await ctx.send(f'Hmm...it doesn\'t look like {away_team["abbrev"]} played {home_team["abbrev"]} in ' - # # f'week {week_num}.') - # # return - # # - # # # Confirm stats for game don't already exist - # # old_home_bat = await get_battingstat( - # # season=current['season'], team_abbrev=home_team['abbrev'], week_start=week_num, - # # week_end=week_num, game_num=game_num) - # # old_away_bat = await get_battingstat( - # # season=current['season'], team_abbrev=away_team['abbrev'], week_start=week_num, - # # week_end=week_num, game_num=game_num) - # # old_home_arm = await get_pitchingstat( - # # season=current['season'], team_abbrev=home_team['abbrev'], week_start=week_num, - # # week_end=week_num, game_num=game_num) - # # old_away_arm = await get_pitchingstat( - # # season=current['season'], team_abbrev=away_team['abbrev'], week_start=week_num, - # # week_end=week_num, game_num=game_num) - # # - # # if len(old_home_bat) + len(old_away_bat) + len(old_home_arm) + len(old_away_arm) > 0: - # # if len(old_home_bat) > 0: - # # await ctx.send(f'I already see batting stats for the {home_team["sname"]} from w{week_num}g{game_num}') - # # if len(old_away_bat) > 0: - # # await ctx.send(f'I already see batting stats for the {away_team["sname"]} from w{week_num}g{game_num}') - # # if len(old_home_arm) > 0: - # # await ctx.send(f'I already see pitching stats for the {home_team["sname"]} from w{week_num}g{game_num}') - # # if len(old_away_arm) > 0: - # # await ctx.send(f'I already see pitching stats for the {away_team["sname"]} from w{week_num}g{game_num}') - # # await ctx.send('Double check the week and game number and then get back to me.') - # # return - # # - # # # Confirm submitting GM - # # if await get_team_by_owner(current['season'], ctx.author.id) not in [home_team, away_team] and \ - # # ctx.author.id != self.bot.owner_id: - # # await ctx.send(f'{await get_emoji(ctx, "squint")} Only a GM of the two teams can submit scorecards.') - # # return - # # - # # # Read scorecard - # # errors = [] - # # b_counts = {'sbc': 0, 'csc': 0, 'sb': 0, 'cs': 0, 'so': 0, 'bb': 0, 'run': 0, 'rbi': 0, 'xba': 0, 'xbt': 0, - # # 'raa': 0, 'rto': 0} - # # p_counts = {'gs': 0, 'win': 0, 'loss': 0, 'so': 0, 'bb': 0, 'run': 0, 'erun': 0, 'ir': 0, 'irs': 0} - # # positions = ['C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF', 'DH', 'PH', 'PR', 'P'] - # # pit_nums = [f'{x}' for x in range(20)] - # # - # # bat_stats = ['player', 'team', 'pos', 'pa', 'ab', 'run', 'hit', 'rbi', 'double', 'triple', 'hr', 'bb', 'so', - # # 'hbp', 'sac', 'ibb', 'gidp', 'sb', 'cs', 'bphr', 'bpfo', 'bp1b', 'bplo', 'xba', 'xbt', 'xch', - # # 'xhit', 'error', 'pb', 'sbc', 'csc', 'roba', 'robs', 'raa', 'rto', 'week', 'game'] - # # pit_stats = ['player', 'team', 'ip', 'hit', 'run', 'erun', 'so', 'bb', 'hbp', 'wp', 'balk', 'hr', 'ir', 'irs', - # # 'gs', 'win', 'loss', 'hold', 'sv', 'bsv', 'week', 'game'] - # # - # # new_bat_stats = [] - # # new_pit_stats = [] - # # final_box_away = {'r': 0, 'h': 0, 'e': 0, 'ip': 0} - # # final_box_home = {'r': 0, 'h': 0, 'e': 0, 'ip': 0} - # # final_wp = None - # # final_lp = None - # # final_holds = [] - # # final_sv = None - # # final_bsv = [] - # # final_doubles = [] - # # final_triples = [] - # # final_homeruns = [] - # # final_sbs = [] - # # final_cscs = [] - # # - # # # Read batting stats - # # for group in [away_bats, home_bats]: - # # for line in group: - # # if line[0]: - # # # Dictionary to hold data to be passed to db for BatStat model - # # this_batter = {'season': current['season']} - # # - # # # Keeping count so we can add stat name and data from sheet into this_batter dict - # # for count in range(len(bat_stats)): - # # if line[count] != '' and line[count] != '#REF' and line[count] != 0: - # # this_batter[bat_stats[count]] = line[count] - # # - # # # Add this_batter to collection new_bat_stats - # # try: - # # this_batter['player_id'] = self.player_list[line[0].lower()] - # # this_batter['team_id'] = away_team['id'] if line[1].lower() == away_team['abbrev'].lower() \ - # # else home_team['id'] - # # # Check for pitcher int in position - # # if this_batter['pos'] in pit_nums: - # # this_batter['pos'] = 'P' - # # this_bat_stat = BatStat.parse_obj(this_batter) - # # new_bat_stats.append(this_bat_stat.dict()) - # # - # # # Get stats for news-ticker - # # if this_batter['team_id'] == away_team['id']: - # # final_box_away['r'] += this_bat_stat.run - # # final_box_away['h'] += this_bat_stat.hit - # # final_box_away['e'] += this_bat_stat.error - # # else: - # # final_box_home['r'] += this_bat_stat.run - # # final_box_home['h'] += this_bat_stat.hit - # # final_box_home['e'] += this_bat_stat.error - # # - # # if this_bat_stat.double: - # # final_doubles.append((this_batter['player_id'], this_bat_stat.double)) - # # if this_bat_stat.triple: - # # final_triples.append((this_batter['player_id'], this_bat_stat.triple)) - # # if this_bat_stat.hr: - # # final_homeruns.append((this_batter['player_id'], this_bat_stat.hr)) - # # if this_bat_stat.sb: - # # final_sbs.append((this_batter['player_id'], this_bat_stat.sb)) - # # if this_bat_stat.csc: - # # final_cscs.append((this_batter['player_id'], this_bat_stat.csc)) - # # - # # except Exception as e: - # # errors.append(f'{line[0]}: {e}') - # # - # # # Read pitching stats - # # for group in [away_arms, home_arms]: - # # for line in group: - # # if line[0]: - # # # Dictionary to hold data for PitStat model - # # this_pitcher = {'season': current['season']} - # # - # # # Keeping count so we can add stat name and data from sheet into this_pitcher dict - # # for count in range(len(pit_stats)): - # # if line[count] != '' and line[count] != '#REF' and line[count] != 0: - # # this_pitcher[pit_stats[count]] = line[count] - # # - # # # Add this_pitcher to collection new_pit_stats - # # try: - # # this_pitcher['player_id'] = self.player_list[line[0].lower()] - # # this_pitcher['team_id'] = away_team['id'] if line[1].lower() == away_team['abbrev'].lower() \ - # # else home_team['id'] - # # this_pit_stat = PitStat.parse_obj(this_pitcher) - # # - # # # Update IP to an even third - # # first_digit = f'{this_pit_stat.ip % 1}'[2] - # # if first_digit == '0': - # # this_pit_stat.ip = math.floor(this_pit_stat.ip) - # # elif first_digit in ['1', '3']: - # # this_pit_stat.ip = math.floor(this_pit_stat.ip) + (1/3) - # # else: - # # this_pit_stat.ip = math.floor(this_pit_stat.ip) + (2/3) - # # - # # new_pit_stats.append(this_pit_stat.dict()) - # # - # # # Get stats for news-ticker - # # if this_pit_stat.win: - # # final_wp = this_pit_stat.player_id - # # if this_pit_stat.loss: - # # final_lp = this_pit_stat.player_id - # # if this_pit_stat.sv: - # # final_sv = this_pit_stat.player_id - # # if this_pit_stat.bsv: - # # final_bsv.append(this_pit_stat.player_id) - # # if this_pit_stat.hold: - # # final_holds.append(this_pit_stat.player_id) - # # if this_pitcher['team_id'] == away_team['id']: - # # final_box_away['ip'] += this_pit_stat.ip - # # else: - # # final_box_home['ip'] += this_pit_stat.ip - # # except Exception as e: - # # errors.append(f'{line[0]}: {e}') - # # - # # # Error checks - # # await ctx.send('Just finished reading the scorecard. Now to look for all of your mistakes...') - # # async with ctx.typing(): - # # for line in new_bat_stats: - # # b_counts['sbc'] += line['sbc'] - # # b_counts['csc'] += line['csc'] - # # b_counts['sb'] += line['sb'] - # # b_counts['cs'] += line['cs'] - # # b_counts['so'] += line['so'] - # # b_counts['bb'] += line['bb'] + line['ibb'] - # # b_counts['run'] += line['run'] - # # b_counts['rbi'] += line['rbi'] - # # b_counts['xba'] += line['xba'] - # # b_counts['xbt'] += line['xbt'] - # # b_counts['raa'] += line['raa'] - # # b_counts['rto'] += line['rto'] - # # if line['pos'] not in positions: - # # errors.append(f'{line["pos"]} not a valid position') - # # for line in new_pit_stats: - # # logging.info(f'line: {line}') - # # p_counts['gs'] += line['gs'] - # # p_counts['win'] += line['win'] - # # p_counts['loss'] += line['loss'] - # # p_counts['bb'] += line['bb'] - # # p_counts['so'] += line['so'] - # # p_counts['run'] += line['run'] - # # p_counts['erun'] += line['erun'] - # # p_counts['ir'] += line['ir'] - # # p_counts['irs'] += line['irs'] - # # - # # if b_counts['sbc'] != b_counts['sb'] + b_counts['cs']: - # # errors.append(f'There are {b_counts["sbc"]} stolen base attempts (SBa), but {b_counts["sb"]} SB and ' - # # f'{b_counts["cs"]} CS.') - # # if b_counts['csc'] != b_counts['cs']: - # # errors.append(f'There are {b_counts["sbc"]} catcher caught stealings (CSc), but ' - # # f'{b_counts["cs"]} baserunner CS.') - # # if b_counts['so'] != p_counts['so']: - # # errors.append(f'There are {b_counts["so"]} batter strikeouts, but {p_counts["so"]} pitcher strikeouts.') - # # if b_counts['bb'] != p_counts['bb']: - # # errors.append(f'There are {b_counts["bb"]} batter walks, but {p_counts["bb"]} pitcher.') - # # if b_counts['run'] != p_counts['run']: - # # errors.append(f'There are {b_counts["run"]} batter runs, but {p_counts["run"]} pitcher runs.') - # # if b_counts['rbi'] > b_counts['run']: - # # errors.append(f'There are {b_counts["rbi"]} runs batted in, but {b_counts["run"]} runs scored.') - # # if b_counts['rto'] > b_counts['raa']: - # # errors.append(f'There are {b_counts["rto"]} runners thrown out, but {b_counts["raa"]} runner ' - # # f'advance attempts.') - # # if b_counts['xbt'] > b_counts['xba']: - # # errors.append(f'There are {b_counts["xbt"]} extra bases taken, but {b_counts["xba"]} extra ' - # # f'base attempts.') - # # if p_counts['erun'] > p_counts['run']: - # # errors.append(f'There are {p_counts["erun"]} earned runs and {p_counts["run"]} total runs. ') - # # if p_counts['gs'] != 2: - # # errors.append(f'There should be 2 GS, but I see {p_counts["gs"]} of them.') - # # if p_counts['win'] != 1: - # # errors.append(f'There should be 1 W, but I see {p_counts["win"]} of them.') - # # if p_counts['loss'] != 1: - # # errors.append(f'There should be 1 L, but I see {p_counts["loss"]} of them.') - # # if p_counts['irs'] > p_counts['ir']: - # # errors.append(f'There are {p_counts["irs"]} inherited runners scored and {p_counts["ir"]} ' - # # f'inherited runners.') - # # - # # # Post errors, if any, or post stats to db - # # if len(errors) > 0: - # # error_message = '\n- '.join(errors) - # # await ctx.message.add_reaction('❌') - # # await ctx.send(f'The following errors were found in your **wk{week_num}g{game_num}** scorecard. ' - # # f'Please resolve them and resubmit - thanks!\n\n- {error_message}') - # # logging.error(f'Scorecard errors: {error_message}') - # # return - # # else: - # # bat_conf = await post_battingstats(new_bat_stats) - # # pit_conf = await post_pitchingstats(new_pit_stats) - # # - # # if bat_conf and pit_conf: - # # await ctx.message.add_reaction('✅') - # # await ctx.send(f'You did it! I just logged the stats for **wk{week_num}g{game_num}**') - # # - # # # Update last games for pitchers - # # for x in new_pit_stats: - # # this_pitcher = await get_one_player(x["player_id"]) - # # game_string = f'{float(x["ip"]):.2}IP w{x["week"]}g{x["game"]}' - # # await patch_player(this_pitcher['id'], last_game=game_string, last_game2=this_pitcher['last_game']) - # # else: - # # await ctx.send('So the stats looked okay, but I had an accident when I tried to post them. They ' - # # 'did not go through.') - # # - # # # Post scorecard to weekly archive - # # card_url = f'<{SBA_BASE_URL}/scorecards/?season={current["season"]}&week={week_num}&game={game_num}' \ - # # f'&away_abbrev={away_team["abbrev"]}&home_abbrev={home_team["abbrev"]}>' - # # archive_channel = discord.utils.get(ctx.guild.text_channels, name=f'week-{week_num}-archive') - # # if not archive_channel: - # # overwrites = {ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False, embed_links=False), - # # ctx.guild.me: discord.PermissionOverwrite(send_messages=True)} - # # archive_channel = await ctx.guild.create_text_channel( - # # f'week-{week_num}-archive', - # # overwrites=overwrites, - # # category=discord.utils.get(ctx.guild.categories, name=f'Season {current["season"]} Archives'), - # # position=0 - # # ) - # # - # # await archive_channel.send( - # # f'Game {game_num}: **{away_team["sname"]}** {await team_emoji(ctx, away_team)} ' - # # f'{final_box_away["r"]} @ {final_box_home["r"]} ' - # # f'{await team_emoji(ctx, home_team)} **{home_team["sname"]}**\n{card_url}') - # # - # # # Post box score to news-ticker - # # extras = '' - # # if final_box_home['ip'] > 9: - # # extras = f' F/{math.floor(final_box_home["ip"])}' - # # embed = get_team_embed( - # # f'{away_team["sname"]} {final_box_away["r"]} @ ' - # # f'{final_box_home["r"]} {home_team["sname"]}{extras}', - # # team=away_team if final_box_away['r'] > final_box_home['r'] else home_team - # # ) - # # embed.description = f'Week {week_num} | Game {game_num}' - # # - # # embed.add_field( - # # name='Box Score', - # # value=f'```\n' - # # f'Team | R | H | E |\n' - # # f'{away_team["abbrev"]: <4} | {final_box_away["r"]: >2} | {final_box_away["h"]: >2} | ' - # # f'{final_box_away["e"]: >2} |\n' - # # f'{home_team["abbrev"]: <4} | {final_box_home["r"]: >2} | {final_box_home["h"]: >2} | ' - # # f'{final_box_home["e"]: >2} |\n' - # # f'```', - # # inline=False - # # ) - # # - # # wp = await get_one_player(final_wp) - # # lp = await get_one_player(final_lp) - # # if final_sv: - # # sv = await get_one_player(final_sv) - # # else: - # # sv = None - # # holds = [] - # # bsvs = [] - # # for x in final_holds: - # # holds.append(await get_one_player(x)) - # # for x in final_bsv: - # # bsvs.append(await get_one_player(x)) - # # - # # pitching_string = f'WP: {wp["name"]}\n' \ - # # f'LP: {lp["name"]}\n' \ - # # f'{"HD: " if len(holds) > 0 else ""}' - # # - # # hold_string = '' - # # count = 1 - # # for x in holds: - # # hold_string += f'{x["name"]}' - # # if count < len(holds): - # # hold_string += ', ' - # # elif len(holds) > 0: - # # hold_string += '\n' - # # count += 1 - # # pitching_string += hold_string - # # - # # if sv: - # # pitching_string += f'SV: {sv["name"]}' - # # - # # embed.add_field(name='Pitching', value=pitching_string, inline=False) - # # - # # batting_string = '' - # # count = 1 - # # if len(final_doubles) > 0: - # # batting_string += '2B: ' - # # - # # for x in final_doubles: - # # player = await get_one_player(x[0]) - # # batting_string += f'{player["name"]}' - # # - # # if x[1] > 1: - # # batting_string += f' {x[1]}' - # # - # # if count < len(final_doubles): - # # batting_string += ', ' - # # else: - # # batting_string += '\n' - # # count += 1 - # # - # # count = 1 - # # if len(final_triples) > 0: - # # batting_string += '3B: ' - # # - # # for x in final_triples: - # # player = await get_one_player(x[0]) - # # batting_string += f'{player["name"]}' - # # - # # if x[1] > 1: - # # batting_string += f' {x[1]}' - # # - # # if count < len(final_triples): - # # batting_string += ', ' - # # else: - # # batting_string += '\n' - # # count += 1 - # # - # # count = 1 - # # if len(final_homeruns) > 0: - # # batting_string += 'HR: ' - # # - # # for x in final_homeruns: - # # player = await get_one_player(x[0]) - # # batting_string += f'{player["name"]}' - # # - # # if x[1] > 1: - # # batting_string += f' {x[1]}' - # # - # # if count < len(final_homeruns): - # # batting_string += ', ' - # # else: - # # batting_string += '\n' - # # count += 1 - # # - # # if len(batting_string) > 0: - # # embed.add_field(name='Batting', value=batting_string, inline=False) - # # - # # baserunning_string = '' - # # count = 1 - # # if len(final_sbs) > 0: - # # baserunning_string += 'SB: ' - # # - # # for x in final_sbs: - # # player = await get_one_player(x[0]) - # # baserunning_string += f'{player["name"]}' - # # - # # if x[1] > 1: - # # baserunning_string += f' {x[1]}' - # # - # # if count < len(final_sbs): - # # baserunning_string += ', ' - # # else: - # # baserunning_string += '\n' - # # count += 1 - # # - # # count = 1 - # # if len(final_cscs) > 0: - # # baserunning_string += 'CSc: ' - # # - # # for x in final_cscs: - # # player = await get_one_player(x[0]) - # # baserunning_string += f'{player["name"]}' - # # - # # if x[1] > 1: - # # baserunning_string += f' {x[1]}' - # # - # # if count < len(final_cscs): - # # baserunning_string += ', ' - # # else: - # # baserunning_string += '\n' - # # count += 1 - # # - # # if len(baserunning_string) > 0: - # # embed.add_field(name='Baserunning', value=baserunning_string, inline=False) - # # - # # embed.add_field(name='Scorecard', value=card_url) - # # embed.set_footer(text='Please share the highlights!') - # # - # # await send_to_channel( - # # self.bot, - # # 'sba-network-news', - # # content=None, - # # embed=embed - # # ) - # await ctx.send(f'Please run `/sba-submit` to submit scorecards.') - - # @commands.command(name='removestats', help='Remove scorecard') - # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) - # async def remove_stats_command(self, ctx, away_abbrev, home_abbrev, week_num, game_num): - # current = await get_current() + # @app_commands.command(name='sba-submit', description='Submit scorecard and game result') + # @app_commands.checks.has_any_role(SBA_PLAYERS_ROLE_NAME) + # async def submit_slash(self, interaction: discord.Interaction, sheet_url: str): + # current = await db_get('current') # - # owner_team = await get_team_by_owner(current['season'], ctx.author.id) - # away_team = await get_one_team(away_abbrev) - # home_team = await get_one_team(home_abbrev) + # # Go get scorecard + # await interaction.response.send_message(content='I\'ll go grab that card now...') + # logging.info(f'Checking scorecard {sheet_url}') + # + # # Try to get card + # try: + # sheets = pygsheets.authorize(service_file='storage/major-domo-service-creds.json') + # scorecard = sheets.open_by_url(sheet_url).worksheet_by_title('Results') + # except Exception as e: + # logging.error(f'Failed to access scorecard {sheet_url}: {e}') + # await interaction.edit_original_response(content='Is that sheet public? I can\'t access it.') + # return + # + # # Get outline data from the sheet + # try: + # away_bats = scorecard.get_values('A3', 'AK19') + # home_bats = scorecard.get_values('A33', 'AK49') + # away_arms = scorecard.get_values('A22', 'V30') + # home_arms = scorecard.get_values('A52', 'V59') + # away_team = await get_one_team(away_arms[0][1]) + # home_team = await get_one_team(home_arms[0][1]) + # week_num = away_bats[0][35] + # game_num = home_bats[0][36] + # except Exception as e: + # logging.error(f'Failed to read scorecard {sheet_url}: {e}') + # await interaction.edit_original_response(content=f'Oof, I got you an error:\n\n{e}.') + # return # # # Confirm teams and matchup # this_matchup = await get_schedule( @@ -2107,75 +1099,517 @@ class Players(commands.Cog): # week_end=week_num # ) # if len(this_matchup) != 1: - # await ctx.send(f'Hmm...it doesn\'t look like {away_team["abbrev"]} played {home_team["abbrev"]} in ' - # f'week {week_num}.') + # await interaction.edit_original_response( + # content=f'Hmm...it doesn\'t look like {away_team["abbrev"]} played {home_team["abbrev"]} in ' + # f'week {week_num}.' + # ) # return # # # Confirm stats for game don't already exist - # s_type = 'Regular' if current['week'] < current['playoffs_begin'] else 'Post' # old_home_bat = await get_battingstat( - # season=current['season'], s_type=s_type, team_abbrev=home_team['abbrev'], week_start=week_num, + # season=current['season'], team_abbrev=home_team['abbrev'], week_start=week_num, # week_end=week_num, game_num=game_num) # old_away_bat = await get_battingstat( - # season=current['season'], s_type=s_type, team_abbrev=away_team['abbrev'], week_start=week_num, + # season=current['season'], team_abbrev=away_team['abbrev'], week_start=week_num, # week_end=week_num, game_num=game_num) # old_home_arm = await get_pitchingstat( - # season=current['season'], s_type=s_type, team_abbrev=home_team['abbrev'], week_start=week_num, + # season=current['season'], team_abbrev=home_team['abbrev'], week_start=week_num, # week_end=week_num, game_num=game_num) # old_away_arm = await get_pitchingstat( - # season=current['season'], s_type=s_type, team_abbrev=away_team['abbrev'], week_start=week_num, + # season=current['season'], team_abbrev=away_team['abbrev'], week_start=week_num, # week_end=week_num, game_num=game_num) # - # if len(old_home_bat) + len(old_away_bat) + len(old_home_arm) + len(old_away_arm) == 0: - # await ctx.send('Good news: I don\'t see any stats for that game. Bad news: you seemed to think there ' - # 'were some.') - # return - # # # Confirm submitting GM - # if owner_team not in [home_team, away_team] and ctx.author.id != self.bot.owner_id: - # await ctx.send(f'{await get_emoji(ctx, "squint")} Only a GM of the two teams can remove stats.') + # if await get_team_by_owner(current['season'], interaction.user.id) not in [home_team, away_team] and \ + # interaction.user.id != self.bot.owner_id: + # await interaction.edit_original_response( + # content=f'{await get_emoji(interaction, "squint")} Only a GM of the two teams can submit scorecards.' + # ) # return # - # prompt = 'Are you sure? This will snap these stats out of existence.' - # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', 30) - # resp = await this_q.ask([ctx.author]) + # if len(old_home_bat) + len(old_away_bat) + len(old_home_arm) + len(old_away_arm) > 0: + # view = Confirm(responders=[interaction.user]) + # question = await interaction.channel.send( + # f'I already see stats for {away_team["abbrev"]} @ {home_team["abbrev"]} week {week_num} game ' + # f'{game_num}. Would you like me to remove those and update with this card?', + # view=view + # ) + # await view.wait() # - # if not resp: - # await ctx.send('Whew. There for a second I thought you fucked up a scorecard. I\'ll leave this one be.') + # if view.value: + # logging.info(f'sba-submit - view.value') + # this_game = { + # 'season': current['season'], + # 'week': week_num, + # 'game_num': game_num, + # 'away_team_id': away_team['id'], + # 'home_team_id': home_team['id'] + # } + # + # await question.edit( + # content='What a pain in my balls. Let\'s start by deleting the batting stats...', + # view=None + # ) + # if await delete_battingstats(this_game): + # await question.edit(content='Batting stats are gone - now the pitching stats...') + # + # if await delete_pitchingstats(this_game): + # await question.edit( + # content='Pitching stats are gone - now to recalculate everybody\'s season batting lines...' + # ) + # + # if await recalc_batting_seasons(current['season'], away_team['id']): + # if await recalc_batting_seasons(current['season'], home_team['id']): + # await question.edit( + # content='Batting lines are done - now to recalculate pitching lines...' + # ) + # + # if await recalc_pitching_seasons(current['season'], away_team['id']): + # if await recalc_pitching_seasons(current['season'], home_team['id']): + # await question.edit( + # content='Pitching lines are done - now to recalculate fielding lines...' + # ) + # + # if await recalc_fielding_seasons(current['season'], away_team['id']): + # if await recalc_fielding_seasons(current['season'], home_team['id']): + # await question.edit( + # content=f'All done. Don\'t suck next time ' + # f'{await get_emoji(interaction.guild, "lakemonsters")}' + # ) + # + # week_games = await get_results( + # current['season'], away_abbrev=away_team['abbrev'], home_abbrev=home_team['abbrev'], week=week_num + # ) + # this_game = None + # for x in week_games: + # if week_games[x]['game'] == game_num: + # this_game = week_games[x] + # break + # if this_game: + # await db_delete('results', object_id=this_game['id']) + # + # else: + # logging.info(f'sba-submit - view.value "else"') + # await interaction.channel.send('Alright, we\'ll call it a day here.') + # return + # + # logging.info(f'sba-submit - reading scorecard') + # # Read scorecard + # errors = [] + # b_counts = {'sbc': 0, 'csc': 0, 'sb': 0, 'cs': 0, 'so': 0, 'bb': 0, 'run': 0, 'rbi': 0, 'xba': 0, 'xbt': 0, + # 'raa': 0, 'rto': 0} + # p_counts = {'gs': 0, 'win': 0, 'loss': 0, 'so': 0, 'bb': 0, 'run': 0, 'erun': 0, 'ir': 0, 'irs': 0} + # positions = ['C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF', 'DH', 'PH', 'PR', 'P'] + # pit_nums = [f'{x}' for x in range(20)] + # + # bat_stats = ['player', 'team', 'pos', 'pa', 'ab', 'run', 'hit', 'rbi', 'double', 'triple', 'hr', 'bb', 'so', + # 'hbp', 'sac', 'ibb', 'gidp', 'sb', 'cs', 'bphr', 'bpfo', 'bp1b', 'bplo', 'xba', 'xbt', 'xch', + # 'xhit', 'error', 'pb', 'sbc', 'csc', 'roba', 'robs', 'raa', 'rto', 'week', 'game'] + # pit_stats = ['player', 'team', 'ip', 'hit', 'run', 'erun', 'so', 'bb', 'hbp', 'wp', 'balk', 'hr', 'ir', 'irs', + # 'gs', 'win', 'loss', 'hold', 'sv', 'bsv', 'week', 'game'] + # + # new_bat_stats = [] + # new_pit_stats = [] + # final_box_away = {'r': 0, 'h': 0, 'e': 0, 'ip': 0} + # final_box_home = {'r': 0, 'h': 0, 'e': 0, 'ip': 0} + # final_wp = None + # final_lp = None + # final_holds = [] + # final_sv = None + # final_bsv = [] + # final_doubles = [] + # final_triples = [] + # final_homeruns = [] + # final_sbs = [] + # final_cscs = [] + # + # # Read batting stats + # for group in [away_bats, home_bats]: + # for line in group: + # if line[0]: + # # Dictionary to hold data to be passed to db for BatStat model + # this_batter = {'season': current['season']} + # + # # Keeping count so we can add stat name and data from sheet into this_batter dict + # for count in range(len(bat_stats)): + # if line[count] != '' and line[count] != '#REF' and line[count] != 0: + # this_batter[bat_stats[count]] = line[count] + # + # # Add this_batter to collection new_bat_stats + # try: + # this_batter['player_id'] = self.player_list[line[0].lower()] + # this_batter['team_id'] = away_team['id'] if line[1].lower() == away_team['abbrev'].lower() \ + # else home_team['id'] + # # Check for pitcher int in position + # if this_batter['pos'] in pit_nums: + # this_batter['pos'] = 'P' + # this_bat_stat = BatStat.parse_obj(this_batter) + # new_bat_stats.append(this_bat_stat.dict()) + # + # # Get stats for news-ticker + # if this_batter['team_id'] == away_team['id']: + # final_box_away['r'] += this_bat_stat.run + # final_box_away['h'] += this_bat_stat.hit + # final_box_away['e'] += this_bat_stat.error + # else: + # final_box_home['r'] += this_bat_stat.run + # final_box_home['h'] += this_bat_stat.hit + # final_box_home['e'] += this_bat_stat.error + # + # if this_bat_stat.double: + # final_doubles.append((this_batter['player_id'], this_bat_stat.double)) + # if this_bat_stat.triple: + # final_triples.append((this_batter['player_id'], this_bat_stat.triple)) + # if this_bat_stat.hr: + # final_homeruns.append((this_batter['player_id'], this_bat_stat.hr)) + # if this_bat_stat.sb: + # final_sbs.append((this_batter['player_id'], this_bat_stat.sb)) + # if this_bat_stat.csc: + # final_cscs.append((this_batter['player_id'], this_bat_stat.csc)) + # + # except Exception as e: + # errors.append(f'{line[0]}: {e}') + # + # # Read pitching stats + # for group in [away_arms, home_arms]: + # for line in group: + # if line[0]: + # # Dictionary to hold data for PitStat model + # this_pitcher = {'season': current['season']} + # + # # Keeping count so we can add stat name and data from sheet into this_pitcher dict + # for count in range(len(pit_stats)): + # if line[count] != '' and line[count] != '#REF' and line[count] != 0: + # this_pitcher[pit_stats[count]] = line[count] + # + # # Add this_pitcher to collection new_pit_stats + # try: + # this_pitcher['player_id'] = self.player_list[line[0].lower()] + # this_pitcher['team_id'] = away_team['id'] if line[1].lower() == away_team['abbrev'].lower() \ + # else home_team['id'] + # this_pit_stat = PitStat.parse_obj(this_pitcher) + # + # # Update IP to an even third + # first_digit = f'{this_pit_stat.ip % 1}'[2] + # if first_digit == '0': + # this_pit_stat.ip = math.floor(this_pit_stat.ip) + # elif first_digit in ['1', '3']: + # this_pit_stat.ip = math.floor(this_pit_stat.ip) + (1/3) + # else: + # this_pit_stat.ip = math.floor(this_pit_stat.ip) + (2/3) + # + # new_pit_stats.append(this_pit_stat.dict()) + # + # # Get stats for news-ticker + # if this_pit_stat.win: + # final_wp = this_pit_stat.player_id + # if this_pit_stat.loss: + # final_lp = this_pit_stat.player_id + # if this_pit_stat.sv: + # final_sv = this_pit_stat.player_id + # if this_pit_stat.bsv: + # final_bsv.append(this_pit_stat.player_id) + # if this_pit_stat.hold: + # final_holds.append(this_pit_stat.player_id) + # if this_pitcher['team_id'] == away_team['id']: + # final_box_away['ip'] += this_pit_stat.ip + # else: + # final_box_home['ip'] += this_pit_stat.ip + # except Exception as e: + # errors.append(f'{line[0]}: {e}') + # + # # Error checks + # await interaction.edit_original_response( + # content='Just finished reading the scorecard. Now to look for all of your mistakes...' + # ) + # for line in new_bat_stats: + # b_counts['sbc'] += line['sbc'] + # b_counts['csc'] += line['csc'] + # b_counts['sb'] += line['sb'] + # b_counts['cs'] += line['cs'] + # b_counts['so'] += line['so'] + # b_counts['bb'] += line['bb'] + line['ibb'] + # b_counts['run'] += line['run'] + # b_counts['rbi'] += line['rbi'] + # b_counts['xba'] += line['xba'] + # b_counts['xbt'] += line['xbt'] + # b_counts['raa'] += line['raa'] + # b_counts['rto'] += line['rto'] + # if line['pos'] not in positions: + # errors.append(f'{line["pos"]} not a valid position') + # for line in new_pit_stats: + # logging.info(f'line: {line}') + # p_counts['gs'] += line['gs'] + # p_counts['win'] += line['win'] + # p_counts['loss'] += line['loss'] + # p_counts['bb'] += line['bb'] + # p_counts['so'] += line['so'] + # p_counts['run'] += line['run'] + # p_counts['erun'] += line['erun'] + # p_counts['ir'] += line['ir'] + # p_counts['irs'] += line['irs'] + # + # if b_counts['sbc'] > b_counts['sb'] + b_counts['cs']: + # errors.append(f'There are {b_counts["sbc"]} stolen base attempts (SBa), but {b_counts["sb"]} SB and ' + # f'{b_counts["cs"]} CS.') + # if b_counts['csc'] > b_counts['cs']: + # errors.append(f'There are {b_counts["sbc"]} catcher caught stealings (CSc), but ' + # f'{b_counts["cs"]} baserunner CS.') + # if b_counts['so'] != p_counts['so']: + # errors.append(f'There are {b_counts["so"]} batter strikeouts, but {p_counts["so"]} pitcher strikeouts.') + # if b_counts['bb'] != p_counts['bb']: + # errors.append(f'There are {b_counts["bb"]} batter walks, but {p_counts["bb"]} pitcher.') + # if b_counts['run'] != p_counts['run']: + # errors.append(f'There are {b_counts["run"]} batter runs, but {p_counts["run"]} pitcher runs.') + # if b_counts['rbi'] > b_counts['run']: + # errors.append(f'There are {b_counts["rbi"]} runs batted in, but {b_counts["run"]} runs scored.') + # if b_counts['rto'] > b_counts['raa']: + # errors.append(f'There are {b_counts["rto"]} runners thrown out, but {b_counts["raa"]} runner ' + # f'advance attempts.') + # if b_counts['xbt'] > b_counts['xba']: + # errors.append(f'There are {b_counts["xbt"]} extra bases taken, but {b_counts["xba"]} extra ' + # f'base attempts.') + # if p_counts['erun'] > p_counts['run']: + # errors.append(f'There are {p_counts["erun"]} earned runs and {p_counts["run"]} total runs. ') + # if p_counts['gs'] != 2: + # errors.append(f'There should be 2 GS, but I see {p_counts["gs"]} of them.') + # if p_counts['win'] != 1: + # errors.append(f'There should be 1 W, but I see {p_counts["win"]} of them.') + # if p_counts['loss'] != 1: + # errors.append(f'There should be 1 L, but I see {p_counts["loss"]} of them.') + # if p_counts['irs'] > p_counts['ir']: + # errors.append(f'There are {p_counts["irs"]} inherited runners scored and {p_counts["ir"]} ' + # f'inherited runners.') + # + # # Post errors, if any, or post stats to db + # if len(errors) > 0: + # error_message = '\n- '.join(errors) + # await interaction.edit_original_response( + # content=f'The following errors were found in your **wk{week_num}g{game_num}** scorecard. ' + # f'Please resolve them and resubmit - thanks!\n\n- {error_message}' + # ) + # logging.error(f'Scorecard errors: {error_message}') # return + # else: + # bat_conf = await post_battingstats(new_bat_stats) + # pit_conf = await post_pitchingstats(new_pit_stats) # - # this_game = { - # 'season': current['season'], + # if bat_conf and pit_conf: + # await interaction.edit_original_response( + # content=f'You did it! I just logged the stats for **wk{week_num}g{game_num}**' + # ) + # + # # Update last games for pitchers + # for x in new_pit_stats: + # this_pitcher = await get_one_player(x["player_id"]) + # game_string = f'{float(x["ip"]):.2}IP w{x["week"]}g{x["game"]}' + # await patch_player(this_pitcher['id'], last_game=game_string, last_game2=this_pitcher['last_game']) + # else: + # await interaction.edit_original_response( + # content='So the stats looked okay, but I had an accident when I tried to post them. They ' + # 'did not go through.' + # ) + # + # # Post scorecard to weekly archive + # card_url = f'<{SBA_BASE_URL}/scorecards/?season={current["season"]}&week={week_num}&game={game_num}' \ + # f'&away_abbrev={away_team["abbrev"]}&home_abbrev={home_team["abbrev"]}>' + # # try: + # # archive_channel = get_channel(interaction, name=f'week-{week_num}-archive') + # # logging.info(f'archive_channel: {archive_channel}') + # # if not archive_channel: + # # archive_channel = await create_channel( + # # interaction, + # # channel_name=f'week-{week_num}-archive', + # # category_name=f'Season {current["season"]} Archives', + # # read_send_roles=[get_role(interaction, 'Gameplay Bots')] + # # ) + # # + # # await archive_channel.send( + # # f'Game {game_num}: **{away_team["sname"]}** {await team_emoji(interaction, away_team)} ' + # # f'{final_box_away["r"]} @ {final_box_home["r"]} ' + # # f'{await team_emoji(interaction, home_team)} **{home_team["sname"]}**\n{card_url}') + # # except Exception as e: + # # await interaction.edit_original_response( + # # content='Ope. I wasn\'t able to post this to the archive channel.' + # # ) + # + # # Post box score to news-ticker + # + # extras = '' + # if final_box_home['ip'] > 9: + # extras = f' F/{math.floor(final_box_home["ip"])}' + # embed = get_team_embed( + # f'{away_team["sname"]} {final_box_away["r"]} @ ' + # f'{final_box_home["r"]} {home_team["sname"]}{extras}', + # team=away_team if final_box_away['r'] > final_box_home['r'] else home_team + # ) + # embed.description = f'Week {week_num} | Game {game_num}' + # + # embed.add_field( + # name='Box Score', + # value=f'```\n' + # f'Team | R | H | E |\n' + # f'{away_team["abbrev"]: <4} | {final_box_away["r"]: >2} | {final_box_away["h"]: >2} | ' + # f'{final_box_away["e"]: >2} |\n' + # f'{home_team["abbrev"]: <4} | {final_box_home["r"]: >2} | {final_box_home["h"]: >2} | ' + # f'{final_box_home["e"]: >2} |\n' + # f'```', + # inline=False + # ) + # + # wp = await get_one_player(final_wp) + # lp = await get_one_player(final_lp) + # if final_sv: + # sv = await get_one_player(final_sv) + # else: + # sv = None + # holds = [] + # bsvs = [] + # for x in final_holds: + # holds.append(await get_one_player(x)) + # for x in final_bsv: + # bsvs.append(await get_one_player(x)) + # + # pitching_string = f'WP: {wp["name"]}\n' \ + # f'LP: {lp["name"]}\n' \ + # f'{"HD: " if len(holds) > 0 else ""}' + # + # hold_string = '' + # count = 1 + # for x in holds: + # hold_string += f'{x["name"]}' + # if count < len(holds): + # hold_string += ', ' + # elif len(holds) > 0: + # hold_string += '\n' + # count += 1 + # pitching_string += hold_string + # + # if sv: + # pitching_string += f'SV: {sv["name"]}' + # + # embed.add_field(name='Pitching', value=pitching_string, inline=False) + # + # batting_string = '' + # count = 1 + # if len(final_doubles) > 0: + # batting_string += '2B: ' + # + # for x in final_doubles: + # player = await get_one_player(x[0]) + # batting_string += f'{player["name"]}' + # + # if x[1] > 1: + # batting_string += f' {x[1]}' + # + # if count < len(final_doubles): + # batting_string += ', ' + # else: + # batting_string += '\n' + # count += 1 + # + # count = 1 + # if len(final_triples) > 0: + # batting_string += '3B: ' + # + # for x in final_triples: + # player = await get_one_player(x[0]) + # batting_string += f'{player["name"]}' + # + # if x[1] > 1: + # batting_string += f' {x[1]}' + # + # if count < len(final_triples): + # batting_string += ', ' + # else: + # batting_string += '\n' + # count += 1 + # + # count = 1 + # if len(final_homeruns) > 0: + # batting_string += 'HR: ' + # + # for x in final_homeruns: + # player = await get_one_player(x[0]) + # batting_string += f'{player["name"]}' + # + # if x[1] > 1: + # batting_string += f' {x[1]}' + # + # if count < len(final_homeruns): + # batting_string += ', ' + # else: + # batting_string += '\n' + # count += 1 + # + # if len(batting_string) > 0: + # embed.add_field(name='Batting', value=batting_string, inline=False) + # + # baserunning_string = '' + # count = 1 + # if len(final_sbs) > 0: + # baserunning_string += 'SB: ' + # + # for x in final_sbs: + # player = await get_one_player(x[0]) + # baserunning_string += f'{player["name"]}' + # + # if x[1] > 1: + # baserunning_string += f' {x[1]}' + # + # if count < len(final_sbs): + # baserunning_string += ', ' + # else: + # baserunning_string += '\n' + # count += 1 + # + # count = 1 + # if len(final_cscs) > 0: + # baserunning_string += 'CSc: ' + # + # for x in final_cscs: + # player = await get_one_player(x[0]) + # baserunning_string += f'{player["name"]}' + # + # if x[1] > 1: + # baserunning_string += f' {x[1]}' + # + # if count < len(final_cscs): + # baserunning_string += ', ' + # else: + # baserunning_string += '\n' + # count += 1 + # + # if len(baserunning_string) > 0: + # embed.add_field(name='Baserunning', value=baserunning_string, inline=False) + # + # embed.add_field( + # name='Scorecard', + # value=f'[Website]({card_url}) / [Sheets]({sheet_url})' + # ) + # embed.set_footer(text='Please share the highlights!') + # + # await send_to_channel( + # self.bot, + # 'sba-network-news', + # content=None, + # embed=embed + # ) + # + # result = { # 'week': week_num, - # 'game_num': game_num, + # 'game': game_num, # 'away_team_id': away_team['id'], - # 'home_team_id': home_team['id'] + # 'home_team_id': home_team['id'], + # 'away_score': final_box_away["r"], + # 'home_score': final_box_home["r"], + # 'season': current['season'], + # 'scorecard_url': sheet_url # } - # - # await ctx.send('What a pain in my balls. Let\'s start by deleting the batting stats.') - # async with ctx.typing(): - # if await delete_battingstats(this_game): - # await ctx.send('Batting stats are gone - now the pitching stats.') - # - # async with ctx.typing(): - # if await delete_pitchingstats(this_game): - # await ctx.send('Pitching stats are gone - now to recalculate everybody\'s season batting lines.') - # - # async with ctx.typing(): - # if await recalc_batting_seasons(current['season'], away_team['id']): - # if await recalc_batting_seasons(current['season'], home_team['id']): - # await ctx.send('Batting lines are done - now to recalculate pitching lines.') - # - # async with ctx.typing(): - # if await recalc_pitching_seasons(current['season'], away_team['id']): - # if await recalc_pitching_seasons(current['season'], home_team['id']): - # await ctx.send('Pitching lines are done - now to recalculate fielding lines.') - # - # async with ctx.typing(): - # if await recalc_fielding_seasons(current['season'], away_team['id']): - # await recalc_fielding_seasons(current['season'], home_team['id']) - # - # await ctx.send(f'All done. Don\'t suck next time {await get_emoji(ctx, "lakemonsters")}') + # if await db_post('results', payload={'results': [result]}): + # update = await interaction.channel.send('I\'m tallying standings now...') + # if await db_post(f'standings/s{current["season"]}/recalculate'): + # await update.delete() @app_commands.command(name='branding', description='Update your team branding') @app_commands.guilds(discord.Object(id=os.environ.get('GUILD_ID'))) @@ -2194,9 +1628,10 @@ class Players(commands.Cog): async def branding_slash_command( self, interaction: discord.Interaction, color_hex: str = None, team_image_url: str = None, mil_color_hex: str = None, mil_team_image_url: str = None, dice_color_hex: str = None): - current = await get_current() + await interaction.response.defer() + current = await db_get('current') team = await get_team_by_owner(current['season'], interaction.user.id) - mil_team = await get_one_team(f'{team["abbrev"]}MiL', current['season']) + mil_team = await get_team_by_abbrev(f'{team["abbrev"]}MiL', current['season']) team_role = get_team_role(interaction, team) errors = [] show_mil = False @@ -2209,21 +1644,23 @@ class Players(commands.Cog): return if color_hex is not None: + color_int = int(color_hex, 16) try: - color_int = int(color_hex, 16) await team_role.edit(colour=color_int) - await patch_team(team, color=color_hex) except Exception as e: logging.info(f'Error setting {team["sname"]} color to {color_hex}') errors.append(f'- Error setting {team["sname"]} color to {color_hex}:\n{e}\n\n') + team['color'] = color_hex + await db_patch('teams', object_id=team['id'], params=[('color', color_hex)]) if team_image_url is not None: if requests.get(team_image_url, timeout=0.5).status_code != 200: errors.append(f'- I wasn\'t able to pull that image. Was it a public URL?\n\n') else: - await patch_team(team, thumbnail=team_image_url) + team['thumbnail'] = team_image_url + await db_patch('teams', object_id=team['id'], params=[('thumbnail', team_image_url)]) if mil_color_hex is not None: try: - await patch_team(mil_team, color=color_hex) + await db_patch('teams', object_id=mil_team['id'], params=[('color', color_hex)]) show_mil = True except Exception as e: logging.info(f'Error setting {team["sname"]} color to {color_hex}') @@ -2232,17 +1669,17 @@ class Players(commands.Cog): if requests.get(mil_team_image_url, timeout=0.5).status_code != 200: errors.append(f'- I wasn\'t able to pull that image. Was it a public URL?\n\n') else: - await patch_team(mil_team, thumbnail=mil_team_image_url) + await db_patch('teams', object_id=mil_team['id'], params=[('thumbnail', mil_team_image_url)]) show_mil = True if dice_color_hex is not None: try: - await patch_team(team, dice_color=dice_color_hex) + await db_patch('teams', object_id=team['id'], params=[('dice_color', dice_color_hex)]) show_dice = True except Exception as e: logging.info(f'Error setting {team["sname"]} color to {color_hex}') errors.append(f'- Error setting {team["sname"]} color to {color_hex}:\n{e}\n\n') - team = await get_one_team(team['id'], season=current['season']) + team = await db_get('teams', object_id=team['id']) major_embed = get_team_embed(f'{team["lname"]} Test', team=team) major_embed.add_field( name='Little Test Data', @@ -2251,7 +1688,7 @@ class Players(commands.Cog): embeds = [major_embed] if show_mil: - mil_team = await get_one_team(mil_team['id']) + mil_team = await db_get('teams', object_id=mil_team['id']) mil_embed = get_team_embed(f'{mil_team["lname"]} Test', team=mil_team) mil_embed.add_field( name='Little Test Data', @@ -2271,12 +1708,12 @@ class Players(commands.Cog): logging.info(f'done with embed: {dice_embed}') embeds.append(dice_embed) - await interaction.response.send_message(content=None, embeds=embeds) + await interaction.edit_original_response(content=None, embeds=embeds) # @commands.command(name='setcolor', help='Set team color') # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) # async def set_color_command(self, ctx, color_code): - # current = await get_current() + # current = await db_get('current') # team = await get_team_by_owner(current['season'], ctx.author.id) # team_role = get_team_role(ctx, team) # color_int = int(color_code, 16) @@ -2299,7 +1736,7 @@ class Players(commands.Cog): # @commands.command(name='setthumbnail', help='Set team pic') # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) # async def set_thumbnail_command(self, ctx, thumbnail_url): - # current = await get_current() + # current = await db_get('current') # team = await get_team_by_owner(current['season'], ctx.author.id) # team_role = get_team_role(ctx, team) # @@ -2324,7 +1761,7 @@ class Players(commands.Cog): # @commands.command(name='setminorthumbnail', help='Set minor team pic') # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) # async def set_minor_pic_command(self, ctx, thumbnail_url): - # current = await get_current() + # current = await db_get('current') # team = await get_team_by_owner(current['season'], ctx.author.id) # minor_team = await get_one_team(team['id'] + 2) # @@ -2348,7 +1785,7 @@ class Players(commands.Cog): # @commands.command(name='setminorcolor', help='Set minor team color') # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) # async def set_minor_color_command(self, ctx, color_code): - # current = await get_current() + # current = await db_get('current') # team = await get_team_by_owner(current['season'], ctx.author.id) # minor_team = await get_one_team(team['id'] + 2) # @@ -2370,7 +1807,7 @@ class Players(commands.Cog): # @commands.command(name='setdicecolor', help='Set dice embed color') # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) # async def set_dice_color_command(self, ctx, color_code): - # current = await get_current() + # current = await db_get('current') # team = await get_team_by_owner(current['season'], ctx.author.id) # # await patch_team(team, dice_color=color_code) @@ -2388,7 +1825,7 @@ class Players(commands.Cog): async def picks_command(self, ctx, *team_abbrev): await ctx.send('Go away.') return - current = await get_current() + current = await db_get('current') if team_abbrev: team = await get_one_team(team_abbrev[0]) @@ -2423,7 +1860,7 @@ class Players(commands.Cog): # @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) # async def fix_score_command( # self, ctx, away_team, away_score: int, home_team, home_score: int, week_num: int, game_num: int): - # current = await get_current() + # current = await db_get('current') # week_games = await get_results(current['season'], away_abbrev=away_team, home_abbrev=home_team, week=week_num) # this_game = None # @@ -2461,172 +1898,172 @@ class Players(commands.Cog): # f'{get_team_role(ctx, this_game["hometeam"]).mention}') # await ctx.send(random_conf_gif()) - @commands.command(name='newaward', help='Grant award') - @commands.has_any_role('Awards Team', 'Da Commish') - async def new_award_command(self, ctx, *, award_name): - # f'{"In-Season" if in_or_off.lower() == "in" else "Off-Season"}' - current = await get_current() - award = { - 'name': award_name, - 'season': None, - 'timing': None, - 'manager1': None, - 'manager2': None, - 'player': None, - 'team': None, - 'image': None, - 'invalid': False - } - - async def add_recipient(search_string): - try: - this_team = await get_one_team(search_string, season=award['season']) - award['team'] = this_team - except ValueError: - try: - this_manager = await get_one_manager(search_string) - if not award['manager1']: - award['manager1'] = this_manager - else: - award['manager2'] = this_manager - except ValueError: - try: - search_name = await fuzzy_player_search( - ctx, ctx.channel, self.bot, search_string, self.player_list) - this_player = await get_one_player(search_name, season=award['season']) - award['player'] = this_player - except ValueError: - try: - this_player = await get_one_player(search_string, season=award['season']) - award['player'] = this_player - except ValueError: - await ctx.send(f'I do not recognize **{search_string}**. Will you check the spelling and ' - f'try again?') - - def get_embed(): - this_embed = discord.Embed(title=award['name']) - this_embed.description = f'{award["timing"]} - S{award["season"]}' - if award['manager1']: - this_embed.add_field(name='Manager', value=award['manager1']) - if award['manager2']: - this_embed.add_field(name='Manager', value=award['manager2']) - if award['player']: - this_embed.add_field(name='Player', value=f'{award["player"]["name"]}') - if award['team']: - this_embed.add_field(name='Team', value=f'{award["team"]["lname"]}') - if award['image']: - try: - this_embed.set_image(url=award['image']) - except: - award['invalid'] = True - this_embed.add_field(name='Image', value='Invalid URL') - return this_embed - - prompt = f'Is this for season {current["season"]}?' - this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45) - resp = await this_q.ask([ctx.author]) - - if resp is None: - await ctx.send('Think on it. Get back to me.') - return - elif resp: - award['season'] = current['season'] - else: - prompt = 'Please enter the season for this award.' - this_q = Question(self.bot, ctx.channel, prompt, 'int', timeout=45) - resp = await this_q.ask([ctx.author]) - - if not resp: - await ctx.send('Think on it. Get back to me.') - return - else: - award['season'] = resp - - prompt = f'Is this an In-Season award (as opposed to off-season)?' - this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45) - resp = await this_q.ask([ctx.author]) - - if resp is None: - await ctx.send('Think on it. Get back to me.') - return - elif resp: - award['timing'] = 'In-Season' - else: - award['timing'] = 'Off-Season' - await ctx.send('Got it - I\'ll put this down as an Off-Season award') - - prompt = 'Is this the start you wanted?' - this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45, embed=get_embed()) - resp = await this_q.ask([ctx.author]) - - if not resp: - await ctx.send('No worries - run `!newaward Award_Name` again to rename it.') - return - - # Get team/player/managers - while True: - prompt = 'Please enter the team abbreviation, player name, or manager name of the recipient.' - this_q = Question(self.bot, ctx.channel, prompt, 'text', timeout=45) - resp = await this_q.ask([ctx.author]) - - if resp is None: - await ctx.send('You think on it and hit me up when you\'re ready.') - return - else: - await add_recipient(resp) - - await ctx.send('Here is the current award', embed=get_embed()) - - prompt = 'Would you like to (re)enter a recipient?' - this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45) - resp = await this_q.ask([ctx.author]) - - if resp is None: - await ctx.send('We can hold off on this for now. Let me know when you\'re ready to start again.') - return - elif not resp: - break - - # Get image URL - while True: - prompt = 'Would you like to (re)enter an image URL for this award?' - this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45, embed=get_embed()) - resp = await this_q.ask([ctx.author]) - - if not resp: - break - else: - prompt = 'Please enter the image URL.' - this_q = Question(self.bot, ctx.channel, prompt, 'url', timeout=45) - resp = await this_q.ask([ctx.author]) - - if resp is None: - await ctx.send('Okey doke, nevermind. I get it. It\'s fine. We only did all this work for nothing. ' - 'Let me know when you want to start again.') - return - elif not resp: - await ctx.send(f'**{resp}** is not a valid URL.') - else: - award['image'] = resp - - prompt = 'Would you like to submit this award?' - this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45, embed=get_embed()) - resp = await this_q.ask([ctx.author]) - - if not resp: - await ctx.send('Really? After all the ti- nevermind. Fine. Kill it. It\'s over. Bye.') - return - else: - await post_award(award) - await ctx.send(random_conf_gif()) - - @commands.command(name='record', help='Record through week num') - async def record_command(self, ctx, team_abbrev, week_num: int): - this_team = await get_one_team(team_abbrev) - this_record = await get_team_record(this_team, week_num) - - await ctx.send(f'The {this_team["sname"]} were ({this_record["w"]}-{this_record["l"]}) through ' - f'week {week_num}.') + # @commands.command(name='newaward', help='Grant award') + # @commands.has_any_role('Awards Team', 'Da Commish') + # async def new_award_command(self, ctx, *, award_name): + # # f'{"In-Season" if in_or_off.lower() == "in" else "Off-Season"}' + # current = await db_get('current') + # award = { + # 'name': award_name, + # 'season': None, + # 'timing': None, + # 'manager1': None, + # 'manager2': None, + # 'player': None, + # 'team': None, + # 'image': None, + # 'invalid': False + # } + # + # async def add_recipient(search_string): + # try: + # this_team = await get_one_team(search_string, season=award['season']) + # award['team'] = this_team + # except ValueError: + # try: + # this_manager = await get_one_manager(search_string) + # if not award['manager1']: + # award['manager1'] = this_manager + # else: + # award['manager2'] = this_manager + # except ValueError: + # try: + # search_name = await fuzzy_player_search( + # ctx, ctx.channel, self.bot, search_string, self.player_list) + # this_player = await get_one_player(search_name, season=award['season']) + # award['player'] = this_player + # except ValueError: + # try: + # this_player = await get_one_player(search_string, season=award['season']) + # award['player'] = this_player + # except ValueError: + # await ctx.send(f'I do not recognize **{search_string}**. Will you check the spelling and ' + # f'try again?') + # + # def get_embed(): + # this_embed = discord.Embed(title=award['name']) + # this_embed.description = f'{award["timing"]} - S{award["season"]}' + # if award['manager1']: + # this_embed.add_field(name='Manager', value=award['manager1']) + # if award['manager2']: + # this_embed.add_field(name='Manager', value=award['manager2']) + # if award['player']: + # this_embed.add_field(name='Player', value=f'{award["player"]["name"]}') + # if award['team']: + # this_embed.add_field(name='Team', value=f'{award["team"]["lname"]}') + # if award['image']: + # try: + # this_embed.set_image(url=award['image']) + # except: + # award['invalid'] = True + # this_embed.add_field(name='Image', value='Invalid URL') + # return this_embed + # + # prompt = f'Is this for season {current["season"]}?' + # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45) + # resp = await this_q.ask([ctx.author]) + # + # if resp is None: + # await ctx.send('Think on it. Get back to me.') + # return + # elif resp: + # award['season'] = current['season'] + # else: + # prompt = 'Please enter the season for this award.' + # this_q = Question(self.bot, ctx.channel, prompt, 'int', timeout=45) + # resp = await this_q.ask([ctx.author]) + # + # if not resp: + # await ctx.send('Think on it. Get back to me.') + # return + # else: + # award['season'] = resp + # + # prompt = f'Is this an In-Season award (as opposed to off-season)?' + # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45) + # resp = await this_q.ask([ctx.author]) + # + # if resp is None: + # await ctx.send('Think on it. Get back to me.') + # return + # elif resp: + # award['timing'] = 'In-Season' + # else: + # award['timing'] = 'Off-Season' + # await ctx.send('Got it - I\'ll put this down as an Off-Season award') + # + # prompt = 'Is this the start you wanted?' + # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45, embed=get_embed()) + # resp = await this_q.ask([ctx.author]) + # + # if not resp: + # await ctx.send('No worries - run `!newaward Award_Name` again to rename it.') + # return + # + # # Get team/player/managers + # while True: + # prompt = 'Please enter the team abbreviation, player name, or manager name of the recipient.' + # this_q = Question(self.bot, ctx.channel, prompt, 'text', timeout=45) + # resp = await this_q.ask([ctx.author]) + # + # if resp is None: + # await ctx.send('You think on it and hit me up when you\'re ready.') + # return + # else: + # await add_recipient(resp) + # + # await ctx.send('Here is the current award', embed=get_embed()) + # + # prompt = 'Would you like to (re)enter a recipient?' + # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45) + # resp = await this_q.ask([ctx.author]) + # + # if resp is None: + # await ctx.send('We can hold off on this for now. Let me know when you\'re ready to start again.') + # return + # elif not resp: + # break + # + # # Get image URL + # while True: + # prompt = 'Would you like to (re)enter an image URL for this award?' + # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45, embed=get_embed()) + # resp = await this_q.ask([ctx.author]) + # + # if not resp: + # break + # else: + # prompt = 'Please enter the image URL.' + # this_q = Question(self.bot, ctx.channel, prompt, 'url', timeout=45) + # resp = await this_q.ask([ctx.author]) + # + # if resp is None: + # await ctx.send('Okey doke, nevermind. I get it. It\'s fine. We only did all this work for nothing. ' + # 'Let me know when you want to start again.') + # return + # elif not resp: + # await ctx.send(f'**{resp}** is not a valid URL.') + # else: + # award['image'] = resp + # + # prompt = 'Would you like to submit this award?' + # this_q = Question(self.bot, ctx.channel, prompt, 'yesno', timeout=45, embed=get_embed()) + # resp = await this_q.ask([ctx.author]) + # + # if not resp: + # await ctx.send('Really? After all the ti- nevermind. Fine. Kill it. It\'s over. Bye.') + # return + # else: + # await post_award(award) + # await ctx.send(random_conf_gif()) + # + # @commands.command(name='record', help='Record through week num') + # async def record_command(self, ctx, team_abbrev, week_num: int): + # this_team = await get_one_team(team_abbrev) + # this_record = await get_team_record(this_team, week_num) + # + # await ctx.send(f'The {this_team["sname"]} were ({this_record["w"]}-{this_record["l"]}) through ' + # f'week {week_num}.') @commands.command(name='vc', aliases=['voice', 'gameplay'], help='Get voice channel') @commands.has_any_role(SBA_PLAYERS_ROLE_NAME, 'Paper Dynasty Players') @@ -2660,7 +2097,7 @@ class Players(commands.Cog): @commands.command(name='private', help='Get private vc') @commands.has_any_role(SBA_PLAYERS_ROLE_NAME) async def private_vc_command(self, ctx): - current = await get_current() + current = await db_get('current') this_team = await get_team_by_owner(current['season'], ctx.author.id) async def get_other_team(): @@ -2672,7 +2109,7 @@ class Players(commands.Cog): await ctx.send('You keep thinking about it and hit me up later if you figure it out.') return None else: - other_team = await get_one_team(resp) + other_team = await get_team_by_abbrev(resp, current['season']) if not other_team: await ctx.send(f'What\'s a **{resp}**? If you could go ahead and run this command again, that\'d ' f'be great.') @@ -2684,18 +2121,17 @@ class Players(commands.Cog): await ctx.send('Hmm...I can\'t find your team. Are you from around here?') return - try: - this_matchup = await get_one_schedule( - season=current['season'], - team_abbrev1=this_team['abbrev'], - week=current['week'] - ) - except ValueError as e: + s_query = await db_get('schedules', params=[ + ('season', current['season']), ('team_abbrev', this_team['abbrev']), ('week_start', current['week']), + ('week_end', current['week']), ('short_output', False) + ]) + if s_query['count'] == 0: other_team = await get_other_team() if not other_team: - return + await ctx.send(f'Idk who you are playing this week.') channel_name = f'{this_team["abbrev"]} vs {other_team["abbrev"]} Muted' else: + this_matchup = s_query['schedules'][0] if this_team == this_matchup['awayteam']: other_team = this_matchup['hometeam'] else: @@ -2710,17 +2146,21 @@ class Players(commands.Cog): await ctx.send('Fine. I bet they didn\'t wanna talk to you anyway.') return elif not resp: - other_team = await get_other_team() - if not other_team: - return channel_name = f'{this_team["abbrev"]} vs {other_team["abbrev"]}' + logging.info(f'getting roles') this_team_role = discord.utils.get(ctx.guild.roles, name=f'{this_team["lname"]}') other_team_role = discord.utils.get(ctx.guild.roles, name=f'{other_team["lname"]}') + if None in [this_team_role, other_team_role]: + await ctx.send(f'Tell Cal that we\'re missing a team role to create this channel.') + return + + logging.info(f'getting overwrites') overwrites = {ctx.guild.default_role: discord.PermissionOverwrite(speak=False), this_team_role: discord.PermissionOverwrite(speak=True), other_team_role: discord.PermissionOverwrite(speak=True)} + logging.info(f'creating channel') this_vc = await ctx.guild.create_voice_channel( channel_name, overwrites=overwrites, @@ -2742,16 +2182,20 @@ class Players(commands.Cog): await ctx.send('Not in season 6 chat, dumbass.') return - current = await get_current() + current = await db_get('current') this_team = await get_team_by_owner(current['season'], ctx.author.id) if not this_team: await ctx.send('Hmm...I can\'t find your team. Are you from around here?') return - player = await get_one_player( - await fuzzy_player_search(ctx, ctx.channel, self.bot, player_name, self.player_list.keys()) + p_name = await fuzzy_player_search( + ctx, ctx.channel, self.bot, player_name, self.player_list.keys(), author=ctx.author ) + player = await get_player_by_name(current['season'], p_name) + if player is None: + await ctx.send(random_gif('it didn\'t work')) + return player_embed = await get_player_embed(player, current) player_embed.set_thumbnail(url=url) @@ -2763,7 +2207,8 @@ class Players(commands.Cog): await ctx.send('That\'s okay. It wasn\'t a very good picture anyway.') return else: - await patch_player(player['id'], headshot=url) + player['headshot'] = url + await patch_player(player) await ctx.send(random_conf_word()) @commands.command(name='fancycard', aliases=['fc'], help='Set vanity card') @@ -2773,16 +2218,20 @@ class Players(commands.Cog): await ctx.send('Not in season 6 chat, dumbass.') return - current = await get_current() + current = await db_get('current') this_team = await get_team_by_owner(current['season'], ctx.author.id) if not this_team: await ctx.send('Hmm...I can\'t find your team. Are you from around here?') return - player = await get_one_player( - await fuzzy_player_search(ctx, ctx.channel, self.bot, player_name, self.player_list.keys()) + p_name = await fuzzy_player_search( + ctx, ctx.channel, self.bot, player_name, self.player_list.keys(), author=ctx.author ) + player = await get_player_by_name(current['season'], p_name) + if player is None: + await ctx.send(random_gif('it didn\'t work')) + return player_embed = await get_player_embed(player, current) player_embed.set_thumbnail(url=url) @@ -2794,7 +2243,8 @@ class Players(commands.Cog): await ctx.send('That\'s okay. It wasn\'t a very good picture anyway.') return else: - await patch_player(player['id'], vanity_card=url) + player['vanity_card'] = url + await patch_player(player) await ctx.send(random_conf_word()) @commands.command(name='getfc', help='Get last season vanity card') @@ -2804,31 +2254,29 @@ class Players(commands.Cog): await ctx.send('Not in season 5 chat, dumbass.') return - current = await get_current() + current = await db_get('current') this_team = await get_team_by_owner(current['season'], ctx.author.id) if not this_team: await ctx.send('Hmm...I can\'t find your team. Are you from around here?') return - player = await get_one_player( - await fuzzy_player_search(ctx, ctx.channel, self.bot, player_name, self.player_list.keys()) + p_name = await fuzzy_player_search( + ctx, ctx.channel, self.bot, player_name, self.player_list.keys(), author=ctx.author ) + player = await get_player_by_name(current['season'], p_name) - old_player = await get_one_player(player["name"], season=current["season"]-1) - await patch_player( - pid=player["id"], - vanity_card=old_player["vanity_card"] - ) - player["vanity_card"] = old_player["vanity_card"] + p_query = await db_get('players', params=[('season', current['season'] - 1), ('name', p_name)]) + if p_query['count'] == 0: + await ctx.send(f'I could not find **{p_name}** from Season {current["season"] - 1}') + return + + player['vanity_card'] = p_query['players'][0]['vanity_card'] + await patch_player(player) player_embed = await get_player_embed(player, current) await ctx.send(content=None, embed=player_embed) - @commands.command(name='charts', aliases=['chart'], help='Run `/charts` for all charts') - async def legacy_charts_command(self, ctx): - await ctx.send(f'Run `/charts` for all charts') - @app_commands.command(name='charts') async def chart_command(self, interaction: discord.Interaction, chart_name: Literal[ 'rest', 'sac-bunt', 'squeeze-bunt', 'rob-hr', 'defense-matters', 'block-plate', 'hit-and-run', @@ -2880,29 +2328,14 @@ class Players(commands.Cog): embed.set_image(url=f'{SBA_BASE_URL}/static/images/pitbat/card-{card_num}.png') await ctx.send(content=None, embed=embed) - @app_commands.command(name='pitupdate', description='Mod: Update pitcher ratings') - @app_commands.checks.has_any_role('Da Commish') - async def pit_update_slash( - self, interaction: discord.Interaction, player_name: str, swar: float = None, injury_games: int = None): - player = await get_one_player( - await fuzzy_player_search(interaction, interaction.channel, self.bot, player_name, self.player_list), - ) - current = await get_current() - - await patch_player( - player['id'], - wara=swar if swar is not None else player['wara'], - injury_rating=f'{player["injury_rating"][:2]}{injury_games}' if injury_games is not None else player["injury_rating"] - ) - new_player = await get_one_player(player['id']) - await interaction.response.send_message(content=None, embed=await get_player_embed(new_player, current)) - @app_commands.command(name='keepers', description='Mod: Set team keepers') @app_commands.checks.has_any_role('Da Commish') async def set_keepers_slash( self, interaction: discord.Interaction, team_abbrev: str, keep1: str = None, keep2: str = None, keep3: str = None, keep4: str = None, keep5: str = None, keep6: str = None, keep7: str = None): - team = await get_one_team(team_abbrev) + await interaction.response.defer() + current = await db_get('current') + team = await get_team_by_abbrev(team_abbrev, current['season']) keepers = [] keeper_string = '' @@ -2921,21 +2354,23 @@ class Players(commands.Cog): for x in [keep1, keep2, keep3, keep4, keep5, keep6, keep7]: if x: - this_p = await get_one_player( - await fuzzy_player_search(interaction, interaction.channel, self.bot, x, self.player_list) + p_name = await fuzzy_player_search( + interaction, interaction.channel, self.bot, x, self.player_list.keys(), author=interaction.user ) + this_p = await get_player_by_name(current['season'], p_name) keepers.append(this_p) keeper_string += f'{get_pos_abbrev(this_p["pos_1"])} - {this_p["name"]} ({this_p["wara"]:.2f})\n' keeper_swar += this_p['wara'] await interaction.response.send_message(content=f'{team["sname"]} Keepers:\n{keeper_string}') - all_players = await db_get('players', api_ver=2, params=[('team_abbrev', team['abbrev'])]) + all_players = await db_get('players', api_ver=3, params=[('team_abbrev', team['abbrev'])]) logging.info(f'all_players: {all_players}') - fa = await get_one_team('FA') + fa = await get_team_by_abbrev('FA', current['season']) for y in all_players['players']: if y not in keepers: - await patch_player(y['id'], team_id=fa['id']) + y['team'] = fa + await patch_player(y) await interaction.channel.send( f'Just yeeted **{len(all_players["players"]) - len(keepers)}** players into the sun!' diff --git a/db_calls.py b/db_calls.py index 2c2d5b8..2d47e0b 100644 --- a/db_calls.py +++ b/db_calls.py @@ -25,7 +25,7 @@ def get_req_url(endpoint: str, api_ver: int = 3, object_id: int = None, params: return endpoint req_url = f'{DB_URL}/v{api_ver}/{endpoint}{"/" if object_id is not None else ""}{object_id if object_id is not None else ""}' - if params: + if params is not None: other_params = False for x in params: req_url += f'{param_char(other_params)}{x[0]}={x[1]}' @@ -74,15 +74,16 @@ async def db_get(endpoint: str, api_ver: int = 3, object_id: int = None, params: raise ValueError(f'DB: {resp.text}') -async def db_patch(endpoint: str, object_id: int, params: list, api_ver: int = 3, timeout: int = 3): +async def db_patch( + endpoint: str, object_id: int, params: list, api_ver: int = 3, timeout: int = 3, payload: dict = None): req_url = get_req_url(endpoint, api_ver=api_ver, object_id=object_id, params=params) - log_string = f'patch:\n{endpoint} {params}' + log_string = f'patch:\n{endpoint}/{object_id} {params}' logging.info(log_string) if master_debug else logging.debug(log_string) retries = 0 while True: try: - resp = requests.patch(req_url, headers=AUTH_TOKEN, timeout=timeout) + resp = requests.patch(req_url, json=payload, headers=AUTH_TOKEN, timeout=timeout) break except requests.Timeout as e: logging.error(f'Patch Timeout: {req_url} / retries: {retries} / timeout: {timeout}') @@ -167,6 +168,39 @@ async def db_delete(endpoint: str, object_id: int, api_ver: int = 3, timeout=3): raise ValueError(f'DB: {resp.text}') +async def get_team_by_abbrev(team_abbrev: str, season: int): + t_query = await db_get('teams', params=[('season', season), ('team_abbrev', team_abbrev)]) + if t_query['count'] == 0: + return None + else: + return t_query['teams'][0] + + +async def get_team_by_owner(season, owner_id): + params = [('active_only', True), ('season', season), ('owner_id', owner_id)] + resp = await db_get('teams', params=params) + if resp['count'] > 0: + return resp['teams'][0] + else: + return None + + +async def get_player_by_name(season: int, player_name: str): + p_query = await db_get('players', params=[('name', player_name), ('season', season)]) + if p_query['count'] == 0: + return None + return p_query['players'][0] + + +async def patch_player(this_player: dict): + this_player['team_id'] = this_player['team']['id'] + return await db_patch('players', object_id=this_player['id'], params=[], payload=this_player) + + +### +# TO BE DEPRECATED FUNCTIONS +### + async def get_current(season=None): if season is not None: params = [('season', season)] @@ -219,27 +253,6 @@ async def get_one_team(id_or_abbrev, season=None, is_pd=False, timeout=3): return await db_get('teams', object_id=id_or_abbrev, params=params) -async def get_team_by_owner(season, owner_id): - params = [('active_only', True), ('season', season), ('owner_id', owner_id)] - resp = await db_get('teams', params=params) - if resp['count'] > 0: - return resp['teams'][0] - else: - return None - - -async def post_team(team): - req_url = f'{DB_URL}/v1/teams' - payload = json.dumps(team) - - resp = requests.post(req_url, payload, headers=AUTH_TOKEN, timeout=3) - if resp.status_code == 200: - return resp.json() - else: - logging.warning(resp.text) - raise ValueError(f'DB: {resp.text}') - - async def get_team_roster(team, current_or_next): resp = requests.get(f'{DB_URL}/v1/teams/{team["id"]}/roster/{current_or_next}', timeout=3) if resp.status_code == 200: @@ -342,21 +355,6 @@ async def get_one_schedule( return return_val -async def post_players(all_players: list): - req_url = f'{DB_URL}/v1/players' - data = { - 'players': all_players - } - payload = json.dumps(data) - - resp = requests.post(req_url, payload, headers=AUTH_TOKEN, timeout=3) - if resp.status_code == 200: - return True - else: - logging.warning(resp.text) - raise ValueError(f'DB: {resp.text}') - - async def get_players(season, team_abbrev=None, sort=None, injured=None): req_url = f'{DB_URL}/v2/players?season={season}' if team_abbrev: @@ -377,148 +375,148 @@ async def get_one_player(id_or_name, season=None): return await db_get(req_url) -async def patch_player( - pid, name=None, wara=None, image=None, image2=None, team_id=None, season=None, pitcher_injury=None, pos_1=None, - pos_2=None, pos_3=None, pos_4=None, pos_5=None, pos_6=None, pos_7=None, pos_8=None, last_game=None, - last_game2=None, il_return=None, demotion_week=None, headshot=None, vanity_card=None, injury_rating=None): - """ - For values being patched to "None", set to False - - :param pid: - :param name: - :param wara: - :param image: - :param image2: - :param team_id: - :param season: - :param pitcher_injury: - :param pos_1: - :param pos_2: - :param pos_3: - :param pos_4: - :param pos_5: - :param pos_6: - :param pos_7: - :param pos_8: - :param last_game: - :param last_game2: - :param il_return: - :return: - """ - req_url = f'{DB_URL}/v2/players/{pid}' - other_params = False - if name is not None: - req_url += f'{param_char(other_params)}name={name}' - other_params = True - if wara is not None: - req_url += f'{param_char(other_params)}wara={wara}' - other_params = True - if image is not None: - req_url += f'{param_char(other_params)}image={image}' - other_params = True - if image2 is not None: - if not image2: - req_url += f'{param_char(other_params)}image2=False' - else: - req_url += f'{param_char(other_params)}image2={image2}' - other_params = True - if team_id is not None: - req_url += f'{param_char(other_params)}team_id={team_id}' - other_params = True - if season is not None: - req_url += f'{param_char(other_params)}season={season}' - other_params = True - if pitcher_injury is not None: - if not pitcher_injury: - req_url += f'{param_char(other_params)}pitcher_injury=False' - else: - req_url += f'{param_char(other_params)}pitcher_injury={pitcher_injury}' - other_params = True - if pos_1 is not None: - req_url += f'{param_char(other_params)}pos_1={pos_1}' - other_params = True - if pos_2 is not None: - if not pos_2: - req_url += f'{param_char(other_params)}pos_2=False' - else: - req_url += f'{param_char(other_params)}pos_2={pos_2}' - other_params = True - if pos_3 is not None: - if not pos_3: - req_url += f'{param_char(other_params)}pos_3=False' - else: - req_url += f'{param_char(other_params)}pos_3={pos_3}' - other_params = True - if pos_4 is not None: - if not pos_4: - req_url += f'{param_char(other_params)}pos_4=False' - else: - req_url += f'{param_char(other_params)}pos_4={pos_4}' - other_params = True - if pos_5 is not None: - if not pos_5: - req_url += f'{param_char(other_params)}pos_5=False' - else: - req_url += f'{param_char(other_params)}pos_5={pos_5}' - other_params = True - if pos_6 is not None: - if not pos_6: - req_url += f'{param_char(other_params)}pos_6=False' - else: - req_url += f'{param_char(other_params)}pos_6={pos_6}' - other_params = True - if pos_7 is not None: - if not pos_7: - req_url += f'{param_char(other_params)}pos_7=False' - else: - req_url += f'{param_char(other_params)}pos_7={pos_7}' - other_params = True - if pos_8 is not None: - if not pos_8: - req_url += f'{param_char(other_params)}pos_8=False' - else: - req_url += f'{param_char(other_params)}pos_8={pos_8}' - other_params = True - if last_game is not None: - if not last_game: - req_url += f'{param_char(other_params)}last_game=False' - else: - req_url += f'{param_char(other_params)}last_game={last_game}' - other_params = True - if last_game2 is not None: - req_url += f'{param_char(other_params)}last_game2={last_game2}' - other_params = True - if il_return is not None: - if not il_return: - req_url += f'{param_char(other_params)}il_return=false' - else: - req_url += f'{param_char(other_params)}il_return={il_return}' - other_params = True - if demotion_week is not None: - req_url += f'{param_char(other_params)}demotion_week={demotion_week}' - other_params = True - if headshot is not None: - if not headshot: - req_url += f'{param_char(other_params)}headshot=false' - else: - req_url += f'{param_char(other_params)}headshot={headshot}' - other_params = True - if vanity_card is not None: - if not vanity_card: - req_url += f'{param_char(other_params)}vanity_card=false' - else: - req_url += f'{param_char(other_params)}vanity_card={vanity_card}' - other_params = True - if injury_rating is not None: - req_url += f'{param_char(other_params)}injury_rating={injury_rating}' - other_params = True - - resp = requests.patch(req_url, headers=AUTH_TOKEN, timeout=3) - if resp.status_code == 200: - return True - else: - logging.warning(resp.text) - raise ValueError(f'DB: {resp.text}') +# async def patch_player( +# pid, name=None, wara=None, image=None, image2=None, team_id=None, season=None, pitcher_injury=None, pos_1=None, +# pos_2=None, pos_3=None, pos_4=None, pos_5=None, pos_6=None, pos_7=None, pos_8=None, last_game=None, +# last_game2=None, il_return=None, demotion_week=None, headshot=None, vanity_card=None, injury_rating=None): +# """ +# For values being patched to "None", set to False +# +# :param pid: +# :param name: +# :param wara: +# :param image: +# :param image2: +# :param team_id: +# :param season: +# :param pitcher_injury: +# :param pos_1: +# :param pos_2: +# :param pos_3: +# :param pos_4: +# :param pos_5: +# :param pos_6: +# :param pos_7: +# :param pos_8: +# :param last_game: +# :param last_game2: +# :param il_return: +# :return: +# """ +# req_url = f'{DB_URL}/v2/players/{pid}' +# other_params = False +# if name is not None: +# req_url += f'{param_char(other_params)}name={name}' +# other_params = True +# if wara is not None: +# req_url += f'{param_char(other_params)}wara={wara}' +# other_params = True +# if image is not None: +# req_url += f'{param_char(other_params)}image={image}' +# other_params = True +# if image2 is not None: +# if not image2: +# req_url += f'{param_char(other_params)}image2=False' +# else: +# req_url += f'{param_char(other_params)}image2={image2}' +# other_params = True +# if team_id is not None: +# req_url += f'{param_char(other_params)}team_id={team_id}' +# other_params = True +# if season is not None: +# req_url += f'{param_char(other_params)}season={season}' +# other_params = True +# if pitcher_injury is not None: +# if not pitcher_injury: +# req_url += f'{param_char(other_params)}pitcher_injury=False' +# else: +# req_url += f'{param_char(other_params)}pitcher_injury={pitcher_injury}' +# other_params = True +# if pos_1 is not None: +# req_url += f'{param_char(other_params)}pos_1={pos_1}' +# other_params = True +# if pos_2 is not None: +# if not pos_2: +# req_url += f'{param_char(other_params)}pos_2=False' +# else: +# req_url += f'{param_char(other_params)}pos_2={pos_2}' +# other_params = True +# if pos_3 is not None: +# if not pos_3: +# req_url += f'{param_char(other_params)}pos_3=False' +# else: +# req_url += f'{param_char(other_params)}pos_3={pos_3}' +# other_params = True +# if pos_4 is not None: +# if not pos_4: +# req_url += f'{param_char(other_params)}pos_4=False' +# else: +# req_url += f'{param_char(other_params)}pos_4={pos_4}' +# other_params = True +# if pos_5 is not None: +# if not pos_5: +# req_url += f'{param_char(other_params)}pos_5=False' +# else: +# req_url += f'{param_char(other_params)}pos_5={pos_5}' +# other_params = True +# if pos_6 is not None: +# if not pos_6: +# req_url += f'{param_char(other_params)}pos_6=False' +# else: +# req_url += f'{param_char(other_params)}pos_6={pos_6}' +# other_params = True +# if pos_7 is not None: +# if not pos_7: +# req_url += f'{param_char(other_params)}pos_7=False' +# else: +# req_url += f'{param_char(other_params)}pos_7={pos_7}' +# other_params = True +# if pos_8 is not None: +# if not pos_8: +# req_url += f'{param_char(other_params)}pos_8=False' +# else: +# req_url += f'{param_char(other_params)}pos_8={pos_8}' +# other_params = True +# if last_game is not None: +# if not last_game: +# req_url += f'{param_char(other_params)}last_game=False' +# else: +# req_url += f'{param_char(other_params)}last_game={last_game}' +# other_params = True +# if last_game2 is not None: +# req_url += f'{param_char(other_params)}last_game2={last_game2}' +# other_params = True +# if il_return is not None: +# if not il_return: +# req_url += f'{param_char(other_params)}il_return=false' +# else: +# req_url += f'{param_char(other_params)}il_return={il_return}' +# other_params = True +# if demotion_week is not None: +# req_url += f'{param_char(other_params)}demotion_week={demotion_week}' +# other_params = True +# if headshot is not None: +# if not headshot: +# req_url += f'{param_char(other_params)}headshot=false' +# else: +# req_url += f'{param_char(other_params)}headshot={headshot}' +# other_params = True +# if vanity_card is not None: +# if not vanity_card: +# req_url += f'{param_char(other_params)}vanity_card=false' +# else: +# req_url += f'{param_char(other_params)}vanity_card={vanity_card}' +# other_params = True +# if injury_rating is not None: +# req_url += f'{param_char(other_params)}injury_rating={injury_rating}' +# other_params = True +# +# resp = requests.patch(req_url, headers=AUTH_TOKEN, timeout=3) +# if resp.status_code == 200: +# return True +# else: +# logging.warning(resp.text) +# raise ValueError(f'DB: {resp.text}') async def get_standings(season=None, team_abbrev=None, league_abbrev=None, division_abbrev=None): @@ -540,18 +538,6 @@ async def get_standings(season=None, team_abbrev=None, league_abbrev=None, divis return await db_get(req_url) -async def post_standings_recalc(season): - req_url = f'{DB_URL}/v1/standings/s{season}/recalculate' - - resp = requests.post(req_url, headers=AUTH_TOKEN, timeout=15) - if resp.status_code == 200: - print(f'Done calculating') - return resp.json() - else: - logging.warning(resp.text) - raise ValueError(f'DB: {resp.text}') - - async def get_results(season, team_abbrev=None, week=None, away_abbrev=None, home_abbrev=None): req_url = f'{DB_URL}/v1/results?season={season}' if team_abbrev: @@ -566,47 +552,6 @@ async def get_results(season, team_abbrev=None, week=None, away_abbrev=None, hom return await db_get(req_url) -async def post_result(result): - req_url = f'{DB_URL}/v1/results' - payload = json.dumps(result) - - resp = requests.post(req_url, payload, headers=AUTH_TOKEN, timeout=3) - if resp.status_code == 200: - return True - else: - logging.warning(resp.text) - raise ValueError(f'DB: {resp.text}') - - -async def patch_result(result_id, away_score=None, home_score=None): - req_url = f'{DB_URL}/v1/results/{result_id}' - other_params = False - if away_score: - req_url += f'{param_char(other_params)}away_score={away_score}' - other_params = True - if home_score: - req_url += f'{param_char(other_params)}home_score={home_score}' - other_params = True - - resp = requests.patch(req_url, headers=AUTH_TOKEN, timeout=3) - if resp.status_code == 200: - return True - else: - logging.warning(resp.text) - raise ValueError(f'DB: {resp.text}') - - -async def delete_result(result_id): - req_url = f'{DB_URL}/v1/results/{result_id}' - - resp = requests.delete(req_url, headers=AUTH_TOKEN, timeout=3) - if resp.status_code == 200: - return True - else: - logging.warning(resp.text) - raise ValueError(f'DB: {resp.text}') - - async def get_transactions( season, team_abbrev=None, week_start=None, week_end=None, cancelled=None, frozen=None, player_name=None, player_id=None, move_id=None, timeout=3): diff --git a/helpers.py b/helpers.py index e543418..5e55b6b 100644 --- a/helpers.py +++ b/helpers.py @@ -2,7 +2,8 @@ import datetime import pygsheets -from db_calls import * +from db_calls import db_get, db_patch, db_post, db_delete, get_player_headshot +# from db_calls import * import asyncio import logging @@ -642,7 +643,7 @@ async def team_emoji(ctx, team): return emoji -async def fuzzy_player_search(ctx, channel, bot, name, master_list): +async def fuzzy_player_search(ctx, channel, bot, name, master_list, author = None): """ Takes a name to search and returns the name of the best match @@ -681,7 +682,7 @@ async def fuzzy_player_search(ctx, channel, bot, name, master_list): count += 1 embed.set_footer(text='These are the closest matches. Spell better if they\'re not who you want.') this_q = Question(bot, channel, None, 'int', 45, embed=embed) - resp = await this_q.ask([ctx.author]) + resp = await this_q.ask([author]) if not resp: return None