Skip to content

Commit af07707

Browse files
authored
Add files via upload
1 parent 19b1863 commit af07707

File tree

2 files changed

+50
-35
lines changed

2 files changed

+50
-35
lines changed

discord/components.py

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
from .errors import InvalidArgument, InvalidButtonUrl, URLAndCustomIDNotAlowed, InvalidData, EmptyActionRow
3636
URL_REGEX = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
3737

38+
3839
class ButtonStyle:
3940
"""
4041
:class:`ButtonS
@@ -51,6 +52,7 @@ class ButtonStyle:
5152

5253
__repr__ = [Primary, Secondary, Success, Danger, Link_Button]
5354

55+
5456
class ButtonColor:
5557
"""
5658
:class:`ButtonColor`
@@ -65,23 +67,24 @@ class ButtonColor:
6567
grey_url = ButtonStyle.Link_Button
6668

6769

68-
class Button:
70+
class Button(object):
6971
"""
7072
:class:`Button`
7173
72-
Represens an ``Discord-Button``
74+
Represents an ``Discord-Button``
7375
7476
.. note ::
7577
For more information Discord-Button's visit the `Discord-API Documentation <https://discord.com/developers/docs/interactions/message-components#buttons>`_.
7678
"""
79+
7780
def __init__(self, **kwargs):
7881
self._style = kwargs.get('style', kwargs.get('color', ButtonStyle.Secondary))
7982
self._url: str = kwargs.get('url', None)
8083
if self._url and not re.match(URL_REGEX, self.url):
8184
raise InvalidButtonUrl(self.url)
82-
if not self._style in [1, 2, 3, 4, 5]:
85+
if self._style not in [1, 2, 3, 4, 5]:
8386
raise InvalidArgument(
84-
"The Style of an discord.Button have to be an Object of discord.ButtonStyle, discord.ButtonColor or usaly an Integer betwean 1 and 5")
87+
"The Style of an discord.Button have to be an Object of discord.ButtonStyle, discord.ButtonColor or usually an Integer between 1 and 5")
8588
if self._style == ButtonStyle.Link_Button and not self.url:
8689
raise MissingRequiredArgument(
8790
'You must also pass a URL if the ButtonStyle is a link.')
@@ -90,12 +93,12 @@ def __init__(self, **kwargs):
9093
self._custom_id: str = kwargs.get('custom_id', None)
9194
if self._custom_id and len(self.custom_id) > 100:
9295
raise InvalidArgument(
93-
'The maximum length of Button-custom_id\'s are 100; youre one is %s long. (%s Characters to long)' % (len(self.custom_id), len(self.custom_id) - 100))
96+
'The maximum length of Button-custom_id\'s are 100; your one is %s long. (%s Characters to long)' % (len(self.custom_id), len(self.custom_id) - 100))
9497
if self._custom_id and self.url:
9598
raise URLAndCustomIDNotAlowed(self.custom_id)
9699
self._label: str = kwargs.get('label', kwargs.get('name', 'I\'m an Button'))
97100
if self._label and len(self._label) > 80:
98-
raise InvalidArgument(f'The maximum length of Button-Labels\'s are 80; youre one is {len(self.label)} long. ({len(self.label) - 100} Characters to long)')
101+
raise InvalidArgument(f'The maximum length of Button-Labels\'s are 80; your one is {len(self.label)} long. ({len(self.label) - 100} Characters to long)')
99102
self._emoji = kwargs.get('emoji', None)
100103
if isinstance(self._emoji, Emoji):
101104
self._emoji = PartialEmoji(name=self._emoji.name, animated=self._emoji.animated, id=self._emoji.id)
@@ -105,8 +108,11 @@ def __init__(self, **kwargs):
105108
self._emoji = None
106109
self._disabled: bool = kwargs.get('disabled', False)
107110

111+
def __repr__(self):
112+
return f'<discord.Button {" ".join([k+"="+v for k, v in self.__dict__.items()])}'
113+
108114
@property
109-
def style(self) -> ButtonStyle:
115+
def style(self) -> int:
110116
return self._style
111117

112118
@property
@@ -115,7 +121,7 @@ def label(self) -> Union[str, None]:
115121

116122
def set_label(self, label: str):
117123
if len(label) > 80:
118-
raise InvalidArgument(f'The maximum length of Button-Labels\'s are 80; youre one is {len(label)} long. ({len(label) - 100} Characters to long)')
124+
raise InvalidArgument(f'The maximum length of Button-Labels\'s are 80; your one is {len(label)} long. ({len(label) - 100} Characters to long)')
119125
self._label = label
120126
return self
121127

@@ -134,13 +140,13 @@ def custom_id(self) -> str:
134140
return self._custom_id
135141

