New Scorebug

This commit is contained in:
Cal Corum 2024-06-27 00:31:10 -05:00
parent c24a71a4ee
commit 7b868696fa

View File

@ -131,60 +131,179 @@ class Players(commands.Cog):
return embed return embed
async def game_scorebug(self, sheets_data, include_images: bool = True):
away_team = await db_get('teams', object_id=sheets_data.get_value('B5'))
home_team = await db_get('teams', object_id=sheets_data.get_value('B6'))
logging.info(f'getting gamestate')
game_state = sheets_data.get_values('B2', 'G8', include_tailing_empty_rows=True)
logging.info(f'gamestate: {game_state}')
header = game_state[0][0]
is_final = header[-5:] == 'FINAL'
inning_desc = {header.split(" - ")[1]}
away_score = game_state[3][2]
home_score = game_state[4][2]
which_half = game_state[3][4]
logging.info(f'getting runners')
runners = sheets_data.get_values('K11', 'L14', include_tailing_empty_rows=True)
logging.info(f'runners: {runners}')
logging.info(f'getting matchups')
matchups = sheets_data.get_values('K3', 'O6', include_tailing_empty_rows=True)
logging.info(f'matchups: {matchups}')
this_embed = get_team_embed(
# title=f'[{away_team["sname"]}]({get_team_url(away_team)}) @ '
# f'[{home_team["sname"]}]({get_team_url(home_team)}) - {header.split(" - ")[1]}',
title=header,
team=away_team if away_score > home_score else home_team,
thumbnail=False
)
def get_ascii_scorebug():
occupied = ''
unoccupied = ''
first_base = unoccupied if runners[1][0] == '' else occupied
second_base = unoccupied if runners[2][0] == '' else occupied
third_base = unoccupied if runners[3][0] == '' else occupied
half = '' if which_half == 'Top' else ''
if not is_final:
so = sheets_data.get_value('F6')
inning = f'{half} {game_state[3][5]}'
outs = f'{so} Out{"s" if so != "1" else ""}'
else:
inning = f'F/{game_state[3][5] if which_half == "Bot" else int(game_state[3][5]) - 1}'
outs = ''
return f'```\n' \
f'{away_team["abbrev"]: ^4}{away_score: ^3} {second_base}' \
f'{inning: >10}\n' \
f'{home_team["abbrev"]: ^4}{home_score: ^3} {third_base} ' \
f'{first_base}{outs: >8}\n```'
this_embed.add_field(
name='Game State',
value=get_ascii_scorebug(),
inline=False
)
p_name = matchups[0][0]
this_embed.add_field(
name='Pitcher',
value=f'[{p_name}]({get_player_url({"season": away_team["season"], "name": p_name})})\n'
f'{matchups[0][2]}'
)
b_name = matchups[1][0]
this_embed.add_field(
name='Batter',
value=f'{matchups[1][3]}. '
f'[{b_name}]({get_player_url({"season": away_team["season"], "name": b_name})})'
f' - {matchups[1][4]}\n'
f'{matchups[1][2]}'
)
if include_images:
this_embed.set_thumbnail(url=matchups[0][1])
this_embed.set_image(url=matchups[1][1])
on_first = runners[1][0]
on_second = runners[2][0]
on_third = runners[3][0]
if len(on_first) + len(on_second) + len(on_third) > 0:
br_string = f''
if len(on_first) > 0:
br_string += f'On First: [{runners[1][0]}]({get_player_url({"season": away_team["season"], "name": runners[1][0]})})\n'
if len(on_second) > 0:
br_string += f'On Second: [{runners[2][0]}]({get_player_url({"season": away_team["season"], "name": runners[2][0]})})\n'
if len(on_third) > 0:
br_string += f'On Third: [{runners[3][0]}]({get_player_url({"season": away_team["season"], "name": runners[3][0]})})\n'
this_embed.add_field(name=' ', value=' ', inline=False)
this_embed.add_field(
name='Baserunners',
value=br_string
)
this_embed.add_field(
name='Catcher',
value=f'[{runners[0][0]}]({get_player_url({"season": away_team["season"], "name": runners[0][0]})})'
)
if not is_final:
inning_sum = sheets_data.get_values('R3', 'S20')
i_string = ''
for line in inning_sum:
i_string += f'- Play {line[0]}: {line[1]}\n'
this_embed.add_field(
name='Inning Summary',
value=i_string,
inline=False
)
return this_embed
@tasks.loop(count=1) @tasks.loop(count=1)
async def build_master_player_list(self): async def build_master_player_list(self):
guild = self.bot.get_guild(int(os.environ.get('GUILD_ID'))) # logging.info(f'build_master_player_list - getting current')
if not guild:
logging.error(f'build_master_player_list - could not pull guild / retrying in 15 seconds')
await asyncio.sleep(15)
guild = self.bot.get_guild(int(os.environ.get('GUILD_ID')))
logging.info(f'build_master_player_list - guild: {guild}')
logging.info(f'build_master_player_list - getting current')
current = await db_get('current') current = await db_get('current')
logging.info(f'build_master_player_list - getting all_players') # logging.info(f'build_master_player_list - getting all_players')
p_query = await db_get('players', 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') # logging.info(f'build_master_player_list - building player_list')
self.player_list = {x['name'].lower(): x['id'] for x in p_query['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.info(f'player list count: {len(self.player_list)}')
logging.debug(f'player list: {self.player_list}') logging.debug(f'player list: {self.player_list}')
@build_master_player_list.before_loop
async def before_build_master_player_list(self):
await self.bot.wait_until_ready()
@tasks.loop(minutes=3) @tasks.loop(minutes=3)
async def live_scorecard_loop(self): async def live_scorecard_loop(self):
guild = self.bot.get_guild(int(os.environ.get('GUILD_ID'))) guild = self.bot.get_guild(int(os.environ.get('GUILD_ID')))
if not guild:
logging.error(f'live_scorecard_loop - could not pull guild / retrying in 15 seconds')
await asyncio.sleep(15)
guild = self.bot.get_guild(int(os.environ.get('GUILD_ID')))
logging.info(f'live_scorecard_loop - guild: {guild}')
score_channel = discord.utils.get(guild.text_channels, name='live-sba-scores') score_channel = discord.utils.get(guild.text_channels, name='live-sba-scores')
player_role = get_role(score_channel, SBA_PLAYERS_ROLE_NAME, bot=self.bot) player_role = get_role(score_channel, SBA_PLAYERS_ROLE_NAME, bot=self.bot)
try: try:
if len(self.voice_channels) > 0: if len(self.voice_channels) > 0:
game_strings = [] all_embeds = []
for x in self.scorecards.values(): for x in self.scorecards.values():
logging.info(f'looping through scorecards')
await asyncio.sleep(1) await asyncio.sleep(1)
this_string = x.get_value('A1') logging.info(f'creating embeds')
if ' F' not in this_string: all_embeds.append(await self.game_scorebug(x, include_images=False))
game_strings.append(this_string)
if len(game_strings) > 0: logging.info(f'embeds: {all_embeds}')
if len(all_embeds) > 0:
# Clear old messages # Clear old messages
async for message in score_channel.history(limit=25): async for message in score_channel.history(limit=25):
await message.delete() await message.delete()
embed = get_team_embed('SBa Scoreboard')
embed.add_field(name='Live Games', value="\n\n".join(game_strings))
embed.set_footer(
text=f'SBa Season {SBA_SEASON}',
icon_url=LOGO
)
await score_channel.set_permissions(player_role, read_messages=True) await score_channel.set_permissions(player_role, read_messages=True)
await score_channel.send(content=None, embed=embed) await score_channel.send(content=None, embeds=all_embeds)
return return
# game_strings = []
# for x in self.scorecards.values():
# await asyncio.sleep(1)
# this_string = x.get_value('A1')
# if ' F' not in this_string:
# game_strings.append(this_string)
#
# if len(game_strings) > 0:
# # Clear old messages
# async for message in score_channel.history(limit=25):
# await message.delete()
#
# embed = get_team_embed('SBa Scoreboard')
# embed.add_field(name='Live Games', value="\n\n".join(game_strings))
# embed.set_footer(
# text=f'SBa Season {SBA_SEASON}',
# icon_url=LOGO
# )
# await score_channel.set_permissions(player_role, read_messages=True)
# await score_channel.send(content=None, embed=embed)
# return
self.scorecards = {} self.scorecards = {}
await score_channel.set_permissions(player_role, read_messages=False) await score_channel.set_permissions(player_role, read_messages=False)
@ -192,6 +311,10 @@ class Players(commands.Cog):
await send_to_channel(self.bot, 'commissioners-office', f'Could not update live scorecard:\n\n{e}') await send_to_channel(self.bot, 'commissioners-office', f'Could not update live scorecard:\n\n{e}')
logging.error(f'Could not update live scorecard: {e}') logging.error(f'Could not update live scorecard: {e}')
@live_scorecard_loop.before_loop
async def before_live_scorecard_loop(self):
await self.bot.wait_until_ready()
@staticmethod @staticmethod
async def update_injuries(ctx): async def update_injuries(ctx):
current = await db_get('current') current = await db_get('current')
@ -1659,7 +1782,8 @@ class Players(commands.Cog):
@app_commands.checks.has_any_role(SBA_PLAYERS_ROLE_NAME) @app_commands.checks.has_any_role(SBA_PLAYERS_ROLE_NAME)
async def branding_slash_command( async def branding_slash_command(
self, interaction: discord.Interaction, color_hex: str = None, team_image_url: str = None, 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): mil_color_hex: str = None, mil_team_image_url: str = None, mil_team_name: str = None,
dice_color_hex: str = None):
await interaction.response.defer() await interaction.response.defer()
current = await db_get('current') current = await db_get('current')
team = await get_team_by_owner(current['season'], interaction.user.id) team = await get_team_by_owner(current['season'], interaction.user.id)
@ -1967,8 +2091,8 @@ class Players(commands.Cog):
@app_commands.command(name='charts') @app_commands.command(name='charts')
async def chart_command(self, interaction: discord.Interaction, chart_name: Literal[ 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', 'block-plate', 'defense-matters', 'fly-b', 'g1', 'g2', 'g3', 'groundball', 'hit-and-run',
'g1', 'g2', 'g3', 'groundball']): 'rest', 'rob-hr', 'sac-bunt', 'squeeze-bunt']):
gb_url = 'https://sombaseball.ddns.net/static/images/season04/ground-ball-chart' gb_url = 'https://sombaseball.ddns.net/static/images/season04/ground-ball-chart'
all_charts = { all_charts = {
'rest': [f'{SBA_IMAGE_URL}/season05/charts/rest.png'], 'rest': [f'{SBA_IMAGE_URL}/season05/charts/rest.png'],
@ -1990,7 +2114,8 @@ class Players(commands.Cog):
'g1': [f'{gb_url}-g1.png', f'{gb_url}01.png', f'{gb_url}02.png'], 'g1': [f'{gb_url}-g1.png', f'{gb_url}01.png', f'{gb_url}02.png'],
'g2': [f'{gb_url}-g2.png', f'{gb_url}01.png', f'{gb_url}02.png'], 'g2': [f'{gb_url}-g2.png', f'{gb_url}01.png', f'{gb_url}02.png'],
'g3': [f'{gb_url}-g3.png', f'{gb_url}01.png', f'{gb_url}02.png'], 'g3': [f'{gb_url}-g3.png', f'{gb_url}01.png', f'{gb_url}02.png'],
'groundball': [f'{gb_url}01.png', f'{gb_url}02.png'] 'groundball': [f'{gb_url}01.png', f'{gb_url}02.png'],
'fly-b': [f'https://i.postimg.cc/CMfZPwPC/flyball-b.png']
} }
first = True first = True
@ -2079,9 +2204,9 @@ class Players(commands.Cog):
try: try:
if 'https://' in sheet_url: if 'https://' in sheet_url:
scorecard = sheets.open_by_url(sheet_url).worksheet_by_title('ASCII') scorecard = sheets.open_by_url(sheet_url).worksheet_by_title('Scorebug')
else: else:
scorecard = sheets.open_by_key(sheet_url).worksheet_by_title('ASCII') scorecard = sheets.open_by_key(sheet_url).worksheet_by_title('Scorebug')
except Exception as e: except Exception as e:
await interaction.response.send_message( await interaction.response.send_message(
'Frick. I wasn\'t able to publish that card. Is that card ID correct?' 'Frick. I wasn\'t able to publish that card. Is that card ID correct?'
@ -2111,8 +2236,14 @@ class Players(commands.Cog):
await interaction.response.send_message(f'I am checking sheets now...', ephemeral=True) await interaction.response.send_message(f'I am checking sheets now...', ephemeral=True)
score_text = this_scorecard.get_value('A1') try:
await interaction.edit_original_response(content=score_text) game_embed = await self.game_scorebug(this_scorecard)
await interaction.edit_original_response(content=None, embed=game_embed)
except Exception as e:
logging.error(e)
await interaction.edit_original_response(
content='I was not able to generate a scorebug for this game'
)
@app_commands.command(name='injury', description='Make an injury check; rating = left of "p", games = right') @app_commands.command(name='injury', description='Make an injury check; rating = left of "p", games = right')
# @app_commands.guilds(discord.Object(id=os.environ.get('GUILD_ID'))) # @app_commands.guilds(discord.Object(id=os.environ.get('GUILD_ID')))