Browse Source

Merge branch 'master' into feat/share-client-theme

pull/10428/head
Soheab_ 3 weeks ago
parent
commit
dc5ebd5379
  1. 2
      discord/components.py
  2. 3
      discord/ext/commands/converter.py
  3. 114
      discord/ext/commands/core.py
  4. 68
      discord/ext/commands/hybrid.py
  5. 9
      discord/gateway.py
  6. 2
      discord/http.py
  7. 2
      discord/reaction.py
  8. 6
      discord/ui/action_row.py
  9. 4
      discord/ui/checkbox.py
  10. 2
      discord/ui/container.py
  11. 4
      discord/ui/radio.py
  12. 14
      discord/ui/view.py
  13. 3
      discord/webhook/async_.py
  14. 88
      tests/test_ui_view.py

2
discord/components.py

@ -1379,7 +1379,7 @@ class Container(Component):
}
if self.id is not None:
payload['id'] = self.id
if self._colour:
if self._colour is not None:
payload['accent_color'] = self._colour.value
return payload

3
discord/ext/commands/converter.py

@ -1140,6 +1140,9 @@ class Greedy(List[T]):
converter = getattr(self.converter, '__name__', repr(self.converter))
return f'Greedy[{converter}]'
def __or__(self, value: Any) -> Any:
return Union[self, value]
def __class_getitem__(cls, params: Union[Tuple[T], T]) -> Greedy[T]:
if not isinstance(params, tuple):
params = (params,)

114
discord/ext/commands/core.py

