-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcomponents.py
783 lines (658 loc) · 29.6 KB
/
components.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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-present mccuber04#2960
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import typing
from .enums import ComponentType, ButtonStyle
from .emoji import Emoji
from typing import Union
from .partial_emoji import PartialEmoji
from .errors import InvalidArgument, InvalidButtonUrl, URLAndCustomIDNotAlowed, EmptyActionRow
__all__ = ('Button', 'SelectMenu', 'ActionRow', 'SelectOption')
class Button:
"""
Represents an `Discord-Button <https://discord.com/developers/docs/interactions/message-components#button-object>`_
Read more in the `Documentation <https://discordpy-message-components.readthedocs.io/en/latest/components.html#Button>`_
Parameters
----------
label: Optional[:class:`str`] = None
text that appears on the button, max 80 characters
custom_id: Optional[Union[:class:`str`, :class:`int`]] = None
a developer-defined identifier for the button, max 100 characters
style: Optional[Union[:class:`ButtonStyle`, :class:`int`]] = ButtonStyle.grey
The Style the Button should have
emoji: Optional[Union[:class:`discord.PartialEmoji`, :class:`discord.Emoji`, :class:`str`]] = None
The Emoji that will be displayed on the left side of the Button.
url: Optional[:class:`str`]
a url for link-style buttons
disabled: Optional[:class:`bool`] = False
whether the button is disabled (default False)
"""
def __init__(self, label: str = None,
custom_id: Union[str, int] = None,
style: Union[ButtonStyle, int] = ButtonStyle.grey,
emoji: Union[PartialEmoji, Emoji, str] = None,
url: str = None,
disabled: bool = False):
if url and not url.startswith(('http', 'discord://')):
raise InvalidButtonUrl(url)
self.url = url
if isinstance(style, int):
style = ButtonStyle.from_value(style)
if not isinstance(style, ButtonStyle):
raise InvalidArgument(
"The Style of an discord.Button have to be an Object of discord.ButtonStyle, discord.ButtonColor or usually an Integer between 1 and 5")
self.style = style
if self.style == ButtonStyle.url and not self.url:
raise InvalidArgument('You must also pass a URL if the ButtonStyle is a link.')
if self.url and int(self.style) != 5:
self.style = ButtonStyle.Link_Button
if custom_id and len(custom_id) > 100:
raise InvalidArgument(
'The maximum length of Button-custom_id\'s are 100; your one is %s long. (%s Characters to long)' % (
len(custom_id), len(custom_id) - 100))
if isinstance(custom_id, str) and custom_id.isdigit():
self.custom_id = int(custom_id)
else:
self.custom_id = custom_id
if self.custom_id is not None and self.url:
raise URLAndCustomIDNotAlowed(self.custom_id)
if label and len(label) > 80:
raise InvalidArgument(
'The maximum length of Button-Labels\'s are 80; your one is %s long. (%s Characters to long)' % (
len(label), len(label) - 80))
self.label = label
if isinstance(emoji, Emoji):
self.emoji = PartialEmoji(name=emoji.name, animated=emoji.animated, id=emoji.id)
elif isinstance(emoji, PartialEmoji):
self.emoji = emoji
elif isinstance(emoji, str):
if emoji[0] == '<':
self.emoji = PartialEmoji.from_string(emoji)
else:
self.emoji = PartialEmoji(name=emoji)
else:
self.emoji = None
self.disabled = disabled
def __repr__(self) -> str:
return f'<Button {", ".join(["%s=%s" % (k, str(v)) for k, v in self.__dict__.items()])}>'
def __len__(self):
if self.label:
return len(self.label)
return len(self.emoji)
def set_label(self, label: str):
"""
Sets the Label of the :class:`Button`
:param label: str
The label to replace th old one with.
:return: discord.Button
"""
if len(label) > 80:
raise InvalidArgument(
'The maximum length of Button-Labels\'s are 80; your one is %s long. (%s Characters to long)' % (
len(label), len(label) - 80))
self.label = label
return self
def set_url(self, url: str):
"""
Sets the url of the :class:`Button`
:param url: str
The url to replace the old one with
:return: discord.Button
"""
if not url.startswith('http'):
raise InvalidButtonUrl(url)
self.url = url
return self
def update(self, **kwargs):
self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.__dict__.keys())
return self
def set_custom_id(self, custom_id: Union[str, int]):
"""
Sets the custom_id of the :class:`Button`
:param custom_id: Union[:class:`str`, :class:`int`]
The custom_id to replace the old one with
:return: discord.Button
"""
if self.url:
raise URLAndCustomIDNotAlowed(custom_id)
if len(custom_id) > 100:
raise InvalidArgument(
'The maximum length of Button-custom_id\'s are 100; your one is %s long. (%s Characters to long)' % (
len(custom_id), len(custom_id) - 100))
if isinstance(custom_id, str) and custom_id.isdigit():
self.custom_id = int(custom_id)
else:
self.custom_id = custom_id
return self
def disable_if(self, check: typing.Union[bool, typing.Callable], *args):
"""
Disables the :class:`discord.Button` if the passed :attr:`check` returns :bool:`True`.
Parameters
----------
check: Union[:class:`bool`, :type:`typing.Callable`]
The check could be an :class:`bool` or usually any :type:`Callable` that returns an :class:`bool`.
*args: Any
Arguments that should passed in to the :attr:`check` if it is an :type:`Callable`.
:return: discord.Button
"""
try:
check = check(*args)
except TypeError:
pass
if check is True:
self.disabled = True
return self
def set_style_if(self, check: Union[bool, typing.Callable], style: ButtonStyle, *args):
"""
Sets the style of the :class:`Button` to the specified one if the specified check returns True.
Parameters
----------
check: Union[:class:`bool`, :type:`typing.Callable`]
The check could be an :class:`bool` or usually any :type:`Callable` that returns an :class:`bool`
style: discord.ButtonStyle
The style the :class:`Button` should have when the :attr:`check` returns True
*args: Any
Arguments that should passed in to the :attr:`check` if it is an :type:`Callable`.
:return: discord.Button
"""
try:
check = check(*args)
except TypeError:
pass
if check is True:
self.style = style
return self
def to_dict(self):
base = {'type': 2, 'label': self.label, 'style': int(self.style), 'disabled': self.disabled}
if self.custom_id is not None:
base['custom_id'] = str(self.custom_id)
elif self.url:
base['url'] = self.url
if self.emoji:
base['emoji'] = self.emoji.to_dict()
return base
@classmethod
def from_dict(cls, data: dict):
style = data.get('style', None)
label = data.get('label', None)
emoji = data.get('emoji')
custom_id = data.get('custom_id', None)
url = data.get('url', None)
disabled = data.get('disabled', None)
if emoji and isinstance(emoji, dict):
emoji = PartialEmoji.from_dict(emoji)
return cls(style=style, label=label, emoji=emoji, custom_id=custom_id, url=url, disabled=disabled)
class SelectOption:
"""
A class that creates an option for a :class:`SelectMenu`
and represents it in a :class:`SelectMenu` in the components of a :class:`discord.Message`.
Read more in the `Documentation <https://discordpy-message-components.readthedocs.io/en/latest/components.html#SelectOption>`_
Parameters
----------
label: :class:`str`
the user-facing name of the option, max 25 characters
value: :class:`str`
the dev-define value of the option, max 100 characters
description: Optional[:class:`str`] = None
an additional description of the option, max 50 characters
emoji: Union[:class:`PartialEmoji`, :class:`Emoji`, :class:`str`] = None
an Emoji that will shown on the left side of the option.
default: Optional[:class:`bool`] = False
will render this option as selected by default
"""
def __init__(self, label: str,
value: str,
description: str = None,
emoji: Union[PartialEmoji, Emoji, str] = None,
default: bool = False):
if len(label) > 100:
raise AttributeError('The maximum length of the label is 100 characters.')
self.label = label
if len(value) > 100:
raise AttributeError('The maximum length of the value is 100 characters.')
self.value = value
if description and len(description) > 100:
raise AttributeError('The maximum length of the description is 100 characters.')
self.description = description
if isinstance(emoji, PartialEmoji):
self.emoji = emoji
elif isinstance(emoji, Emoji):
self.emoji = PartialEmoji(name=emoji.name, animated=emoji.animated, id=emoji.id)
elif isinstance(emoji, str):
if emoji[0] == '<':
self.emoji = PartialEmoji.from_string(emoji)
else:
self.emoji = PartialEmoji(name=emoji)
else:
self.emoji = None
self.default = default
def __repr__(self):
return f'<SelectOption {", ".join(["%s=%s" % (k, v) for (k, v) in self.__dict__.items()])}>'
def set_default(self, value: bool):
self.default = value
return self
def to_dict(self):
base = {'label': str(self.label),
'value': str(self.value),
'default': bool(self.default)}
if self.description:
base['description'] = str(self.description)
if self.emoji:
base['emoji'] = self.emoji.to_dict()
return base
@classmethod
def from_dict(cls, data):
emoji = data.pop('emoji', None)
if emoji:
emoji = PartialEmoji.from_dict(emoji)
return cls(label=data.pop('label'),
value=data.pop('value'),
description=data.pop('description', None),
emoji=emoji,
default=data.pop('default', False))
class SelectMenu:
"""
Represents a `Select-Menu <https://discord.com/developers/docs/interactions/message-components#select-menus>`_
Read more in the `Documentation <https://discordpy-message-components.readthedocs.io/en/latest/components.html#SelectMenu>`_
Parameters
----------
custom_id: str or int
A developer-defined identifier for the :class:`SelectMenu`, max. 100 characters.
options: List[:class:`SelectOption`]
A :class:`list` of choices(:class:`SelectOption`) the :class:`SelectMenu` should have, max. 25.
placeholder: Optional[:class:`str`] = None
Custom placeholder text if nothing is selected, max. 100 characters.
min_values: Optional[:class:`int`] = 1
The minimum number of items that must be chosen; default 1, min. 0, max. 25.
max_values: Optional[:class:`int`] = 1
The maximum number of items that can be chosen; default 1, max. 25.
disabled: Optional[:class:`bool`] ) = False
disable the SelectMenu, default False
"""
def __init__(self, custom_id: Union[str, int],
options: typing.List[SelectOption],
placeholder: str = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False):
if not any([isinstance(obj, SelectOption) for obj in options]):
raise InvalidArgument("SelectMenu.options must be a list of discord.SelectOption")
if len(options) > 25:
raise InvalidArgument('The maximum number of options in a SelectMenu is 25.')
self.options = options
if len(custom_id) > 100:
raise ValueError(
'The maximum length of a custom_id is 100 characters; your one is %s long (%s to long).' % (
len(custom_id), len(custom_id) - 100))
if isinstance(custom_id, str) and custom_id.isdigit():
self.custom_id = int(custom_id)
else:
self.custom_id = custom_id
if placeholder and len(placeholder) > 100:
raise AttributeError(
'The maximum length of a the placeholder is 100 characters; your one is %s long (%s to long).' % (
len(placeholder), len(placeholder) - 100))
self.placeholder = placeholder
if 25 < min_values < 0:
raise ValueError('The minimum number of elements to be selected must be between 1 and 25.')
self.min_values = min_values
if 25 < max_values <= 0:
raise ValueError('The maximum number of elements to be selected must be between 0 and 25.')
self.max_values = max_values
self.disabled = disabled
self._values = None
def __repr__(self):
return f'<SelectMenu {", ".join(["%s=%s" % (k, v) for k, v in self.__dict__.items()])}>'
@property
def all_option_values(self):
"""
All values of the :attr:`options`
If the value is a number it is returned as an integer, otherwise as string
.. note::
This is equal to
.. code-block:: python3
for option in self.options:
if option.value.isdigit():
yield int(option.value)
else:
yield option.value
"""
for option in self.options:
if option.value.isdigit():
yield int(option.value)
else:
yield option.value
def to_dict(self) -> dict:
base = {
'type': 3,
'custom_id': str(self.custom_id),
'options': [o.to_dict() for o in self.options if isinstance(o, SelectOption)],
'placeholder': self.placeholder,
'min_values': self.min_values,
'max_values': self.max_values
}
if self.disabled is True:
base['disabled'] = True
return base
@property
def values(self):
"""
The options that were selected
.. note::
This only exists if the :class:`SelectMenu` is passed as a parameter in an interaction.
If the value is a number it is returned as an integer, otherwise as string
:return: List[Union[int, str]]
"""
values = []
_values = getattr(self, '_values', [])
for value in _values:
if value.isdigit():
values.append(int(value))
else:
values.append(value)
return values
@property
def not_selected(self):
"""
The options that were **not** selected
.. note::
This only exists if the :class:`SelectMenu` is passed as a parameter in an interaction.
If the value is a number it is returned as an integer, otherwise as string
:return: List[Union[int, str]]
"""
_not_selected = []
values = self.values
for value in self.all_option_values:
if value not in values:
_not_selected.append(value)
return _not_selected
def update(self, **kwargs):
self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.__dict__.keys())
return self
def set_custom_id(self, custom_id: Union[str, int]):
"""
Set the custom_id of the :class:`SelectMenu`
:param custom_id: Union[:class:`str`, :class:`int`]
The custom_id to replace the old one with
:return: discord.SelectMenu
"""
if len(custom_id) > 100:
raise InvalidArgument(
'The maximum length of SelectMenu-custom_id\'s are 100; your one is %s long. (%s Characters to long)' % (
len(custom_id), len(custom_id) - 100))
if isinstance(custom_id, str) and custom_id.isdigit():
self.custom_id = int(custom_id)
else:
self.custom_id = custom_id
return self
def disable_if(self, check: typing.Union[bool, typing.Callable], *args):
"""
Disables the :class:`discord.SelectMenu` if the passed :attr:`check` returns :bool:`True`.
Parameters
----------
check: Union[:class:`bool`, :type:`typing.Callable`]
The check could be an :class:`bool` or usually any :obj:`Callable` that returns an :class:`bool`.
*args: Any
Arguments that should passed in to the :param:`check` if it is an :type:`Callable`.
:return: discord.SelectMenu
"""
try:
check = check(*args)
except TypeError:
pass
if check is True:
self.disabled = True
return self
@classmethod
def from_dict(cls, data: dict):
return cls(custom_id=data.pop('custom_id'),
options=[SelectOption.from_dict(o) for o in data.pop('options')],
placeholder=data.pop('placeholder', None),
min_values=data.pop('min_values', 1),
max_values=data.pop('max_values', 1))
class ActionRow:
"""
Represents an ActionRow-Part for the components of an :class:`discord.Message`.
Read more in the `Documentation <https://discordpy-message-components.readthedocs.io/en/latest/components.html#ActionRow>`_
Parameters
----------
*components: *Union[:class:`Button, :class:`SelectMenu`]
The components the :class:`ActionRow` should have. It could contain at least 5 :class:`Button`or 1 :class:`SelectMenu`.
.. note ::
For more information about ActionRow's visit the `Discord-APIMethodes Documentation <https://discord.com/developers/docs/interactions/message-components#actionrow>`_.
"""
def __init__(self, *components):
self.components = []
for component in components:
if isinstance(component, (Button, SelectMenu)):
self.components.append(component)
elif isinstance(component, dict):
if not component.get('type', None) in [2, 3]:
raise InvalidArgument(
'If you use an Dict instead of Button or SelectMenu you have to pass an type between 2 or 3')
self.components.append(
{2: Button.from_dict(component), 3: SelectMenu.from_dict(component)}.get(component.get('type')))
def __repr__(self):
return f'<ActionRow components={self.components}>'
def __iter__(self):
for component in self.components:
yield component
def to_dict(self) -> Union[list, EmptyActionRow]:
base = []
base.extend([{'type': 1, 'components': [obj.to_dict() for obj in self.components[five:5:]]} for five in
range(0, len(self.components), 5)])
objects = len([i['components'] for i in base])
if any([any([part['type'] == 2]) and any([part['type'] == 3]) for part in base]):
raise InvalidArgument('An ActionRow containing a select menu cannot also contain buttons')
if any([any([part['type'] == 3]) and len(part) > 1 for part in base]):
raise InvalidArgument('An ActionRow can contain only one SelectMenu')
if any([len(ar['components']) < 1 for ar in base]):
raise EmptyActionRow from base
elif len(base) > 5 or objects > 25:
raise InvalidArgument(
f"The maximum number of ActionRow's per message is 5 and they can only contain 5 Buttons or 1 Select-Menu each; you have {len(base)} ActionRow's passed with {objects} objects")
return base
def __len__(self):
return len(self.components)
def __invert__(self):
return self.components
def __getitem__(self, item) -> Union[Button, SelectMenu, None]:
return self.components.get(item, None)
def __setitem__(self, index, component):
return self.set_component_at(index, component)
def __reversed__(self):
return reversed(self.components)
def add_component(self, component: Union[Button, SelectMenu]):
"""
Adds a component to the :class:`ActionRow`.
Parameters
----------
component: Union[:class:`Button`, :class:`SelectMenu`]
The component to add to the ActionRow.
:return: discord.ActionRow
"""
self.components.append(component)
return self
def insert_component_at(self, index, component: Union[Button, SelectMenu]):
"""
Inserts a component before a specified index to the :class:`ActionRow`.
Parameters
-----------
index: :class:`int`
The index of where to insert the component.
component: Union[:class:`Button`, :class:`SelectMenu`]
The component to insert.
:return: discord.ActionRow
"""
self.components.insert(index, component)
return self
def set_component_at(self, index, component: Union[Button, SelectMenu]):
"""
Modifies a component to the ActionRow object.
The index must point to a valid pre-existing component.
Parameters
----------
index: :class:`int`
The index of the component to modify.
component: Union[:class:`Button`, :class:`SelectMenu`]
The component to replace the old one with.
Raises
-------
IndexError
An invalid index was provided.
:return: discord.ActionRow
"""
try:
_component = self.components[index]
except IndexError:
raise IndexError('component index %s out of range' % index)
_component = component
return self
def disable_component_at(self, index):
"""
Disables the component at the specified position.
Parameters
----------
index: int
The position of the component to be deactivated in the ActionRow.
Raises
------
IndexError
The specified index is outside the length of the actionRow.
:return: discord.ActionRow
"""
try:
component = self.components[index]
except IndexError:
raise IndexError('component index %s out of range' % index)
component.disabled = True
return self
def add_components(self, *components: Union[Button, SelectMenu]):
"""
Adds multiple components to the :class:`ActionRow`.
Parameters
----------
*components: *Union[:class:`Button`, :class:`SelectMenu`]
The components to add to the ActionRow.
:return: discord.ActionRow
"""
self.components.extend(*components)
return self
def disable_all_components(self):
"""
Disables all component's in this :class:`ActionRow`.
:return: discord.ActionRow
"""
[obj.__setattr__('disabled', True) for obj in self.components]
return self
def disable_all_components_if(self, check: Union[bool, typing.Callable], *args: typing.Any):
"""
Disables all :attr:`components` in this :class:`ActionRow` if the passed :attr:`check` returns :bool:`True`.
Parameters
-----------
check: Union[:class:`bool`, :type:`typing.Callable`]
Could be an bool or usually any Callable that returns a bool.
*args: Any
Arguments that should passed in to the check if it is a Callable.
:return: discord.ActionRow
"""
if not isinstance(check, (bool, typing.Callable)):
raise AttributeError(
'The check must bee a bool or any callable that returns one. Not {0.__class__.__name__}'.format(check))
try:
check = check(*args)
except TypeError:
pass
if check is True:
[obj.__setattr__('disabled', True) for obj in self.components]
return self
def disable_all_buttons(self):
"""
Disables all ::class:`discord.Button`'s in this :class:`ActionRow`.
:return: discord.ActionRow
"""
[obj.__setattr__('disabled', True) for obj in self.components if isinstance(obj, Button)]
return self
def disable_all_buttons_if(self, check: Union[bool, typing.Callable], *args: typing.Any):
"""
Disables all :class:`discord.Button`'s in this :class:`ActionRow` if the passed :attr:`check` returns :bool:`True`.
Parameters
-----------
check: Union[:class:`bool`, :type:`typing.Callable`]
Could be an bool or usually any Callable that returns a bool.
*args: Any
Arguments that should passed in to the check if it is a Callable.
:return: discord.ActionRow
"""
if not isinstance(check, (bool, typing.Callable)):
raise AttributeError(
'The check must bee a bool or any callable that returns one. Not {0.__class__.__name__}'.format(check))
try:
check = check(*args)
except TypeError:
pass
if check is True:
[obj.__setattr__('disabled', True) for obj in self.components if isinstance(obj, Button)]
return self
def disable_all_select_menus(self):
"""
Disables all :class:`discord.SelectMenu`'s in this :class:`ActionRow`.
:return: discord.ActionRow
"""
[obj.__setattr__('disabled', True) for obj in self.components if isinstance(obj, SelectMenu)]
return self
def disable_all_select_menus_if(self, check: Union[bool, typing.Callable], *args: typing.Any):
"""
Disables all :class:`SelectMenu`'s in this :class:`ActionRow` if the passed :attr:`check` returns :bool:`True`.
Parameters
----------
check: Union[:class:`bool`, :class:`typing.Callable`]
could be an :class:`bool` or usually any :type:`Callable` that returns a :class:`bool`
*args: Any
Arguments that should passed in to the :param:`check` if it is a :type:`Callable`.
:return: discord.ActionRow
"""
if not isinstance(check, (bool, typing.Callable)):
raise AttributeError(
'The check must bee a bool or any callable that returns one. Not {0.__class__.__name__}'.format(check))
try:
check = check(*args)
except TypeError:
pass
if check is True:
[obj.__setattr__('disabled', True) for obj in self.components if isinstance(obj, SelectMenu)]
return self
@classmethod
def from_dict(cls, data):
if data.get('type', None) != 1:
return InvalidArgument("%s could not be implemented as an ActionRow" % data)
else:
components = [_component_factory(component) for component in data.get('components', [])]
return cls(*components)
def _component_factory(data):
component_type = data.get('type', None)
if component_type == ComponentType.ActionRow:
return ActionRow.from_dict(data)
elif component_type == ComponentType.Button:
return Button.from_dict(data)
elif component_type == ComponentType.SelectMenu:
return SelectMenu.from_dict(data)
else:
return None