-
Notifications
You must be signed in to change notification settings - Fork 134
/
select.py
417 lines (343 loc) · 14 KB
/
select.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# SPDX-License-Identifier: MIT
from __future__ import annotations
import asyncio
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
get_origin,
overload,
)
from ..components import SelectMenu, SelectOption
from ..enums import ComponentType
from ..partial_emoji import PartialEmoji
from ..utils import MISSING
from .item import DecoratedItem, Item, Object
__all__ = (
"Select",
"select",
)
if TYPE_CHECKING:
from typing_extensions import ParamSpec, Self
from ..emoji import Emoji
from ..interactions import MessageInteraction
from .item import ItemCallbackType
from .view import View
else:
ParamSpec = TypeVar
S = TypeVar("S", bound="Select")
S_co = TypeVar("S_co", bound="Select", covariant=True)
V_co = TypeVar("V_co", bound="Optional[View]", covariant=True)
P = ParamSpec("P")
SelectOptionInput = Union[List[SelectOption], List[str], Dict[str, str]]
def _parse_select_options(options: SelectOptionInput) -> List[SelectOption]:
if isinstance(options, dict):
return [SelectOption(label=key, value=val) for key, val in options.items()]
return [opt if isinstance(opt, SelectOption) else SelectOption(label=opt) for opt in options]
class Select(Item[V_co]):
"""Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use :attr:`Select.values`.
.. versionadded:: 2.0
Parameters
----------
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
If not given then one is generated for you.
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
options: Union[List[:class:`disnake.SelectOption`], List[:class:`str`], Dict[:class:`str`, :class:`str`]]
A list of options that can be selected in this menu. Use explicit :class:`.SelectOption`\\s
for fine-grained control over the options. Alternatively, a list of strings will be treated
as a list of labels, and a dict will be treated as a mapping of labels to values.
.. versionchanged:: 2.5
Now also accepts a list of str or a dict of str to str, which are then appropriately parsed as
:class:`.SelectOption` labels and values.
disabled: :class:`bool`
Whether the select is disabled.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
"""
__repr_attributes__: Tuple[str, ...] = (
"placeholder",
"min_values",
"max_values",
"options",
"disabled",
)
# We have to set this to MISSING in order to overwrite the abstract property from WrappedComponent
_underlying: SelectMenu = MISSING
@overload
def __init__(
self: Select[None],
*,
custom_id: str = ...,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
options: SelectOptionInput = ...,
disabled: bool = False,
row: Optional[int] = None,
):
...
@overload
def __init__(
self: Select[V_co],
*,
custom_id: str = ...,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
options: SelectOptionInput = ...,
disabled: bool = False,
row: Optional[int] = None,
):
...
def __init__(
self,
*,
custom_id: str = MISSING,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
options: SelectOptionInput = MISSING,
disabled: bool = False,
row: Optional[int] = None,
) -> None:
super().__init__()
self._selected_values: List[str] = []
self._provided_custom_id = custom_id is not MISSING
custom_id = os.urandom(16).hex() if custom_id is MISSING else custom_id
options = [] if options is MISSING else _parse_select_options(options)
self._underlying = SelectMenu._raw_construct(
custom_id=custom_id,
type=ComponentType.select,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
options=options,
disabled=disabled,
)
self.row = row
@property
def custom_id(self) -> str:
""":class:`str`: The ID of the select menu that gets received during an interaction."""
return self._underlying.custom_id
@custom_id.setter
def custom_id(self, value: str):
if not isinstance(value, str):
raise TypeError("custom_id must be None or str")
self._underlying.custom_id = value
@property
def placeholder(self) -> Optional[str]:
"""Optional[:class:`str`]: The placeholder text that is shown if nothing is selected, if any."""
return self._underlying.placeholder
@placeholder.setter
def placeholder(self, value: Optional[str]):
if value is not None and not isinstance(value, str):
raise TypeError("placeholder must be None or str")
self._underlying.placeholder = value
@property
def min_values(self) -> int:
""":class:`int`: The minimum number of items that must be chosen for this select menu."""
return self._underlying.min_values
@min_values.setter
def min_values(self, value: int):
self._underlying.min_values = int(value)
@property
def max_values(self) -> int:
""":class:`int`: The maximum number of items that must be chosen for this select menu."""
return self._underlying.max_values
@max_values.setter
def max_values(self, value: int):
self._underlying.max_values = int(value)
@property
def options(self) -> List[SelectOption]:
"""List[:class:`disnake.SelectOption`]: A list of options that can be selected in this select menu."""
return self._underlying.options
@options.setter
def options(self, value: List[SelectOption]):
if not isinstance(value, list):
raise TypeError("options must be a list of SelectOption")
if not all(isinstance(obj, SelectOption) for obj in value):
raise TypeError("all list items must subclass SelectOption")
self._underlying.options = value
def add_option(
self,
*,
label: str,
value: str = MISSING,
description: Optional[str] = None,
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
default: bool = False,
):
"""Adds an option to the select menu.
To append a pre-existing :class:`.SelectOption` use the
:meth:`append_option` method instead.
Parameters
----------
label: :class:`str`
The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str`
The value of the option. This is not displayed to users.
If not given, defaults to the label. Can only be up to 100 characters.
description: Optional[:class:`str`]
An additional description of the option, if any.
Can only be up to 100 characters.
emoji: Optional[Union[:class:`str`, :class:`.Emoji`, :class:`.PartialEmoji`]]
The emoji of the option, if available. This can either be a string representing
the custom or unicode emoji or an instance of :class:`.PartialEmoji` or :class:`.Emoji`.
default: :class:`bool`
Whether this option is selected by default.
Raises
------
ValueError
The number of options exceeds 25.
"""
option = SelectOption(
label=label,
value=value,
description=description,
emoji=emoji,
default=default,
)
self.append_option(option)
def append_option(self, option: SelectOption):
"""Appends an option to the select menu.
Parameters
----------
option: :class:`disnake.SelectOption`
The option to append to the select menu.
Raises
------
ValueError
The number of options exceeds 25.
"""
if len(self._underlying.options) >= 25:
raise ValueError("maximum number of options already provided")
self._underlying.options.append(option)
@property
def disabled(self) -> bool:
""":class:`bool`: Whether the select menu is disabled."""
return self._underlying.disabled
@disabled.setter
def disabled(self, value: bool):
self._underlying.disabled = bool(value)
@property
def values(self) -> List[str]:
"""List[:class:`str`]: A list of values that have been selected by the user."""
return self._selected_values
@property
def width(self) -> int:
return 5
def refresh_component(self, component: SelectMenu) -> None:
self._underlying = component
def refresh_state(self, interaction: MessageInteraction) -> None:
self._selected_values = interaction.values # type: ignore
@classmethod
def from_component(cls, component: SelectMenu) -> Self:
return cls(
custom_id=component.custom_id,
placeholder=component.placeholder,
min_values=component.min_values,
max_values=component.max_values,
options=component.options,
disabled=component.disabled,
row=None,
)
def is_dispatchable(self) -> bool:
"""Whether the select menu is dispatchable. This will always return ``True``.
:return type: :class:`bool`
"""
return True
@overload
def select(
*,
placeholder: Optional[str] = None,
custom_id: str = ...,
min_values: int = 1,
max_values: int = 1,
options: SelectOptionInput = ...,
disabled: bool = False,
row: Optional[int] = None,
) -> Callable[[ItemCallbackType[Select[V_co]]], DecoratedItem[Select[V_co]]]:
...
@overload
def select(
cls: Type[Object[S_co, P]], *_: P.args, **kwargs: P.kwargs
) -> Callable[[ItemCallbackType[S_co]], DecoratedItem[S_co]]:
...
def select(
cls: Type[Object[S_co, P]] = Select[Any],
**kwargs: Any,
) -> Callable[[ItemCallbackType[S_co]], DecoratedItem[S_co]]:
"""A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, ``self`` representing
the :class:`disnake.ui.View`, the :class:`disnake.ui.Select` being pressed and
the :class:`disnake.MessageInteraction` you receive.
In order to get the selected items that the user has chosen within the callback
use :attr:`Select.values`.
Parameters
----------
cls: Type[:class:`Select`]
The select subclass to create an instance of. If provided, the following parameters
described below do no apply. Instead, this decorator will accept the same keywords
as the passed cls does.
.. versionadded:: 2.6
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
options: Union[List[:class:`disnake.SelectOption`], List[:class:`str`], Dict[:class:`str`, :class:`str`]]
A list of options that can be selected in this menu. Use explicit :class:`.SelectOption`\\s
for fine-grained control over the options. Alternatively, a list of strings will be treated
as a list of labels, and a dict will be treated as a mapping of labels to values.
.. versionchanged:: 2.5
Now also accepts a list of str or a dict of str to str, which are then appropriately parsed as
:class:`.SelectOption` labels and values.
disabled: :class:`bool`
Whether the select is disabled. Defaults to ``False``.
"""
if (origin := get_origin(cls)) is not None:
cls = origin
if not isinstance(cls, type) or not issubclass(cls, Select):
raise TypeError(f"cls argument must be a subclass of Select, got {cls!r}")
def decorator(func: ItemCallbackType[S_co]) -> DecoratedItem[S_co]:
if not asyncio.iscoroutinefunction(func):
raise TypeError("select function must be a coroutine function")
func.__discord_ui_model_type__ = cls
func.__discord_ui_model_kwargs__ = kwargs
return func # type: ignore
return decorator