@ -1504,15 +1504,7 @@ class GroupMixin(Generic[CogT]):
name: str = ...,
*args: Any,
**kwargs: Unpack[_CommandDecoratorKwargs],
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
],
Command[CogT, P, T],
]: ...
) -> _CogCommandDecorator[CogT]: ...
@overload
def command(
@ -1521,15 +1513,7 @@ class GroupMixin(Generic[CogT]):
cls: Type[CommandT] = ..., # type: ignore # previous overload handles case where cls is not set
*args: Any,
**kwargs: Unpack[_CommandDecoratorKwargs],
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
],
CommandT,
]: ...
) -> _CogCommandDecoratorWithCls[CogT, CommandT]: ...
def command(
self,
@ -1561,15 +1545,7 @@ class GroupMixin(Generic[CogT]):
name: str = ...,
*args: Any,
**kwargs: Unpack[_GroupDecoratorKwargs],
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
],
Group[CogT, P, T],
]: ...
) -> _CogGroupDecorator[CogT]: ...
@overload
def group(
@ -1578,15 +1554,7 @@ class GroupMixin(Generic[CogT]):
cls: Type[GroupT] = ..., # type: ignore # previous overload handles case where cls is not set
*args: Any,
**kwargs: Unpack[_GroupDecoratorKwargs],
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
],
GroupT,
]: ...
) -> _CogGroupDecoratorWithCls[CogT, GroupT]: ...
def group(
self,
@ -1748,6 +1716,60 @@ if TYPE_CHECKING:
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _CogCommandDecorator(Generic[CogT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Command[CogT, P, T]: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Command[CogT, P, T]: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _CogGroupDecorator(Generic[CogT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Group[CogT, P, T]: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Group[CogT, P, T]: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _CommandDecoratorWithCls(Generic[CommandT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> CommandT: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> CommandT: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _GroupDecoratorWithCls(Generic[GroupT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> GroupT: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> GroupT: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _CogCommandDecoratorWithCls(Generic[CogT, CommandT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> CommandT: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> CommandT: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _CogGroupDecoratorWithCls(Generic[CogT, GroupT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> GroupT: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> GroupT: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
@overload
def command(
@ -1761,15 +1783,7 @@ def command(
name: str = ...,
cls: Type[CommandT] = ..., # type: ignore # previous overload handles case where cls is not set
**attrs: Unpack[_CommandDecoratorKwargs],
) -> Callable[
[
Union[
Callable[Concatenate[ContextT, P], Coro[Any]],
Callable[Concatenate[CogT, ContextT, P], Coro[Any]], # type: ignore # CogT is used here to allow covariance
]
],
CommandT,
]: ...
) -> _CommandDecoratorWithCls[CommandT]: ...
def command(
@ -1829,15 +1843,7 @@ def group(
name: str = ...,
cls: Type[GroupT] = ..., # type: ignore # previous overload handles case where cls is not set
**attrs: Unpack[_GroupDecoratorKwargs],
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[Any]], # type: ignore # CogT is used here to allow covariance
Callable[Concatenate[ContextT, P], Coro[Any]],
]
],
GroupT,
]: ...
) -> _GroupDecoratorWithCls[GroupT]: ...
def group(

68
discord/ext/commands/hybrid.py

@ -24,7 +24,21 @@ DEALINGS IN THE SOFTWARE.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Tuple, Type, TypeVar, Union, Optional
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generic,
List,
Tuple,
Type,
TypeVar,
Union,
Optional,
overload,
)
import discord
import inspect
@ -98,6 +112,42 @@ if TYPE_CHECKING:
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
class _HybridCommandDecorator:
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> HybridCommand[CogT, P, T]: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> HybridCommand[None, P, T]: ... # type: ignore
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _HybridGroupDecorator:
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> HybridGroup[CogT, P, T]: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> HybridGroup[None, P, T]: ... # type: ignore
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _CogHybridCommandDecorator(Generic[CogT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> HybridCommand[CogT, P, T]: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> HybridCommand[CogT, P, T]: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
class _CogHybridGroupDecorator(Generic[CogT]):
@overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> HybridGroup[CogT, P, T]: ...
@overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> HybridGroup[CogT, P, T]: ...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
else:
P = TypeVar('P')
P2 = TypeVar('P2')
@ -847,7 +897,7 @@ class HybridGroup(Group[CogT, P, T]):
*args: Any,
with_app_command: bool = True,
**kwargs: Unpack[_HybridCommandDecoratorKwargs], # type: ignore # name, with_app_command
) -> Callable[[CommandCallback[CogT, ContextT, P2, U]], HybridCommand[CogT, P2, U]]:
) -> _CogHybridCommandDecorator[CogT]:
"""A shortcut decorator that invokes :func:`~discord.ext.commands.hybrid_command` and adds it to
the internal command list via :meth:`add_command`.
@ -863,7 +913,7 @@ class HybridGroup(Group[CogT, P, T]):
self.add_command(result)
return result
return decorator
return decorator # type: ignore # _CogHybridCommandDecorator only exists under TYPE_CHECKING
def group(
self,
@ -871,7 +921,7 @@ class HybridGroup(Group[CogT, P, T]):
*args: Any,
with_app_command: bool = True,
**kwargs: Unpack[_HybridGroupDecoratorKwargs], # type: ignore # name, with_app_command
) -> Callable[[CommandCallback[CogT, ContextT, P2, U]], HybridGroup[CogT, P2, U]]:
) -> _CogHybridGroupDecorator[CogT]:
"""A shortcut decorator that invokes :func:`~discord.ext.commands.hybrid_group` and adds it to
the internal command list via :meth:`~.GroupMixin.add_command`.
@ -887,7 +937,7 @@ class HybridGroup(Group[CogT, P, T]):
self.add_command(result)
return result
return decorator
return decorator # type: ignore # _CogHybridGroupDecorator only exists under TYPE_CHECKING
def hybrid_command(
@ -895,7 +945,7 @@ def hybrid_command(
*,
with_app_command: bool = True,
**attrs: Unpack[_HybridCommandDecoratorKwargs], # type: ignore # name, with_app_command
) -> Callable[[CommandCallback[CogT, ContextT, P, T]], HybridCommand[CogT, P, T]]:
) -> _HybridCommandDecorator:
r"""A decorator that transforms a function into a :class:`.HybridCommand`.
A hybrid command is one that functions both as a regular :class:`.Command`
@ -939,7 +989,7 @@ def hybrid_command(
# Pyright does not allow Command[Any] to be assigned to Command[CogT] despite it being okay here
return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs) # type: ignore # name, with_app_command
return decorator
return decorator # type: ignore # _HybridCommandDecorator only exists under TYPE_CHECKING
def hybrid_group(
@ -947,7 +997,7 @@ def hybrid_group(
*,
with_app_command: bool = True,
**attrs: Unpack[_HybridGroupDecoratorKwargs], # type: ignore # name, with_app_command
) -> Callable[[CommandCallback[CogT, ContextT, P, T]], HybridGroup[CogT, P, T]]:
) -> _HybridGroupDecorator:
"""A decorator that transforms a function into a :class:`.HybridGroup`.
This is similar to the :func:`~discord.ext.commands.group` decorator except it creates
@ -972,4 +1022,4 @@ def hybrid_group(
raise TypeError('Callback is already a command.')
return HybridGroup(func, name=name, with_app_command=with_app_command, **attrs) # type: ignore # name, with_app_command
return decorator
return decorator # type: ignore # _HybridGroupDecorator only exists under TYPE_CHECKING

9
discord/gateway.py

@ -173,8 +173,7 @@ class KeepAliveHandler(threading.Thread):
data = self.get_payload()
_log.debug(self.msg, self.shard_id, data['d'])
coro = self.ws.send_heartbeat(data)
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
f = asyncio.run_coroutine_threadsafe(self._send_heartbeat(data), loop=self.ws.loop)
try:
# block until sending is complete
total = 0
@ -195,8 +194,6 @@ class KeepAliveHandler(threading.Thread):
except Exception:
self.stop()
else:
self._last_send = time.perf_counter()
def get_payload(self) -> Dict[str, Any]:
return {
@ -214,6 +211,10 @@ class KeepAliveHandler(threading.Thread):
self._last_send = time.perf_counter()
return self.get_payload()
async def _send_heartbeat(self, data: Any) -> None:
self._last_send = time.perf_counter()
await self.ws.send_heartbeat(data)
def ack(self) -> None:
ack_time = time.perf_counter()
self._last_ack = ack_time

2
discord/http.py

@ -572,7 +572,7 @@ class HTTPClient:
'compress': compress,
}
return await self.__session.ws_connect(url, **kwargs)
return await self.__session.ws_connect(url, **kwargs) # pyright: ignore[reportReturnType]
def _try_clear_expired_ratelimits(self) -> None:
if len(self._buckets) < 256:

2
discord/reaction.py

@ -169,7 +169,7 @@ class Reaction:
.. versionadded:: 1.3
.. versionchanged:: 2.0
This function will now raise :exc:`ValueError` instead of
This function will now raise :exc:`TypeError` instead of
``InvalidArgument``.
Raises

6
discord/ui/action_row.py

@ -260,15 +260,15 @@ class ActionRow(Item[V]):
or (40) for the entire view.
"""
if not isinstance(item, Item):
raise TypeError(f'expected Item not {item.__class__.__name__}')
if (self._weight + item.width) > 5:
raise ValueError('maximum number of children exceeded')
if len(self._children) >= 5:
raise ValueError('maximum number of children exceeded')
if not isinstance(item, Item):
raise TypeError(f'expected Item not {item.__class__.__name__}')
if self._view:
self._view._add_count(1)

4
discord/ui/checkbox.py

@ -59,7 +59,7 @@ V = TypeVar('V', bound='BaseView', covariant=True)
class CheckboxGroup(Item[V]):
"""Represents a checkbox group component within a modal.
"""Represents a checkbox group component within a modal that can only be used in :class:`Label`.
.. versionadded:: 2.7
@ -281,7 +281,7 @@ class CheckboxGroup(Item[V]):
class Checkbox(Item[V]):
"""Represents a checkbox component within a modal.
"""Represents a checkbox component within a modal that can only be used in :class:`Label`.
.. versionadded:: 2.7

2
discord/ui/container.py

@ -243,7 +243,7 @@ class Container(Item[V]):
components = self.to_components()
colour = None
if self._colour:
if self._colour is not None:
colour = self._colour if isinstance(self._colour, int) else self._colour.value
base = {

4
discord/ui/radio.py

@ -54,7 +54,7 @@ V = TypeVar('V', bound='BaseView', covariant=True)
class RadioGroup(Item[V]):
"""Represents a radio group component within a modal.
"""Represents a radio group component within a modal that can only be used in :class:`Label`.
.. versionadded:: 2.7
@ -113,7 +113,7 @@ class RadioGroup(Item[V]):
@property
def value(self) -> Optional[str]:
"""Optional[:class:`str`]: The value have been selected by the user, if any."""
"""Optional[:class:`str`]: The value that has been selected by the user, if any."""
return self._value
@property

14
discord/ui/view.py

@ -468,8 +468,8 @@ class BaseView:
if not isinstance(item, Item):
raise TypeError(f'expected Item not {item.__class__.__name__}')
item._update_view(self)
self._add_count(item._total_count)
item._update_view(self)
self._children.append(item)
return self
@ -783,20 +783,17 @@ class View(BaseView):
return components
def add_item(self, item: Item[Any]) -> Self:
if not isinstance(item, Item):
raise TypeError(f'expected Item not {item.__class__.__name__}')
if len(self._children) >= 25:
raise ValueError('maximum number of children exceeded')
if item._is_v2():
raise ValueError('v2 items cannot be added to this view')
self.__weights.add_item(item)
super().add_item(item)
try:
self.__weights.add_item(item)
except ValueError as e:
# if the item has no space left then remove it from _children
self._children.remove(item)
raise e
return self
def remove_item(self, item: Item[Any]) -> Self:
@ -806,6 +803,7 @@ class View(BaseView):
pass
else:
self.__weights.remove_item(item)
self._add_count(-item._total_count)
item._update_view(None)
return self

3
discord/webhook/async_.py

@ -1322,6 +1322,9 @@ class Webhook(BaseWebhook):
state = None
if client is not MISSING:
if client._ready is MISSING:
raise ValueError('Client must be logged in to use from_url with a client.')
state = client._connection
if session is MISSING:
session = client.http._HTTPClient__session # type: ignore

88
tests/test_ui_view.py

@ -0,0 +1,88 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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.
"""
from __future__ import annotations
import discord
import pytest
def test_add_item_with_full_row():
view = discord.ui.View()
for i in range(5):
view.add_item(discord.ui.Button(label=str(i), row=0))
with pytest.raises(ValueError):
view.add_item(discord.ui.Button(label="6", row=0))
assert len(view.children) == 5
assert view.total_children_count == 5
def test_add_item_invalid():
view = discord.ui.View()
with pytest.raises(TypeError):
view.add_item(object()) # type: ignore
def test_remove_item():
view = discord.ui.View()
item = discord.ui.Button(label="Test")
view.add_item(item)
view.remove_item(item)
assert view.children == []
assert view.total_children_count == 0
assert item.view is None
def test_action_row_add_item_invalid():
row = discord.ui.ActionRow()
with pytest.raises(TypeError):
row.add_item(object()) # type: ignore
def test_layout_view_add_item_with_too_many_children():
view = discord.ui.LayoutView()
max_item_limit = 40
for i in range(max_item_limit - 1):
view.add_item(discord.ui.TextDisplay(str(i)))
row = discord.ui.ActionRow(
discord.ui.Button(label="A"),
discord.ui.Button(label="B"),
)
with pytest.raises(ValueError):
view.add_item(row)
assert len(view.children) == max_item_limit - 1
assert view.total_children_count == max_item_limit - 1
assert row.view is None
assert all(item.view is None for item in row.children)
Loading…
Cancel
Save