Skip to content

Commit

Permalink
[Hockey] Fix schedule game state emojis and update display with new f…
Browse files Browse the repository at this point in the history
…ormatting.

- Fix broadcast button in schedule command.
- Properly compare goals lists to hopefully remove goals that were pulled back again.
- Add the PWHL server to the all invite list.
- Add delay to AsyncIterator usage for posting goal and game updates.
- Fix players lookup with missing data.
  • Loading branch information
TrustyJAID committed Jan 19, 2024
1 parent d7a340a commit 386c62a
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 75 deletions.
39 changes: 26 additions & 13 deletions hockey/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ class GameState(Enum):
def __str__(self):
return self.name.replace("_", " ").title()

def emoji(self) -> str:
if 1 <= self.value < 5:
return "\N{LARGE RED CIRCLE}"
if self.value == 5:
return "\N{LARGE GREEN CIRCLE}"
if 5 < self.value < 9:
return "\N{LARGE YELLOW CIRCLE}"
if self.value >= 9:
return "\N{CHEQUERED FLAG}"
return str(self)

def is_preview(self):
return self in (
GameState.preview,
Expand Down Expand Up @@ -817,7 +828,7 @@ async def period_recap(self, bot: Red, period: Literal["1st", "2nd", "3rd"]) ->
post_state = ["all", self.home_team, self.away_team]
config = bot.get_cog("Hockey").config
all_channels = await bot.get_cog("Hockey").config.all_channels()
async for channel_id, data in AsyncIter(all_channels.items(), steps=100):
async for channel_id, data in AsyncIter(all_channels.items(), steps=5, delay=5):
await self.maybe_edit_gamedaythread_message(bot, channel_id, data)
channel = await get_channel_obj(bot, channel_id, data)
if not channel:
Expand Down Expand Up @@ -871,7 +882,7 @@ async def post_game_state(self, bot: Red) -> None:
state_text = await self.game_state_text()
tasks = []
all_channels = await bot.get_cog("Hockey").config.all_channels()
async for channel_id, data in AsyncIter(all_channels.items(), steps=100):
async for channel_id, data in AsyncIter(all_channels.items(), steps=5, delay=5):
await self.maybe_edit_gamedaythread_message(bot, channel_id, data)
channel = await get_channel_obj(bot, channel_id, data)
if not channel:
Expand Down Expand Up @@ -994,8 +1005,10 @@ async def check_team_goals(self, bot: Red) -> None:
# home_goal_ids = [goal.goal_id for goal in self.home_goals]
# away_goal_ids = [goal.goal_id for goal in self.away_goals]

home_goal_list = list(team_data[self.home_team]["goal_id"])
away_goal_list = list(team_data[self.away_team]["goal_id"])
home_goal_list = set(team_data[self.home_team]["goal_id"])
current_home_goals = set(goal.goal_id for goal in self.home_goals)
away_goal_list = set(team_data[self.away_team]["goal_id"])
current_away_goals = set(goal.goal_id for goal in self.away_goals)

for goal in self.goals:
# goal_id = str(goal["result"]["eventCode"])
Expand Down Expand Up @@ -1034,14 +1047,14 @@ async def check_team_goals(self, bot: Red) -> None:
if old_msgs:
asyncio.create_task(goal.edit_team_goal(bot, self, old_msgs))
# attempts to delete the goal if it was called back
home_diff = abs(len(home_goal_list) - len(self.home_goals))
away_diff = abs(len(away_goal_list) - len(self.away_goals))
if 1 < home_diff <= 2:
for goal_str in home_goal_list:
await Goal.remove_goal_post(bot, goal_str, self.home_team, self)
if 1 < away_diff <= 2:
for goal_str in away_goal_list:
await Goal.remove_goal_post(bot, goal_str, self.away_team, self)
home_diff = home_goal_list.difference(current_home_goals)
# the difference here from the saved data to the new data returns only goals
# that are missing from the old data and ignores new goals in the current data
away_diff = away_goal_list.difference(current_away_goals)
for goal_str in home_diff:
await Goal.remove_goal_post(bot, goal_str, self.home_team, self)
for goal_str in away_diff:
await Goal.remove_goal_post(bot, goal_str, self.away_team, self)

async def save_game_state(self, bot: Red, time_to_game_start: str = "0") -> None:
"""
Expand Down Expand Up @@ -1104,7 +1117,7 @@ async def post_time_to_game_start(self, bot: Red, time_left: str) -> None:
)
tasks = []
all_channels = await bot.get_cog("Hockey").config.all_channels()
async for channel_id, data in AsyncIter(all_channels.items(), steps=100):
async for channel_id, data in AsyncIter(all_channels.items(), steps=5, delay=5):
channel = await get_channel_obj(bot, channel_id, data)
if not channel:
continue
Expand Down
28 changes: 17 additions & 11 deletions hockey/goal.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ async def post_team_goal(self, bot: Red, game_data: Game) -> List[Tuple[int, int
tasks = []
all_channels = await bot.get_cog("Hockey").config.all_channels()
post_data = []
async for channel_id, data in AsyncIter(all_channels.items(), steps=100):
async for channel_id, data in AsyncIter(all_channels.items(), steps=5, delay=5):
channel = await get_channel_obj(bot, channel_id, data)
if not channel:
continue
Expand Down Expand Up @@ -323,16 +323,16 @@ async def actually_post_goal(
return None

@staticmethod
async def remove_goal_post(bot: Red, goal: str, team: str, data: Game) -> None:
async def remove_goal_post(bot: Red, goal_id: str, team: str, data: Game) -> None:
"""
Attempt to delete a goal if it was pulled back
"""
config = bot.get_cog("Hockey").config
team_list = await config.teams()
team_data = await get_team(bot, team, data.game_start_str)
if goal not in [goal.goal_id for goal in data.goals]:
if goal_id not in [goal.goal_id for goal in data.goals]:
try:
old_msgs = team_data["goal_id"][goal]["messages"]
old_msgs = team_data["goal_id"][goal_id]["messages"]
except KeyError:
return
except Exception:
Expand All @@ -350,25 +350,31 @@ async def remove_goal_post(bot: Red, goal: str, team: str, data: Game) -> None:
continue
except Exception:
log.exception(
f"Error getting old goal for {str(team)} {str(goal)} in "
f"{guild_id=} {channel_id=}"
"Error getting old goal for %s %s in guild=%s channel=%s",
team,
goal_id,
guild_id,
channel_id,
)
pass
continue
if message is not None:
try:
await message.delete()
except (discord.errors.NotFound, discord.errors.Forbidden):
pass
except Exception:
log.exception(
f"Error getting old goal for {str(team)} {str(goal)} in "
f"{guild_id=} {channel_id=}"
"Error getting old goal for %s %s in guild=%s channel=%s",
team,
goal_id,
guild_id,
channel_id,
)
else:
log.debug("Channel does not have permission to read history")
try:
team_list.remove(team_data)
del team_data["goal_id"][goal]
del team_data["goal_id"][goal_id]
team_list.append(team_data)
await config.teams.set(team_list)
except Exception:
Expand All @@ -387,7 +393,7 @@ async def edit_team_goal(
em = await self.goal_post_embed(game_data)
if og_msg is None:
return
async for guild_id, channel_id, message_id in AsyncIter(og_msg, steps=10):
async for guild_id, channel_id, message_id in AsyncIter(og_msg, steps=5, delay=5):
guild = bot.get_guild(int(guild_id))
if not guild:
continue
Expand Down
4 changes: 3 additions & 1 deletion hockey/hockey_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,9 @@ async def otherdiscords(
"appropriate punishments ranging from a warning "
"to a ban. ```\n\nhttps://discord.gg/reddithockey\n"
"https://discord.gg/rishockey\n"
"https://discord.gg/c3Q7Fq4T\nhttps://discord.gg/thehockeyguy"
"https://discord.gg/c3Q7Fq4T\n"
"https://discord.gg/thehockeyguy\n"
"https://discord.gg/P3aFDDXqym\n"
)
eastern_conference = "https://i.imgur.com/CtXvcCs.png"
western_conference = "https://i.imgur.com/UFYJTDF.png"
Expand Down
2 changes: 1 addition & 1 deletion hockey/hockeypickems.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ async def get_pickem_object(
return self.all_pickems[str(guild.id)][str(game.game_id)]

async def fix_pickem_game_start(self, game: Game):
async for guild_id, data in AsyncIter(self.all_pickems.items(), steps=100):
async for guild_id, data in AsyncIter(self.all_pickems.items(), steps=5, delay=10):
guild = self.bot.get_guild(int(guild_id))
if guild is None:
continue
Expand Down
8 changes: 4 additions & 4 deletions hockey/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,10 +373,6 @@ class PlayerStats:
position: Optional[str]
headshot: Optional[str]
heroImage: Optional[str]
heightInInches: int
heightInCentimeters: int
weightInPounds: int
weightInKilograms: int
birthDate: str
birthCity: dict
birthCountry: str
Expand All @@ -393,6 +389,10 @@ class PlayerStats:
seasonTotals: List[SeasonStats]
awards: List[dict]
currentTeamRoster: List[dict]
heightInInches: Optional[int] = None
heightInCentimeters: Optional[int] = None
weightInPounds: Optional[int] = None
weightInKilograms: Optional[int] = None
currentTeamId: Optional[int] = None
currentTeamAbbrev: Optional[str] = None
birthStateProvince: dict = field(default_factory=dict)
Expand Down
66 changes: 21 additions & 45 deletions hockey/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,12 +303,6 @@ async def get_page(
async def format_page(
self, menu: menus.MenuPages, games: List[ScheduledGame]
) -> discord.Embed:
states = {
GameState.preview: "\N{LARGE RED CIRCLE}",
GameState.live: "\N{LARGE GREEN CIRCLE}",
"Intermission": "\N{LARGE YELLOW CIRCLE}",
GameState.final: "\N{CHEQUERED FLAG}",
}
# log.debug(games)
msg = humanize_list(self.team) + "\n"
day = None
Expand All @@ -324,13 +318,12 @@ async def format_page(
broadcast_str = ""
log.verbose("ScheduleList game: %s", game)
if game.broadcasts and self.show_broadcasts:
broadcasts = game.broadcasts
if broadcasts:
if game.broadcasts:
broadcast_str = (
"- "
+ _("Broadcasts")
+ "\n"
+ humanize_list([f" - {b['name']}" for b in broadcasts])
" - "
+ _("__Broadcasts__")
+ "\n - "
+ humanize_list([b.get("network", "Unknown") for b in game.broadcasts])
)
if home_team in TEAMS:
home_emoji = discord.PartialEmoji.from_str(TEAMS[home_team]["emoji"])
Expand All @@ -340,10 +333,7 @@ async def format_page(
away_abr = TEAMS[away_team]["tri_code"]

postponed = game.schedule_state != "OK"
try:
game_state = states[game.game_state]
except KeyError:
game_state = "\N{LARGE RED CIRCLE}"
game_state = game.game_state.emoji()
if start_time is None:
start_time = game_start
if day is None:
Expand All @@ -356,40 +346,26 @@ async def format_page(
time = f"<t:{int(game_start.timestamp())}:D>"
game_str = _("Games") if self.team == [] else _("Game")
msg += f"**{game_str} {time}**\n"

time_str = f"<t:{int(game_start.timestamp())}:t>"
if postponed:
time_str = _("Postponed")
msg += (
f"{game_state} - {away_emoji} {away_abr} @ "
f"{home_emoji} {home_abr} - {time_str}\n{broadcast_str}\n"
)
elif game_start < datetime.now(timezone.utc):
game_state = "\N{CROSS MARK}"
msg += (
f"- {away_emoji} {away_abr} @ "
f"{home_emoji} {home_abr} - {time_str} - {game_state}"
)

if game_start < datetime.now(timezone.utc):
home_score = game.home_score
away_score = game.away_score
if not self.get_recap:
msg += (
f"{game_state} - {away_emoji} {away_abr} **{away_score}** - "
f"**{home_score}** {home_emoji} {home_abr} \n{broadcast_str}\n"
)

else:
score_msg = f"{away_abr} **{away_score}** - " f"**{home_score}** {home_abr}"
if self.get_recap:
game_recap = await self.api.get_game_recap(game.id)
if game_recap is not None:
msg += (
f"[{game_state} - {away_emoji} {away_abr} **{away_score}** - "
f"**{home_score}** {home_emoji} {home_abr}]({game_recap}) \n{broadcast_str}\n"
)
else:
msg += (
f"{game_state} - {away_emoji} {away_abr} **{away_score}** - "
f"**{home_score}** {home_emoji} {home_abr} \n{broadcast_str}\n"
)
else:
time_str = f"<t:{int(game_start.timestamp())}:t>"
msg += (
f"{game_state} - {away_emoji} {away_abr} @ "
f"{home_emoji} {home_abr} - {time_str}\n{broadcast_str}\n"
)
score_msg = f"[{score_msg}]({game_recap})"
msg += f"\n - {score_msg}"
msg += "\n"
if self.show_broadcasts:
msg += f"{broadcast_str}\n"

count = 0
em = discord.Embed()
Expand Down

0 comments on commit 386c62a

Please sign in to comment.