Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 18 additions & 54 deletions cogs/beatmap_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ def format_length(self, total_seconds: int, user_id_for_l10n: int) -> str:
if not total_seconds:
return "0:00"
try:
return str(datetime.timedelta(seconds=int(total_seconds)))[
2:
] # 去掉小時部分 0:
return str(datetime.timedelta(seconds=int(total_seconds)))[2:] # 去掉小時部分 0:
except:
return "N/A"

Expand Down Expand Up @@ -79,9 +77,7 @@ async def on_message(self, message: discord.Message) -> None:
if beatmap_id_str:
try:
beatmap_id = int(beatmap_id_str)
beatmap_detail = await self.osu_api.get_beatmap_details(
beatmap_id=beatmap_id
)
beatmap_detail = await self.osu_api.get_beatmap_details(beatmap_id=beatmap_id)
if beatmap_detail:
target_beatmap_from_direct_id = beatmap_detail
beatmap_data_list = [
Expand All @@ -94,9 +90,7 @@ async def on_message(self, message: discord.Message) -> None:
elif beatmapset_id_str:
try:
beatmapset_id = int(beatmapset_id_str)
beatmapset_data = await self.osu_api.get_beatmapset(
beatmapset_id=beatmapset_id
)
beatmapset_data = await self.osu_api.get_beatmapset(beatmapset_id=beatmapset_id)
# beatmapset_data for API v2 contains a 'beatmaps' key with list of difficulties
if (
beatmapset_data
Expand Down Expand Up @@ -132,9 +126,7 @@ async def on_message(self, message: discord.Message) -> None:
# Fallback: if somehow target_beatmap_from_direct_id wasn't set or ID mismatched
# This part of the logic might be redundant if target_beatmap_from_direct_id is reliable
elif beatmap_data_list:
for bm in (
beatmap_data_list
): # Should be a list of one if direct fetch worked
for bm in beatmap_data_list: # Should be a list of one if direct fetch worked
if str(bm.get("id")) == beatmap_id_str: # API v2 beatmap id is 'id'
target_beatmap = bm
break
Expand All @@ -147,14 +139,10 @@ async def on_message(self, message: discord.Message) -> None:
elif beatmap_data_list: # Ensure list is not empty
# Try to find osu!standard (ruleset_id 0)
for bm in beatmap_data_list:
if (
bm.get("ruleset_id") == 0
): # API v2 uses 'ruleset_id' for mode integer
if bm.get("ruleset_id") == 0: # API v2 uses 'ruleset_id' for mode integer
target_beatmap = bm
break
if (
not target_beatmap
): # If no osu!standard, take the first one in the list
if not target_beatmap: # If no osu!standard, take the first one in the list
target_beatmap = beatmap_data_list[0]
# If beatmap_data_list was empty, target_beatmap remains None

Expand All @@ -173,9 +161,7 @@ async def on_message(self, message: discord.Message) -> None:
# bpm, total_length, hit_length, max_combo, status (string), url, ruleset_id.
# It also contains a nested 'beatmapset' object.

current_beatmapset_data = target_beatmap.get(
"beatmapset"
) # This should be a nested object
current_beatmapset_data = target_beatmap.get("beatmapset") # This should be a nested object
if not current_beatmapset_data:
current_beatmapset_data = {} # Fallback to avoid errors, though this indicates an issue
logger.warning(
Expand Down Expand Up @@ -207,9 +193,7 @@ async def on_message(self, message: discord.Message) -> None:
)

status_display_string_on_message = get_beatmap_status_display(
raw_status_on_message,
user_id_for_l10n,
lstr,
raw_status_on_message, user_id_for_l10n, lstr
)

stars = float(target_beatmap.get("difficulty_rating", 0.0))
Expand All @@ -229,22 +213,16 @@ async def on_message(self, message: discord.Message) -> None:
b_id = target_beatmap.get("id")
# bs_id can be from target_beatmap.beatmapset_id or from current_beatmapset_data.id
bs_id = target_beatmap.get("beatmapset_id")
if (
not bs_id and current_beatmapset_data
): # Fallback if not directly on beatmap object
if not bs_id and current_beatmapset_data: # Fallback if not directly on beatmap object
bs_id = current_beatmapset_data.get("id")

beatmap_url = target_beatmap.get("url", f"https://osu.ppy.sh/b/{b_id}")

beatmap_cover_url = discord.Embed.Empty
if current_beatmapset_data and "covers" in current_beatmapset_data:
beatmap_cover_url = current_beatmapset_data["covers"].get(
"card", discord.Embed.Empty
)
beatmap_cover_url = current_beatmapset_data["covers"].get("card", discord.Embed.Empty)

mode_int = int(
target_beatmap.get("ruleset_id", 0)
) # ruleset_id is the integer mode
mode_int = int(target_beatmap.get("ruleset_id", 0)) # ruleset_id is the integer mode
mode_name = self.get_mode_name(mode_int, user_id_for_l10n)

# For footer: num_diffs_in_set
Expand All @@ -254,16 +232,12 @@ async def on_message(self, message: discord.Message) -> None:
# Or, if we fetched the full set, len(beatmap_data_list) when beatmapset_id_str was used.

num_diffs_to_report_in_footer = 0
if (
not beatmap_id_str and beatmapset_id_str
): # It was a query for a full beatmapset
if not beatmap_id_str and beatmapset_id_str: # It was a query for a full beatmapset
if (
current_beatmapset_data and "total" in current_beatmapset_data
): # API v2 Beatmapset has 'total' beatmaps
num_diffs_to_report_in_footer = current_beatmapset_data["total"]
elif (
beatmap_data_list
): # Fallback using the length of the fetched list of diffs
elif beatmap_data_list: # Fallback using the length of the fetched list of diffs
num_diffs_to_report_in_footer = len(beatmap_data_list)
# If beatmap_id_str was present, we don't show "multiple difficulties" footer usually.

Expand All @@ -278,9 +252,7 @@ async def on_message(self, message: discord.Message) -> None:

embed.add_field(
name=lstr(user_id_for_l10n, "beatmap_creator_label"),
value=f"[{creator}](https://osu.ppy.sh/u/{creator_id})"
if creator_id
else creator,
value=f"[{creator}](https://osu.ppy.sh/u/{creator_id})" if creator_id else creator,
inline=True,
)
embed.add_field(
Expand All @@ -297,21 +269,15 @@ async def on_message(self, message: discord.Message) -> None:

stats_text = f"CS: `{cs}` AR: `{ar}` OD: `{od}` HP: `{hp}`"
embed.add_field(
name=lstr(user_id_for_l10n, "beatmap_stats_label"),
value=stats_text,
inline=False,
name=lstr(user_id_for_l10n, "beatmap_stats_label"), value=stats_text, inline=False
)

length_formatted = f"{self.format_length(total_length, user_id_for_l10n)} ({self.format_length(hit_length, user_id_for_l10n)} {lstr(user_id_for_l10n, 'short_playable_time_indicator', default_fallback='play')})"
embed.add_field(
name=lstr(user_id_for_l10n, "beatmap_length_label"),
value=length_formatted,
inline=True,
name=lstr(user_id_for_l10n, "beatmap_length_label"), value=length_formatted, inline=True
)
embed.add_field(
name=lstr(user_id_for_l10n, "beatmap_bpm_label"),
value=f"{bpm:.0f}",
inline=True,
name=lstr(user_id_for_l10n, "beatmap_bpm_label"), value=f"{bpm:.0f}", inline=True
)
if max_combo:
embed.add_field(
Expand All @@ -321,9 +287,7 @@ async def on_message(self, message: discord.Message) -> None:
)
else: # Create a placeholder field if max_combo is None or 0
embed.add_field(
name=lstr(user_id_for_l10n, "beatmap_max_combo_label"),
value="N/A",
inline=True,
name=lstr(user_id_for_l10n, "beatmap_max_combo_label"), value="N/A", inline=True
)

# 頁腳
Expand Down
15 changes: 4 additions & 11 deletions cogs/copypasta_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ def load_copypastas(self) -> None:
)
self.copypastas = {}
else:
logger.error(
f"[CopypastaCog] {COPASTA_FILE} not found. No copypastas loaded."
)
logger.error(f"[CopypastaCog] {COPASTA_FILE} not found. No copypastas loaded.")
self.copypastas = {}
except json.JSONDecodeError:
logger.error(
Expand All @@ -59,8 +57,7 @@ def load_copypastas(self) -> None:
self.copypastas = {}

@app_commands.command(
name="copypasta",
description="Sends a random copypasta based on your language preference.",
name="copypasta", description="Sends a random copypasta based on your language preference."
)
async def send_copypasta(self, interaction: discord.Interaction) -> None:
if not self.copypastas:
Expand Down Expand Up @@ -94,12 +91,8 @@ async def send_copypasta(self, interaction: discord.Interaction) -> None:

# 2. If preferred language had no pastas (or lang key didn't exist) AND it's not the copypasta default, try copypasta default
if not pastas_to_choose_from and preferred_lang != copypasta_default_lang_key:
if (
self.copypastas.get(copypasta_default_lang_key)
):
pastas_to_choose_from = list(
self.copypastas[copypasta_default_lang_key].values()
)
if self.copypastas.get(copypasta_default_lang_key):
pastas_to_choose_from = list(self.copypastas[copypasta_default_lang_key].values())
logger.debug(
f"[CopypastaCog] User {user_id} preferred {preferred_lang} (no pastas), falling back to {copypasta_default_lang_key}. Found {len(pastas_to_choose_from)} pastas."
)
Expand Down
31 changes: 8 additions & 23 deletions cogs/help_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ def __init__(self, bot: commands.Bot) -> None:
self.bot = bot

@app_commands.command(
name="help",
description="Displays all available slash commands and their descriptions.",
name="help", description="Displays all available slash commands and their descriptions."
)
async def slash_help(self, interaction: discord.Interaction) -> None:
logger.debug(
Expand All @@ -46,12 +45,8 @@ async def slash_help(self, interaction: discord.Interaction) -> None:

test_title_key = "help_embed_title"
english_fallback_title = "Available Slash Commands (Fallback)"
localized_title_test = lstr(
user_id_for_l10n, test_title_key, english_fallback_title
)
logger.debug(
f"[HelpCog] Attempted lstr for '{test_title_key}': '{localized_title_test}'"
)
localized_title_test = lstr(user_id_for_l10n, test_title_key, english_fallback_title)
logger.debug(f"[HelpCog] Attempted lstr for '{test_title_key}': '{localized_title_test}'")

try:
await interaction.response.defer(ephemeral=True)
Expand All @@ -75,28 +70,20 @@ def sort_key(cmd):
try:
return DESIRED_COMMAND_ORDER.index(cmd.name)
except ValueError:
return len(
DESIRED_COMMAND_ORDER
) # Put commands not in the list at the end
return len(DESIRED_COMMAND_ORDER) # Put commands not in the list at the end

sorted_commands = sorted(all_app_commands, key=sort_key)
logger.debug(
f"[HelpCog] Sorted commands: {[cmd.name for cmd in sorted_commands]}"
)
logger.debug(f"[HelpCog] Sorted commands: {[cmd.name for cmd in sorted_commands]}")

commands_to_display = []
for i, cmd in enumerate(sorted_commands):
logger.debug(
f"[HelpCog] Processing command {i + 1}/{len(sorted_commands)}: {cmd.name}"
)
logger.debug(f"[HelpCog] Processing command {i + 1}/{len(sorted_commands)}: {cmd.name}")
if isinstance(cmd, app_commands.Command):
cmd_name = cmd.name
cmd_description = cmd.description
if not cmd_description or cmd_description == "...":
cmd_description = lstr(
user_id_for_l10n,
"help_no_description",
"No description available.",
user_id_for_l10n, "help_no_description", "No description available."
)

localized_desc_key = f"cmd_desc_{cmd_name.lower()}"
Expand Down Expand Up @@ -130,9 +117,7 @@ def sort_key(cmd):
logger.error(f"[HelpCog] Failed to send help embed: {e_send}")
# Try to send a simple text message if embed fails
try:
fallback_text = (
"Could not display help commands as an embed. Please check logs."
)
fallback_text = "Could not display help commands as an embed. Please check logs."
if commands_to_display:
fallback_text = "\n".join(commands_to_display)
await interaction.followup.send(fallback_text, ephemeral=True)
Expand Down
Loading