|
| 1 | +import os |
| 2 | +from typing import Callable |
| 3 | + |
| 4 | +import discord |
| 5 | +from discord import ui |
| 6 | +from typing_extensions import override |
| 7 | + |
| 8 | +__all__ = ["CustomDropdown"] |
| 9 | + |
| 10 | + |
| 11 | +DropdownCallback = Callable[[discord.Interaction], str | None] |
| 12 | +""" |
| 13 | +A callback for a dropdown. |
| 14 | +
|
| 15 | +Parameters: |
| 16 | +----------- |
| 17 | +interaction: discord.Interaction |
| 18 | + The interaction object. |
| 19 | +
|
| 20 | +Returns: |
| 21 | +-------- |
| 22 | +``str`` | ``None`` |
| 23 | + Return with a string to mark it as an error message, otherwise None. |
| 24 | +""" |
| 25 | + |
| 26 | + |
| 27 | +class CustomDropdown(ui.Select[ui.View]): |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + custom_id: str | None = None, |
| 31 | + placeholder: str | None = "Select an option", |
| 32 | + min_values: int = 1, |
| 33 | + max_values: int = 1, |
| 34 | + disabled: bool = False, |
| 35 | + ): |
| 36 | + self._callback: list[DropdownCallback] = [] |
| 37 | + if custom_id is None: |
| 38 | + custom_id = "nameless-dropdown-" + os.urandom(16).hex() |
| 39 | + |
| 40 | + super().__init__( |
| 41 | + custom_id=custom_id, |
| 42 | + placeholder=placeholder, |
| 43 | + min_values=min_values, |
| 44 | + max_values=max_values, |
| 45 | + disabled=disabled, |
| 46 | + options=[], |
| 47 | + ) |
| 48 | + |
| 49 | + def add_callback(self, callback: DropdownCallback): |
| 50 | + self._callback.append(callback) |
| 51 | + return self |
| 52 | + |
| 53 | + @override |
| 54 | + async def callback(self, interaction: discord.Interaction): |
| 55 | + await interaction.response.defer() |
| 56 | + for callback in self._callback: |
| 57 | + error = callback(interaction) |
| 58 | + if error: |
| 59 | + await interaction.response.send_message(error, ephemeral=True) |
| 60 | + return |
| 61 | + |
| 62 | + if self.view is not None: |
| 63 | + self.view.stop() |
| 64 | + |
| 65 | + def self_add_option( |
| 66 | + self, |
| 67 | + *, |
| 68 | + label: str, |
| 69 | + value: str = "", |
| 70 | + description: str | None = None, |
| 71 | + emoji: str | discord.Emoji | discord.PartialEmoji | None = None, |
| 72 | + default: bool = False, |
| 73 | + ): |
| 74 | + self.add_option( |
| 75 | + label=label, |
| 76 | + value=value, |
| 77 | + description=description, |
| 78 | + emoji=emoji, |
| 79 | + default=default, |
| 80 | + ) |
| 81 | + return self |
0 commit comments