|
| 1 | +from typing import Mapping, Optional, Type |
| 2 | + |
| 3 | +import discord |
| 4 | + |
| 5 | + |
| 6 | +class MenuBase(discord.ui.View): |
| 7 | + __menu_copy_attrs__ = () |
| 8 | + |
| 9 | + def __init__(self, owner: discord.User, *args, **kwargs): |
| 10 | + super().__init__(*args, **kwargs) |
| 11 | + self.owner = owner |
| 12 | + self.message = None # type: Optional[discord.Message] |
| 13 | + |
| 14 | + @classmethod |
| 15 | + def from_menu(cls, other: 'MenuBase', cancel_other=True): |
| 16 | + inst = cls(owner=other.owner) |
| 17 | + inst.message = other.message |
| 18 | + if cancel_other: |
| 19 | + other.stop() |
| 20 | + for attr in cls.__menu_copy_attrs__: |
| 21 | + # copy the instance attr to the new instance if available, or fall back to the class default |
| 22 | + sentinel = object() |
| 23 | + value = getattr(other, attr, sentinel) |
| 24 | + if value is sentinel: |
| 25 | + value = getattr(cls, attr, None) |
| 26 | + setattr(inst, attr, value) |
| 27 | + return inst |
| 28 | + |
| 29 | + # ==== d.py overrides ==== |
| 30 | + async def interaction_check(self, interaction: discord.Interaction) -> bool: |
| 31 | + if interaction.user.id == self.owner.id: |
| 32 | + return True |
| 33 | + await interaction.response.send_message("You are not the owner of this menu.", ephemeral=True) |
| 34 | + return False |
| 35 | + |
| 36 | + async def on_timeout(self): |
| 37 | + if self.message is None: |
| 38 | + return |
| 39 | + await self.message.edit(view=None) |
| 40 | + |
| 41 | + # ==== content ==== |
| 42 | + def get_content(self) -> Mapping: |
| 43 | + """Return a mapping of kwargs to send when sending the view.""" |
| 44 | + return {} |
| 45 | + |
| 46 | + # ==== helpers ==== |
| 47 | + async def send_to(self, destination: discord.abc.Messageable, *args, **kwargs): |
| 48 | + """Sends this menu to a given destination.""" |
| 49 | + message = await destination.send(*args, view=self, **self.get_content(), **kwargs) |
| 50 | + self.message = message |
| 51 | + return message |
| 52 | + |
| 53 | + async def defer_to(self, view_type: Type['MenuBase'], interaction: discord.Interaction): |
| 54 | + """Defers control to another menu item.""" |
| 55 | + view = view_type.from_menu(self, cancel_other=True) |
| 56 | + await interaction.response.edit_message(view=view, **view.get_content()) |
| 57 | + |
| 58 | + async def refresh_content(self, interaction: discord.Interaction): |
| 59 | + """Refresh the interaction's message with the current state of the menu.""" |
| 60 | + await interaction.response.edit_message(view=self, **self.get_content()) |
0 commit comments