From 0064cc1d4a2b3413d5d1af17b7edd8015964247a Mon Sep 17 00:00:00 2001 From: rnxm <63553775+rnxm@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:00:28 +0100 Subject: [PATCH] fix: defer slash commands that can outlast Discord's 3-second window Nothing defers slash commands automatically (the old before_invoke hook never ran), so commands that do slow work before their first reply fail with "The application did not respond". These now call ctx.defer() (a no-op for prefix commands): level (rank card render), snapshot and snapshot load, voice play, info ip and info template. Their replies are public, which matches what they send today. Co-Authored-By: Claude Opus 5.5 --- GLOSSARY.md | 2 +- cogs/info.py | 2 ++ cogs/level.py | 1 + cogs/snapshot.py | 2 ++ cogs/voice.py | 1 + tests/test_level_cog.py | 17 +++++++++++++++++ 6 files changed, 24 insertions(+), 1 deletion(-) diff --git a/GLOSSARY.md b/GLOSSARY.md index fc4da0f..77afe22 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -38,4 +38,4 @@ The words this codebase uses for its own concepts, and the decisions that shape **Cache invalidation uses Redis pub/sub.** Instances tell each other about changed guild settings over the existing Redis event bus (`core/clustering/`). Postgres `LISTEN/NOTIFY` triggers were considered, so outside writers such as the dashboard backend would invalidate caches automatically, and rejected until the monorepo move. -**Message visibility is configured per message, not in code.** Whether a response is ephemeral (and whether it deletes itself) comes from its localization key, which the dashboard will make editable per message. Commands don't hard-code `ephemeral`, and the bot doesn't defer slash commands automatically (a deferred response's visibility can't be changed afterwards). Revisit deferring when the dashboard work starts. +**Message visibility is configured per message, not in code.** Whether a response is ephemeral (and whether it deletes itself) comes from its localization key, which the dashboard will make editable per message. Commands don't hard-code `ephemeral`, and the bot doesn't defer slash commands automatically (a deferred response's visibility can't be changed afterwards). Commands that can take longer than Discord's 3-second window (rank card, snapshots, `voice play`, `info ip`, `info template`) call `ctx.defer()` themselves, so their replies are public. Revisit deferring when the dashboard work starts. diff --git a/cogs/info.py b/cogs/info.py index 4d39917..0546d8e 100644 --- a/cogs/info.py +++ b/cogs/info.py @@ -83,6 +83,7 @@ async def role(self, ctx: Context, role: discord.Role | None = None): @info.command(user=False, l10n_key="ipinfo") async def ip(self, ctx: Context, ip_addr: str): + await ctx.defer() # slow: calls ipinfo.io try: ip_json = await self.client.request(f"https://ipinfo.io/{ip_addr}/json") except RuntimeError: @@ -124,6 +125,7 @@ async def channel(self, ctx: Context, channel: discord.abc.GuildChannel): @info.command(l10n_key="tmplteinfo") async def template(self, ctx: Context, template: str): + await ctx.defer() # slow: fetches the template from Discord regex = DISCORD_TEMPLATE.search(template) if regex: template_code = regex.group(1) diff --git a/cogs/level.py b/cogs/level.py index 5543df7..29656ae 100644 --- a/cogs/level.py +++ b/cogs/level.py @@ -348,6 +348,7 @@ async def set_role_multiplier(self, guild_id: int, role_id: int, multiplier: flo async def level_command(self, ctx: Context, member: discord.Member | None = None) -> None: if not ctx.guild: return + await ctx.defer() # slow: renders the rank card image target = member or (ctx.author if isinstance(ctx.author, discord.Member) else None) if not target: diff --git a/cogs/snapshot.py b/cogs/snapshot.py index 076cf49..5f1223e 100644 --- a/cogs/snapshot.py +++ b/cogs/snapshot.py @@ -314,6 +314,7 @@ async def load_snapshot(self, ctx: Context, payload: dict): @group(permissions=["administrator"], user=False) async def snapshot(self, ctx: Context): assert ctx.guild is not None + await ctx.defer() # slow: reads every role and channel code = await self.create_snapshot(ctx) await ctx.send("snapshot.create", code=code) @@ -321,6 +322,7 @@ async def snapshot(self, ctx: Context): @snapshot.command(l10n_key="ss_load", permissions=["administrator"]) async def load(self, ctx: Context, code: str): assert ctx.guild is not None + await ctx.defer() # slow: recreates roles and channels payload = await self.get_snapshot(code) if not payload: await ctx.send("snapshot.not_found") diff --git a/cogs/voice.py b/cogs/voice.py index df10501..bec6389 100644 --- a/cogs/voice.py +++ b/cogs/voice.py @@ -117,6 +117,7 @@ async def on_voice_state_update( @command(user=False) async def play(self, ctx: Context, *, query: str): + await ctx.defer() # slow: connects to voice and searches Lavalink player = await self._get_player(ctx, connect=True) if not player: return diff --git a/tests/test_level_cog.py b/tests/test_level_cog.py index f8a65a9..212b5cf 100644 --- a/tests/test_level_cog.py +++ b/tests/test_level_cog.py @@ -320,6 +320,7 @@ async def test_level_command_sends_card(level_cog): ctx.author = MagicMock(spec=discord.Member) ctx.author.id = 111 ctx.send = AsyncMock() + ctx.defer = AsyncMock() level_cog.client.db.fetchrow.side_effect = [ {"xp": 120, "level": 1}, # user_levels row @@ -422,3 +423,19 @@ async def fetch(query, *args): await level_cog.get_role_overrides(guild_id) assert level_cog.client.db.fetch.await_count == 4 level_cog.client.event_bus.publish.assert_awaited() + + +@pytest.mark.asyncio +async def test_level_command_defers_before_rendering(level_cog): + """Rendering the card can exceed Discord's 3-second window, so the interaction is acknowledged first.""" + ctx = MagicMock() + ctx.guild = None + ctx.defer = AsyncMock() + await level_cog.level_command.callback(level_cog, ctx) + ctx.defer.assert_not_awaited() # DMs return before any work + + ctx.guild = MagicMock() + ctx.author = MagicMock(spec=discord.User) # not a member: no card, but the interaction was already acknowledged + ctx.send = AsyncMock() + await level_cog.level_command.callback(level_cog, ctx) + ctx.defer.assert_awaited_once()