-
Notifications
You must be signed in to change notification settings - Fork 134
/
action_row.py
621 lines (502 loc) · 20.1 KB
/
action_row.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# SPDX-License-Identifier: MIT
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Generator,
Generic,
Iterator,
List,
Literal,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
overload,
)
from ..components import (
ActionRow as ActionRowComponent,
Button as ButtonComponent,
NestedComponent,
SelectMenu as SelectComponent,
)
from ..enums import ButtonStyle, ComponentType, TextInputStyle
from ..utils import MISSING, SequenceProxy
from .button import Button
from .item import WrappedComponent
from .select import Select, SelectOptionInput
from .text_input import TextInput
if TYPE_CHECKING:
from typing_extensions import Self
from ..emoji import Emoji
from ..message import Message
from ..partial_emoji import PartialEmoji
from ..types.components import ActionRow as ActionRowPayload
__all__ = (
"ActionRow",
"Components",
"MessageUIComponent",
"ModalUIComponent",
"MessageActionRow",
"ModalActionRow",
)
MessageUIComponent = Union[Button[Any], Select[Any]]
ModalUIComponent = TextInput # Union[TextInput, Select[Any]]
UIComponentT = TypeVar("UIComponentT", bound=WrappedComponent)
StrictUIComponentT = TypeVar("StrictUIComponentT", MessageUIComponent, ModalUIComponent)
Components = Union[
"ActionRow[UIComponentT]",
UIComponentT,
Sequence[Union["ActionRow[UIComponentT]", UIComponentT, Sequence[UIComponentT]]],
]
# this is cursed
ButtonCompatibleActionRowT = TypeVar(
"ButtonCompatibleActionRowT",
bound="Union[ActionRow[MessageUIComponent], ActionRow[WrappedComponent]]",
)
SelectCompatibleActionRowT = TypeVar(
"SelectCompatibleActionRowT",
bound="Union[ActionRow[MessageUIComponent], ActionRow[WrappedComponent]]", # to add: ActionRow[ModalUIComponent]
)
TextInputCompatibleActionRowT = TypeVar(
"TextInputCompatibleActionRowT",
bound="Union[ActionRow[ModalUIComponent], ActionRow[WrappedComponent]]",
)
class ActionRow(Generic[UIComponentT]):
"""Represents a UI action row. Useful for lower level component manipulation.
.. container:: operations
.. describe:: x[i]
Returns the component at position ``i``. Also supports slices.
.. versionadded:: 2.6
.. describe:: len(x)
Returns the number of components in this row.
.. versionadded:: 2.6
.. describe:: iter(x)
Returns an iterator for the components in this row.
.. versionadded:: 2.6
To handle interactions created by components sent in action rows or entirely independently,
event listeners must be used. For buttons and selects, the related events are
:func:`disnake.on_button_click` and :func:`disnake.on_dropdown`, respectively. Alternatively,
:func:`disnake.on_message_interaction` can be used for either. For modals, the related event is
:func:`disnake.on_modal_submit`.
.. versionadded:: 2.4
.. versionchanged:: 2.6
Requires and provides stricter typing for contained components.
Parameters
----------
*components: :class:`WrappedComponent`
The components of this action row.
.. versionchanged:: 2.6
Components can now be either valid in the context of a message, or in the
context of a modal. Combining components from both contexts is not supported.
"""
type: ClassVar[Literal[ComponentType.action_row]] = ComponentType.action_row
# When unspecified and called empty, default to an ActionRow that takes any kind of component.
@overload
def __init__(self: ActionRow[WrappedComponent]):
...
# Explicit definitions are needed to make
# "ActionRow(Select(), TextInput())" and
# "ActionRow(Select(), Button())"
# differentiate themselves properly.
@overload
def __init__(self: ActionRow[MessageUIComponent], *components: MessageUIComponent):
...
@overload
def __init__(self: ActionRow[ModalUIComponent], *components: ModalUIComponent):
...
# Allow use of "ActionRow[StrictUIComponent]" externally.
@overload
def __init__(self: ActionRow[StrictUIComponentT], *components: StrictUIComponentT):
...
def __init__(self, *components: UIComponentT):
self._children: List[UIComponentT] = []
for component in components:
if not isinstance(component, WrappedComponent):
raise TypeError(
f"components should be of type WrappedComponent, got {type(component).__name__}."
)
self.append_item(component)
def __repr__(self) -> str:
return f"<ActionRow children={self._children!r}>"
def __len__(self) -> int:
return len(self._children)
@property
def children(self) -> Sequence[UIComponentT]:
"""Sequence[:class:`WrappedComponent`]:
A read-only copy of the UI components stored in this action row. To add/remove
components to/from the action row, use its methods to directly modify it.
.. versionchanged:: 2.6
Returns an immutable sequence instead of a list.
"""
return SequenceProxy(self._children)
@property
def width(self) -> int:
return sum(child.width for child in self._children)
def append_item(self, item: UIComponentT) -> Self:
"""Append a component to the action row. The component's type must match that
of the action row.
This function returns the class instance to allow for fluent-style chaining.
Parameters
----------
item: :class:`WrappedComponent`
The component to append to the action row.
Raises
------
ValueError
The width of the action row exceeds 5.
"""
self.insert_item(len(self), item)
return self
def insert_item(self, index: int, item: UIComponentT) -> Self:
"""Insert a component to the action row at a given index. The component's
type must match that of the action row.
This function returns the class instance to allow for fluent-style chaining.
.. versionadded:: 2.6
Parameters
----------
index: :class:`int`
The index at which to insert the component into the action row.
item: :class:`WrappedComponent`
The component to insert into the action row.
Raises
------
ValueError
The width of the action row exceeds 5.
"""
if self.width + item.width > 5:
raise ValueError("Too many components in this row, can not append a new one.")
self._children.insert(index, item)
return self
def add_button(
self: ButtonCompatibleActionRowT,
index: Optional[int] = None,
*,
style: ButtonStyle = ButtonStyle.secondary,
label: Optional[str] = None,
disabled: bool = False,
custom_id: Optional[str] = None,
url: Optional[str] = None,
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
) -> ButtonCompatibleActionRowT:
"""Add a button to the action row. Can only be used if the action
row holds message components.
To append a pre-existing :class:`~disnake.ui.Button` use the
:meth:`append_item` method instead.
This function returns the class instance to allow for fluent-style chaining.
.. versionchanged:: 2.6
Now allows for inserting at a given index. The default behaviour of
appending is preserved.
Parameters
----------
index: :class:`int`
The index at which to insert the button into the action row. If not provided,
this method defaults to appending the button to the action row.
style: :class:`.ButtonStyle`
The style of the button.
custom_id: Optional[:class:`str`]
The ID of the button that gets received during an interaction.
If this button is for a URL, it does not have a custom ID.
url: Optional[:class:`str`]
The URL this button sends you to.
disabled: :class:`bool`
Whether the button is disabled or not.
label: Optional[:class:`str`]
The label of the button, if any.
emoji: Optional[Union[:class:`.PartialEmoji`, :class:`.Emoji`, :class:`str`]]
The emoji of the button, if available.
Raises
------
ValueError
The width of the action row exceeds 5.
"""
self.insert_item(
len(self) if index is None else index,
Button(
style=style,
label=label,
disabled=disabled,
custom_id=custom_id,
url=url,
emoji=emoji,
),
)
return self
def add_select(
self: SelectCompatibleActionRowT,
*,
custom_id: str = MISSING,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
options: SelectOptionInput = MISSING,
disabled: bool = False,
) -> SelectCompatibleActionRowT:
"""Add a select menu to the action row. Can only be used if the action
row holds message components.
To append a pre-existing :class:`~disnake.ui.Select` use the
:meth:`append_item` method instead.
This function returns the class instance to allow for fluent-style chaining.
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.
disabled: :class:`bool`
Whether the select is disabled or not.
Raises
------
ValueError
The width of the action row exceeds 5.
"""
self.append_item(
Select(
custom_id=custom_id,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
options=options,
disabled=disabled,
),
)
return self
def add_text_input(
self: TextInputCompatibleActionRowT,
*,
label: str,
custom_id: str,
style: TextInputStyle = TextInputStyle.short,
placeholder: Optional[str] = None,
value: Optional[str] = None,
required: bool = True,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
) -> TextInputCompatibleActionRowT:
"""Add a text input to the action row. Can only be used if the action
row holds modal components.
To append a pre-existing :class:`~disnake.ui.TextInput` use the
:meth:`append_item` method instead.
This function returns the class instance to allow for fluent-style chaining.
.. versionadded:: 2.4
Parameters
----------
style: :class:`.TextInputStyle`
The style of the text input.
label: :class:`str`
The label of the text input.
custom_id: :class:`str`
The ID of the text input that gets received during an interaction.
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is entered.
value: Optional[:class:`str`]
The pre-filled value of the text input.
required: :class:`bool`
Whether the text input is required. Defaults to ``True``.
min_length: Optional[:class:`int`]
The minimum length of the text input.
max_length: Optional[:class:`int`]
The maximum length of the text input.
Raises
------
ValueError
The width of the action row exceeds 5.
"""
self.append_item(
TextInput(
label=label,
custom_id=custom_id,
style=style,
placeholder=placeholder,
value=value,
required=required,
min_length=min_length,
max_length=max_length,
),
)
return self
def clear_items(self) -> Self:
"""Remove all components from the action row.
This function returns the class instance to allow for fluent-style chaining.
.. versionadded:: 2.6
"""
self._children.clear()
return self
def remove_item(self, item: UIComponentT) -> Self:
"""Remove a component from the action row.
This function returns the class instance to allow for fluent-style chaining.
.. versionadded:: 2.6
Parameters
----------
item: :class:`WrappedComponent`
The component to remove from the action row.
Raises
------
ValueError
The component could not be found on the action row.
"""
self._children.remove(item)
return self
def pop(self, index: int) -> UIComponentT:
"""Pop the component at the provided index from the action row.
.. versionadded:: 2.6
Parameters
----------
index: :class:`int`
The index at which to pop the component.
Raises
------
IndexError
There is no component at the provided index.
"""
self.remove_item(component := self[index])
return component
@property
def _underlying(self) -> ActionRowComponent[NestedComponent]:
return ActionRowComponent._raw_construct(
type=self.type,
children=[comp._underlying for comp in self._children],
)
def to_component_dict(self) -> ActionRowPayload:
return self._underlying.to_dict()
def __delitem__(self, index: Union[int, slice]) -> None:
del self._children[index]
@overload
def __getitem__(self, index: int) -> UIComponentT:
...
@overload
def __getitem__(self, index: slice) -> Sequence[UIComponentT]:
...
def __getitem__(self, index: Union[int, slice]) -> Union[UIComponentT, Sequence[UIComponentT]]:
return self._children[index]
def __iter__(self) -> Iterator[UIComponentT]:
return iter(self._children)
@classmethod
def with_modal_components(cls) -> ActionRow[ModalUIComponent]:
"""Create an empty action row meant to store components compatible with
:class:`disnake.ui.Modal`. Saves the need to import type specifiers to
typehint empty action rows.
.. versionadded:: 2.6
Returns
-------
:class:`ActionRow`:
The newly created empty action row, intended for modal components.
"""
return ActionRow[ModalUIComponent]()
@classmethod
def with_message_components(cls) -> ActionRow[MessageUIComponent]:
"""Create an empty action row meant to store components compatible with
:class:`disnake.Message`. Saves the need to import type specifiers to
typehint empty action rows.
.. versionadded:: 2.6
Returns
-------
:class:`ActionRow`:
The newly created empty action row, intended for message components.
"""
return ActionRow[MessageUIComponent]()
@classmethod
def rows_from_message(
cls,
message: Message,
*,
strict: bool = True,
) -> List[ActionRow[MessageUIComponent]]:
"""Create a list of up to 5 action rows from the components on an existing message.
This will abide by existing component format on the message, including component
ordering and rows. Components will be transformed to UI kit components, such that
they can be easily modified and re-sent as action rows.
.. versionadded:: 2.6
Parameters
----------
message: :class:`disnake.Message`
The message from which to extract the components.
strict: :class:`bool`
Whether or not to raise an exception if an unknown component type is encountered.
Raises
------
TypeError
Strict-mode is enabled and an unknown component type is encountered.
Returns
-------
List[:class:`ActionRow`]:
The action rows parsed from the components on the message.
"""
rows: List[ActionRow[MessageUIComponent]] = []
for row in message.components:
rows.append(current_row := ActionRow.with_message_components())
for component in row.children:
if isinstance(component, ButtonComponent):
current_row.append_item(Button.from_component(component))
elif isinstance(component, SelectComponent):
current_row.append_item(Select.from_component(component))
elif strict:
raise TypeError(f"Encountered unknown component type: {component.type!r}.")
return rows
@staticmethod
def walk_components(
action_rows: Sequence[ActionRow[UIComponentT]],
) -> Generator[Tuple[ActionRow[UIComponentT], UIComponentT], None, None]:
"""Iterate over the components in a sequence of action rows, yielding each
individual component together with the action row of which it is a child.
.. versionadded:: 2.6
Parameters
----------
action_rows: Sequence[:class:`ActionRow`]
The sequence of action rows over which to iterate.
Yields
------
Tuple[:class:`ActionRow`, :class:`WrappedComponent`]
A tuple containing an action row and a component of that action row.
"""
for row in tuple(action_rows):
for component in tuple(row._children):
yield row, component
MessageActionRow = ActionRow[MessageUIComponent]
ModalActionRow = ActionRow[ModalUIComponent]
def components_to_rows(
components: Components[StrictUIComponentT],
) -> List[ActionRow[StrictUIComponentT]]:
if not isinstance(components, Sequence):
components = [components]
action_rows: List[ActionRow[StrictUIComponentT]] = []
auto_row: ActionRow[StrictUIComponentT] = ActionRow[StrictUIComponentT]()
for component in components:
if isinstance(component, WrappedComponent):
try:
auto_row.append_item(component)
except ValueError:
action_rows.append(auto_row)
auto_row = ActionRow[StrictUIComponentT](component)
else:
if auto_row.width > 0:
action_rows.append(auto_row)
auto_row = ActionRow[StrictUIComponentT]()
if isinstance(component, ActionRow):
action_rows.append(component)
elif isinstance(component, Sequence):
action_rows.append(ActionRow[StrictUIComponentT](*component))
else:
raise TypeError(
"`components` must be a `WrappedComponent` or `ActionRow`, "
"a sequence/list of `WrappedComponent`s or `ActionRow`s, "
"or a nested sequence/list of `WrappedComponent`s"
)
if auto_row.width > 0:
action_rows.append(auto_row)
return action_rows
def components_to_dict(components: Components[StrictUIComponentT]) -> List[ActionRowPayload]:
return [row.to_component_dict() for row in components_to_rows(components)]