Run black on the repository, with the default configuration.
This commit is contained in:
@@ -35,16 +35,16 @@ from ..partial_emoji import PartialEmoji, _EmojiTag
|
||||
from ..components import Button as ButtonComponent
|
||||
|
||||
__all__ = (
|
||||
'Button',
|
||||
'button',
|
||||
"Button",
|
||||
"button",
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .view import View
|
||||
from ..emoji import Emoji
|
||||
|
||||
B = TypeVar('B', bound='Button')
|
||||
V = TypeVar('V', bound='View', covariant=True)
|
||||
B = TypeVar("B", bound="Button")
|
||||
V = TypeVar("V", bound="View", covariant=True)
|
||||
|
||||
|
||||
class Button(Item[V]):
|
||||
@@ -76,12 +76,12 @@ class Button(Item[V]):
|
||||
"""
|
||||
|
||||
__item_repr_attributes__: Tuple[str, ...] = (
|
||||
'style',
|
||||
'url',
|
||||
'disabled',
|
||||
'label',
|
||||
'emoji',
|
||||
'row',
|
||||
"style",
|
||||
"url",
|
||||
"disabled",
|
||||
"label",
|
||||
"emoji",
|
||||
"row",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
@@ -97,7 +97,7 @@ class Button(Item[V]):
|
||||
):
|
||||
super().__init__()
|
||||
if custom_id is not None and url is not None:
|
||||
raise TypeError('cannot mix both url and custom_id with Button')
|
||||
raise TypeError("cannot mix both url and custom_id with Button")
|
||||
|
||||
self._provided_custom_id = custom_id is not None
|
||||
if url is None and custom_id is None:
|
||||
@@ -112,7 +112,9 @@ class Button(Item[V]):
|
||||
elif isinstance(emoji, _EmojiTag):
|
||||
emoji = emoji._to_partial()
|
||||
else:
|
||||
raise TypeError(f'expected emoji to be str, Emoji, or PartialEmoji not {emoji.__class__}')
|
||||
raise TypeError(
|
||||
f"expected emoji to be str, Emoji, or PartialEmoji not {emoji.__class__}"
|
||||
)
|
||||
|
||||
self._underlying = ButtonComponent._raw_construct(
|
||||
type=ComponentType.button,
|
||||
@@ -145,7 +147,7 @@ class Button(Item[V]):
|
||||
@custom_id.setter
|
||||
def custom_id(self, value: Optional[str]):
|
||||
if value is not None and not isinstance(value, str):
|
||||
raise TypeError('custom_id must be None or str')
|
||||
raise TypeError("custom_id must be None or str")
|
||||
|
||||
self._underlying.custom_id = value
|
||||
|
||||
@@ -157,7 +159,7 @@ class Button(Item[V]):
|
||||
@url.setter
|
||||
def url(self, value: Optional[str]):
|
||||
if value is not None and not isinstance(value, str):
|
||||
raise TypeError('url must be None or str')
|
||||
raise TypeError("url must be None or str")
|
||||
self._underlying.url = value
|
||||
|
||||
@property
|
||||
@@ -191,7 +193,9 @@ class Button(Item[V]):
|
||||
elif isinstance(value, _EmojiTag):
|
||||
self._underlying.emoji = value._to_partial()
|
||||
else:
|
||||
raise TypeError(f'expected str, Emoji, or PartialEmoji, received {value.__class__} instead')
|
||||
raise TypeError(
|
||||
f"expected str, Emoji, or PartialEmoji, received {value.__class__} instead"
|
||||
)
|
||||
else:
|
||||
self._underlying.emoji = None
|
||||
|
||||
@@ -273,17 +277,17 @@ def button(
|
||||
|
||||
def decorator(func: ItemCallbackType) -> ItemCallbackType:
|
||||
if not inspect.iscoroutinefunction(func):
|
||||
raise TypeError('button function must be a coroutine function')
|
||||
raise TypeError("button function must be a coroutine function")
|
||||
|
||||
func.__discord_ui_model_type__ = Button
|
||||
func.__discord_ui_model_kwargs__ = {
|
||||
'style': style,
|
||||
'custom_id': custom_id,
|
||||
'url': None,
|
||||
'disabled': disabled,
|
||||
'label': label,
|
||||
'emoji': emoji,
|
||||
'row': row,
|
||||
"style": style,
|
||||
"custom_id": custom_id,
|
||||
"url": None,
|
||||
"disabled": disabled,
|
||||
"label": label,
|
||||
"emoji": emoji,
|
||||
"row": row,
|
||||
}
|
||||
return func
|
||||
|
||||
|
||||
@@ -24,21 +24,30 @@ DEALINGS IN THE SOFTWARE.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Coroutine, Dict, Generic, Optional, TYPE_CHECKING, Tuple, Type, TypeVar
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Generic,
|
||||
Optional,
|
||||
TYPE_CHECKING,
|
||||
Tuple,
|
||||
Type,
|
||||
TypeVar,
|
||||
)
|
||||
|
||||
from ..interactions import Interaction
|
||||
|
||||
__all__ = (
|
||||
'Item',
|
||||
)
|
||||
__all__ = ("Item",)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..enums import ComponentType
|
||||
from .view import View
|
||||
from ..components import Component
|
||||
|
||||
I = TypeVar('I', bound='Item')
|
||||
V = TypeVar('V', bound='View', covariant=True)
|
||||
I = TypeVar("I", bound="Item")
|
||||
V = TypeVar("V", bound="View", covariant=True)
|
||||
ItemCallbackType = Callable[[Any, I, Interaction], Coroutine[Any, Any, Any]]
|
||||
|
||||
|
||||
@@ -53,7 +62,7 @@ class Item(Generic[V]):
|
||||
.. versionadded:: 2.0
|
||||
"""
|
||||
|
||||
__item_repr_attributes__: Tuple[str, ...] = ('row',)
|
||||
__item_repr_attributes__: Tuple[str, ...] = ("row",)
|
||||
|
||||
def __init__(self):
|
||||
self._view: Optional[V] = None
|
||||
@@ -91,8 +100,10 @@ class Item(Generic[V]):
|
||||
return self._provided_custom_id
|
||||
|
||||
def __repr__(self) -> str:
|
||||
attrs = ' '.join(f'{key}={getattr(self, key)!r}' for key in self.__item_repr_attributes__)
|
||||
return f'<{self.__class__.__name__} {attrs}>'
|
||||
attrs = " ".join(
|
||||
f"{key}={getattr(self, key)!r}" for key in self.__item_repr_attributes__
|
||||
)
|
||||
return f"<{self.__class__.__name__} {attrs}>"
|
||||
|
||||
@property
|
||||
def row(self) -> Optional[int]:
|
||||
@@ -105,7 +116,7 @@ class Item(Generic[V]):
|
||||
elif 5 > value >= 0:
|
||||
self._row = value
|
||||
else:
|
||||
raise ValueError('row cannot be negative or greater than or equal to 5')
|
||||
raise ValueError("row cannot be negative or greater than or equal to 5")
|
||||
|
||||
@property
|
||||
def width(self) -> int:
|
||||
|
||||
@@ -39,8 +39,8 @@ from ..components import (
|
||||
)
|
||||
|
||||
__all__ = (
|
||||
'Select',
|
||||
'select',
|
||||
"Select",
|
||||
"select",
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -50,8 +50,8 @@ if TYPE_CHECKING:
|
||||
ComponentInteractionData,
|
||||
)
|
||||
|
||||
S = TypeVar('S', bound='Select')
|
||||
V = TypeVar('V', bound='View', covariant=True)
|
||||
S = TypeVar("S", bound="Select")
|
||||
V = TypeVar("V", bound="View", covariant=True)
|
||||
|
||||
|
||||
class Select(Item[V]):
|
||||
@@ -89,11 +89,11 @@ class Select(Item[V]):
|
||||
"""
|
||||
|
||||
__item_repr_attributes__: Tuple[str, ...] = (
|
||||
'placeholder',
|
||||
'min_values',
|
||||
'max_values',
|
||||
'options',
|
||||
'disabled',
|
||||
"placeholder",
|
||||
"min_values",
|
||||
"max_values",
|
||||
"options",
|
||||
"disabled",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
@@ -131,7 +131,7 @@ class Select(Item[V]):
|
||||
@custom_id.setter
|
||||
def custom_id(self, value: str):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError('custom_id must be None or str')
|
||||
raise TypeError("custom_id must be None or str")
|
||||
|
||||
self._underlying.custom_id = value
|
||||
|
||||
@@ -143,7 +143,7 @@ class Select(Item[V]):
|
||||
@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')
|
||||
raise TypeError("placeholder must be None or str")
|
||||
|
||||
self._underlying.placeholder = value
|
||||
|
||||
@@ -173,9 +173,9 @@ class Select(Item[V]):
|
||||
@options.setter
|
||||
def options(self, value: List[SelectOption]):
|
||||
if not isinstance(value, list):
|
||||
raise TypeError('options must be a list of SelectOption')
|
||||
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')
|
||||
raise TypeError("all list items must subclass SelectOption")
|
||||
|
||||
self._underlying.options = value
|
||||
|
||||
@@ -224,7 +224,6 @@ class Select(Item[V]):
|
||||
default=default,
|
||||
)
|
||||
|
||||
|
||||
self.append_option(option)
|
||||
|
||||
def append_option(self, option: SelectOption):
|
||||
@@ -242,7 +241,7 @@ class Select(Item[V]):
|
||||
"""
|
||||
|
||||
if len(self._underlying.options) > 25:
|
||||
raise ValueError('maximum number of options already provided')
|
||||
raise ValueError("maximum number of options already provided")
|
||||
|
||||
self._underlying.options.append(option)
|
||||
|
||||
@@ -272,7 +271,7 @@ class Select(Item[V]):
|
||||
|
||||
def refresh_state(self, interaction: Interaction) -> None:
|
||||
data: ComponentInteractionData = interaction.data # type: ignore
|
||||
self._selected_values = data.get('values', [])
|
||||
self._selected_values = data.get("values", [])
|
||||
|
||||
@classmethod
|
||||
def from_component(cls: Type[S], component: SelectMenu) -> S:
|
||||
@@ -340,17 +339,17 @@ def select(
|
||||
|
||||
def decorator(func: ItemCallbackType) -> ItemCallbackType:
|
||||
if not inspect.iscoroutinefunction(func):
|
||||
raise TypeError('select function must be a coroutine function')
|
||||
raise TypeError("select function must be a coroutine function")
|
||||
|
||||
func.__discord_ui_model_type__ = Select
|
||||
func.__discord_ui_model_kwargs__ = {
|
||||
'placeholder': placeholder,
|
||||
'custom_id': custom_id,
|
||||
'row': row,
|
||||
'min_values': min_values,
|
||||
'max_values': max_values,
|
||||
'options': options,
|
||||
'disabled': disabled,
|
||||
"placeholder": placeholder,
|
||||
"custom_id": custom_id,
|
||||
"row": row,
|
||||
"min_values": min_values,
|
||||
"max_values": max_values,
|
||||
"options": options,
|
||||
"disabled": disabled,
|
||||
}
|
||||
return func
|
||||
|
||||
|
||||
@@ -23,7 +23,18 @@ DEALINGS IN THE SOFTWARE.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Any, Callable, ClassVar, Dict, Iterator, List, Optional, Sequence, TYPE_CHECKING, Tuple
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
ClassVar,
|
||||
Dict,
|
||||
Iterator,
|
||||
List,
|
||||
Optional,
|
||||
Sequence,
|
||||
TYPE_CHECKING,
|
||||
Tuple,
|
||||
)
|
||||
from functools import partial
|
||||
from itertools import groupby
|
||||
|
||||
@@ -41,9 +52,7 @@ from ..components import (
|
||||
SelectMenu as SelectComponent,
|
||||
)
|
||||
|
||||
__all__ = (
|
||||
'View',
|
||||
)
|
||||
__all__ = ("View",)
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -74,9 +83,7 @@ def _component_to_item(component: Component) -> Item:
|
||||
|
||||
|
||||
class _ViewWeights:
|
||||
__slots__ = (
|
||||
'weights',
|
||||
)
|
||||
__slots__ = ("weights",)
|
||||
|
||||
def __init__(self, children: List[Item]):
|
||||
self.weights: List[int] = [0, 0, 0, 0, 0]
|
||||
@@ -92,13 +99,15 @@ class _ViewWeights:
|
||||
if weight + item.width <= 5:
|
||||
return index
|
||||
|
||||
raise ValueError('could not find open space for item')
|
||||
raise ValueError("could not find open space for item")
|
||||
|
||||
def add_item(self, item: Item) -> None:
|
||||
if item.row is not None:
|
||||
total = self.weights[item.row] + item.width
|
||||
if total > 5:
|
||||
raise ValueError(f'item would not fit at row {item.row} ({total} > 5 width)')
|
||||
raise ValueError(
|
||||
f"item would not fit at row {item.row} ({total} > 5 width)"
|
||||
)
|
||||
self.weights[item.row] = total
|
||||
item._rendered_row = item.row
|
||||
else:
|
||||
@@ -144,11 +153,11 @@ class View:
|
||||
children: List[ItemCallbackType] = []
|
||||
for base in reversed(cls.__mro__):
|
||||
for member in base.__dict__.values():
|
||||
if hasattr(member, '__discord_ui_model_type__'):
|
||||
if hasattr(member, "__discord_ui_model_type__"):
|
||||
children.append(member)
|
||||
|
||||
if len(children) > 25:
|
||||
raise TypeError('View cannot have more than 25 children')
|
||||
raise TypeError("View cannot have more than 25 children")
|
||||
|
||||
cls.__view_children_items__ = children
|
||||
|
||||
@@ -156,7 +165,9 @@ class View:
|
||||
self.timeout = timeout
|
||||
self.children: List[Item] = []
|
||||
for func in self.__view_children_items__:
|
||||
item: Item = func.__discord_ui_model_type__(**func.__discord_ui_model_kwargs__)
|
||||
item: Item = func.__discord_ui_model_type__(
|
||||
**func.__discord_ui_model_kwargs__
|
||||
)
|
||||
item.callback = partial(func, self, item)
|
||||
item._view = self
|
||||
setattr(self, func.__name__, item)
|
||||
@@ -171,7 +182,7 @@ class View:
|
||||
self.__stopped: asyncio.Future[bool] = loop.create_future()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<{self.__class__.__name__} timeout={self.timeout} children={len(self.children)}>'
|
||||
return f"<{self.__class__.__name__} timeout={self.timeout} children={len(self.children)}>"
|
||||
|
||||
async def __timeout_task_impl(self) -> None:
|
||||
while True:
|
||||
@@ -203,15 +214,17 @@ class View:
|
||||
|
||||
components.append(
|
||||
{
|
||||
'type': 1,
|
||||
'components': children,
|
||||
"type": 1,
|
||||
"components": children,
|
||||
}
|
||||
)
|
||||
|
||||
return components
|
||||
|
||||
@classmethod
|
||||
def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> View:
|
||||
def from_message(
|
||||
cls, message: Message, /, *, timeout: Optional[float] = 180.0
|
||||
) -> View:
|
||||
"""Converts a message's components into a :class:`View`.
|
||||
|
||||
The :attr:`.Message.components` of a message are read-only
|
||||
@@ -261,10 +274,10 @@ class View:
|
||||
"""
|
||||
|
||||
if len(self.children) > 25:
|
||||
raise ValueError('maximum number of children exceeded')
|
||||
raise ValueError("maximum number of children exceeded")
|
||||
|
||||
if not isinstance(item, Item):
|
||||
raise TypeError(f'expected Item not {item.__class__!r}')
|
||||
raise TypeError(f"expected Item not {item.__class__!r}")
|
||||
|
||||
self.__weights.add_item(item)
|
||||
|
||||
@@ -327,7 +340,9 @@ class View:
|
||||
"""
|
||||
pass
|
||||
|
||||
async def on_error(self, error: Exception, item: Item, interaction: Interaction) -> None:
|
||||
async def on_error(
|
||||
self, error: Exception, item: Item, interaction: Interaction
|
||||
) -> None:
|
||||
"""|coro|
|
||||
|
||||
A callback that is called when an item's callback or :meth:`interaction_check`
|
||||
@@ -344,8 +359,10 @@ class View:
|
||||
interaction: :class:`~discord.Interaction`
|
||||
The interaction that led to the failure.
|
||||
"""
|
||||
print(f'Ignoring exception in view {self} for item {item}:', file=sys.stderr)
|
||||
traceback.print_exception(error.__class__, error, error.__traceback__, file=sys.stderr)
|
||||
print(f"Ignoring exception in view {self} for item {item}:", file=sys.stderr)
|
||||
traceback.print_exception(
|
||||
error.__class__, error, error.__traceback__, file=sys.stderr
|
||||
)
|
||||
|
||||
async def _scheduled_task(self, item: Item, interaction: Interaction):
|
||||
try:
|
||||
@@ -377,13 +394,18 @@ class View:
|
||||
return
|
||||
|
||||
self.__stopped.set_result(True)
|
||||
asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}')
|
||||
asyncio.create_task(
|
||||
self.on_timeout(), name=f"discord-ui-view-timeout-{self.id}"
|
||||
)
|
||||
|
||||
def _dispatch_item(self, item: Item, interaction: Interaction):
|
||||
if self.__stopped.done():
|
||||
return
|
||||
|
||||
asyncio.create_task(self._scheduled_task(item, interaction), name=f'discord-ui-view-dispatch-{self.id}')
|
||||
asyncio.create_task(
|
||||
self._scheduled_task(item, interaction),
|
||||
name=f"discord-ui-view-dispatch-{self.id}",
|
||||
)
|
||||
|
||||
def refresh(self, components: List[Component]):
|
||||
# This is pretty hacky at the moment
|
||||
@@ -437,7 +459,9 @@ class View:
|
||||
A persistent view has all their components with a set ``custom_id`` and
|
||||
a :attr:`timeout` set to ``None``.
|
||||
"""
|
||||
return self.timeout is None and all(item.is_persistent() for item in self.children)
|
||||
return self.timeout is None and all(
|
||||
item.is_persistent() for item in self.children
|
||||
)
|
||||
|
||||
async def wait(self) -> bool:
|
||||
"""Waits until the view has finished interacting.
|
||||
@@ -509,7 +533,9 @@ class ViewStore:
|
||||
key = (component_type, message_id, custom_id)
|
||||
# Fallback to None message_id searches in case a persistent view
|
||||
# was added without an associated message_id
|
||||
value = self._views.get(key) or self._views.get((component_type, None, custom_id))
|
||||
value = self._views.get(key) or self._views.get(
|
||||
(component_type, None, custom_id)
|
||||
)
|
||||
if value is None:
|
||||
return
|
||||
|
||||
|
||||
Reference in New Issue
Block a user