Update view to support ephemeral responses

This commit is contained in:
2025-03-29 16:24:37 +01:00
parent ebf958434c
commit 09d147de9d
2 changed files with 12 additions and 9 deletions

View File

@@ -50,7 +50,7 @@ class Counter(ReactiveView):
@bot.slash_command() @bot.slash_command()
async def counter(ctx: discord.ApplicationContext) -> None: async def counter(ctx: discord.ApplicationContext) -> None:
"""Send the counter view.""" """Send the counter view."""
await Counter().send(ctx) await Counter().send(ctx, ephemeral=True)
bot.run(os.getenv("TOKEN")) bot.run(os.getenv("TOKEN_2"))

View File

@@ -20,6 +20,7 @@ class ReactiveView(discord.ui.View):
) -> None: ) -> None:
super().__init__(timeout=timeout, disable_on_timeout=disable_on_timeout) # pyright: ignore[reportUnknownMemberType] super().__init__(timeout=timeout, disable_on_timeout=disable_on_timeout) # pyright: ignore[reportUnknownMemberType]
self._reactives: list[Reactive] = [] self._reactives: list[Reactive] = []
self.ctx: discord.ApplicationContext | discord.Interaction | None = None
@override @override
def add_item(self, item: discord.ui.Item[Self]) -> None: def add_item(self, item: discord.ui.Item[Self]) -> None:
@@ -48,16 +49,18 @@ class ReactiveView(discord.ui.View):
""" """
for reactive in self._reactives: for reactive in self._reactives:
await reactive.refresh() await reactive.refresh()
if not self.message: editable = self.ctx or self.message
raise ValueError("View has no message (not yet sent?), can't refresh") if not editable:
raise ValueError("View has no editable (not yet sent?), can't refresh")
if embeds := await self._get_embeds(): if embeds := await self._get_embeds():
await self.message.edit(content=await self._get_content(), embeds=embeds, view=self) await editable.edit(content=await self._get_content(), embeds=embeds, view=self)
else: else:
await self.message.edit(content=await self._get_content(), view=self) await editable.edit(content=await self._get_content(), view=self)
async def send(self, ctx: discord.ApplicationContext | discord.Interaction) -> None: async def send(self, ctx: discord.ApplicationContext | discord.Interaction, ephemeral: bool = False) -> None:
"""Send the view to a context.""" """Send the view to a context."""
self.ctx = ctx
if embeds := await self._get_embeds(): if embeds := await self._get_embeds():
await ctx.respond(content=await self._get_content(), embeds=embeds, view=self) # pyright: ignore [reportUnknownMemberType] await ctx.respond(content=await self._get_content(), embeds=embeds, view=self, ephemeral=ephemeral) # pyright: ignore [reportUnknownMemberType]
else: else:
await ctx.respond(content=await self._get_content(), view=self) # pyright: ignore [reportUnknownMemberType] await ctx.respond(content=await self._get_content(), view=self, ephemeral=ephemeral) # pyright: ignore [reportUnknownMemberType]