136142
def update(self, **kwargs):
137-
self.__setattr__(**kwargs)
143+
self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.__dict__.keys())
138144
return self
139145

140146
def set_custom_id(self, custom_id: str):
141147
if len(custom_id) > 100:
142148
raise InvalidArgument(
143-
'The maximum length of Button-custom_id\'s are 100; youre one is %s long. (%s Characters to long)' % (len(custom_id), len(custom_id) - 100))
149+
'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))
144150
if self._custom_id and self.url:
145151
raise URLAndCustomIDNotAlowed(self.custom_id)
146152
self._custom_id = custom_id
@@ -161,7 +167,7 @@ def disable_if(self, check: typing.Union[bool, typing.Callable], **kwargs):
161167
______________
162168
163169
``Parameters:``
164-
- ``check:`` could be an :class:`bool` or usaly any :obj:`Callable` that returns an :class:`bool`
170+
- ``check:`` could be an :class:`bool` or usually any :obj:`Callable` that returns an :class:`bool`
165171
- ``**kwargs:`` :obj:`kwargs` that should passed in to the :pram:`check` if it is an :obj:`Callable`
166172
167173
:return: :class:`discord.Button`
@@ -176,7 +182,7 @@ def disable_if(self, check: typing.Union[bool, typing.Callable], **kwargs):
176182

177183
def set_color_if(self, check: Union[bool, typing.Callable], color: any(ButtonStyle.__repr__), **kwargs):
178184
"""
179-
Sets the Color(Style) of an :class:`discord.Button` to the providet ``color`` if the passed ``check`` returns :bool:`True`.
185+
Sets the Color(Style) of an :class:`discord.Button` to the provided ``color`` if the passed ``check`` returns :bool:`True`.
180186
181187
______________
182188
@@ -219,26 +225,31 @@ def from_dict(cls, data: dict):
219225

220226
return cls(style=style, label=label, emoji=emoji, custom_id=custom_id, url=url, disabled=disabled)
221227

228+
222229
def create_option(label: str, value: str):
223230
return {'label': label, 'value': value}
224231

232+
225233
class DropdownMenue:
226234
"""
227235
Represents an Discord-dropdown-Menue
228236
.. note ::
229237
This Feature is ``not`` released jet!
230238
"""
239+
__slots__ = ['__custom_id', '__options']
240+
231241
def __init__(self, **kwargs):
232242
self.__options: list = kwargs.get('options', [])
233243
if not [type(obj) == dict for obj in self._options]:
234-
raise InvalidData("DropdownMenue-Options have to bee an Dict like `{'label': 'that wath should show up in Discord', 'value': 'that wath the Discord-API sends to your Application if the option is choosen'}`, or usaly an :function:`discord.components.create_option`.")
244+
raise InvalidData("DropdownMenue-Options have to bee an Dict like `{'label': 'that what should show up in Discord', 'value': 'that what the Discord-API sends to your Application if the option is chosen'}`, or usually an :function:`discord.components.create_option`.")
235245
self.__custom_id: str = kwargs.get('custom_id', 'no_custom_id_set')
236246

237247
def to_dict(self) -> dict:
238248
return {'type': 3, 'custom_id': self.__custom_id, 'options': self.__options}
239249

240250
def update(self, **kwargs):
241-
return self.__setattr__(**kwargs)
251+
self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.__dict__.keys())
252+
return self
242253

243254
@classmethod
244255
def from_dict(cls, data: dict):
@@ -262,37 +273,37 @@ def __init__(self, *args, **kwargs):
262273
.. note ::
263274
For more information about ActionRow's visit the `Discord-API Documentation <https://discord.com/developers/docs/interactions/message-components#actionrow>`_.
264275
"""
265-
self.base: dict = {'type': 1, 'components': []}
266276
self.components = []
267277
self.force = kwargs.get('force', False)
268278
for obj in args:
269279
if isinstance(obj, Button):
270-
self.base['components'].append(obj.to_dict())
271280
self.components.append(obj)
272281
elif isinstance(obj, DropdownMenue):
273-
self.base['components'].append(obj.to_dict())
274282
self.components.append(obj)
275283
elif isinstance(obj, dict):
276284
if not obj.get('type', None) in [2, 3]:
277-
raise InvalidData('if you use an Dict instad of Button, DropdownMenue you have to pass an type')
278-
self.base['components'].append({1: Button.from_dict(obj).to_dict(), 2: DropdownMenue.from_dict(obj).to_dict()}.get(obj.get('type')))
285+
raise InvalidData('if you use an Dict instead of Button, DropdownMenue you have to pass an type')
279286
self.components.append({1: Button.from_dict(obj), 2: DropdownMenue.from_dict(obj)}.get(obj.get('type')))
280287

281288
def sendable(self) -> Union[dict, EmptyActionRow]:
282-
if not len(self.base['components']) >= 1 and self.force is False:
289+
base = {'type': 1, 'components': [obj.to_dict() for obj in self.components]}
290+
if not len(base['components']) >= 1 and self.force is False:
283291
raise EmptyActionRow()
284-
return self.base
292+
return base
285293

286294
def edit_obj(self, index: int, **kwargs):
287295
obj: Union[Button, DropdownMenue] = self.components.pop(index)
288-
self.base['components'].pop(index)
296+
self.components.pop(index)
289297
self.components.insert(index, obj.update(**kwargs))
290-
self.base['components'].insert(index, obj.update(**kwargs))
298+
return self
299+
300+
def disable_all_buttons(self):
301+
[obj.__setattr__('_disabled', True) for obj in self.components if isinstance(obj, Button)]
291302
return self
292303

293304
@property
294305
def raw(self) -> dict:
295-
return self.base
306+
return {'type': 1, 'components': [obj.to_dict() for obj in self.components]}
296307

297308
@classmethod
298309
def from_dict(cls, data):
@@ -344,6 +355,7 @@ def custom_id(self):
344355
def component_type(self):
345356
return self._component_type
346357

358+
347359
class DecodeMessageComponents:
348360
def __init__(self, value):
349361
self._action_rows = []
@@ -353,12 +365,11 @@ def __init__(self, value):
353365
self._other_elements.append(ActionRow.from_dict(obj))
354366
except InvalidData:
355367
self._other_elements.append(obj)
356-
return self._action_rows
357368

358369
@property
359370
def action_rows(self):
360371
return self._action_rows
361372

362373
@property
363374
def other_elements(self):
364-
return self._other_elements
375+
return self._other_elements

discord/message.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
'DeletedReferencedMessage',
6060
)
6161

62+
6263
def convert_emoji_reaction(emoji):
6364
if isinstance(emoji, Reaction):
6465
emoji = emoji.emoji
@@ -406,6 +407,7 @@ def to_dict(self):
406407

407408
to_message_reference_dict = to_dict
408409

410+
409411
def flatten_handlers(cls):
410412
prefix = len('_handle_')
411413
handlers = [
@@ -422,6 +424,7 @@ def flatten_handlers(cls):
422424
]
423425
return cls
424426

427+
425428
@flatten_handlers
426429
class Message(Hashable):
427430
r"""Represents a message from Discord.
@@ -1100,25 +1103,24 @@ async def edit(self, **fields):
11001103
pass
11011104
else:
11021105
if components is not None:
1103-
from .components import Button, ActionRow
1106+
from .components import Button, DropdownMenue, ActionRow
11041107
components_list = []
11051108
for component in ([components] if not type(components) == list else components):
11061109
if isinstance(component, Button):
11071110
components_list.append(component.to_dict())
1108-
elif isinstance(component, DropDownMenu):
1111+
elif isinstance(component, DropdownMenue):
11091112
components_list.append(component.to_dict())
11101113
elif isinstance(component, ActionRow):
11111114
components_list.append(component.sendable())
1112-
components = components_list
11131115
fields['components'] = components_list
11141116
try:
11151117
suppress = fields.pop('suppress')
11161118
except KeyError:
11171119
pass
11181120
else:
1119-
flags = MessageFlags._from_value(self.flags.value)
1120-
flags.suppress_embeds = suppress
1121-
fields['flags'] = flags.value
1121+
flags = MessageFlags._from_value(self.flags.value)
1122+
flags.suppress_embeds = suppress
1123+
fields['flags'] = flags.value
11221124

11231125
delete_after = fields.pop('delete_after', None)
11241126

@@ -1414,13 +1416,15 @@ def to_message_reference_dict(self):
14141416

14151417
return data
14161418

1419+
14171420
def implement_partial_methods(cls):
14181421
msg = Message
14191422
for name in cls._exported_names:
14201423
func = getattr(msg, name)
14211424
setattr(cls, name, func)
14221425
return cls
14231426

1427+
14241428
@implement_partial_methods
14251429
class PartialMessage(Hashable):
14261430
"""Represents a partial message to aid with working messages when only
@@ -1607,9 +1611,9 @@ async def edit(self, **fields):
16071611
except KeyError:
16081612
pass
16091613
else:
1610-
flags = MessageFlags._from_value(0)
1611-
flags.suppress_embeds = suppress
1612-
fields['flags'] = flags.value
1614+
flags = MessageFlags._from_value(0)
1615+
flags.suppress_embeds = suppress
1616+
fields['flags'] = flags.value
16131617

16141618
delete_after = fields.pop('delete_after', None)
16151619

0 commit comments

Comments
 (0)