Skip to content

Commit

Permalink
🐛 [Bugfix] Stop using nesting asyncio
Browse files Browse the repository at this point in the history
  • Loading branch information
foxwhite25 committed Apr 7, 2022
1 parent d101c81 commit 0555902
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 299 deletions.
2 changes: 0 additions & 2 deletions qq/client.py
Expand Up @@ -41,7 +41,6 @@
from .guild import Guild
from .http import HTTPClient
from .iterators import GuildIterator
from .nest_asyncio import apply
from .state import ConnectionState
from .user import ClientUser, User

Expand Down Expand Up @@ -137,7 +136,6 @@ def __init__(
):
self.ws: QQWebSocket = None # type: ignore
self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() if loop is None else loop
apply(self.loop)
self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {}
self.token = ""
self.shard_id: Optional[int] = options.get('shard_id')
Expand Down
3 changes: 0 additions & 3 deletions qq/ext/commands/bot.py
Expand Up @@ -140,9 +140,6 @@ def __init__(self, command_prefix, help_command=_default, description=None, **op
if self.owner_id and self.owner_ids:
raise TypeError('owner_id 和 owner_ids 都被设置。')

if not self.owner_id and not self.owner_ids:
raise TypeError('owner_id 和 owner_ids 必须设置其中一个。')

if self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection):
raise TypeError(f'owner_ids 必须是一个集合,而不是 {self.owner_ids.__class__!r}')

Expand Down
79 changes: 41 additions & 38 deletions qq/ext/commands/core.py
Expand Up @@ -259,8 +259,6 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
在此定义的任何 ``pre_invoke`` 或 ``after_invoke`` 都将覆盖父项。
.. versionadded:: 1.1.0
"""
__original_kwargs__: Dict[str, Any]

Expand All @@ -281,8 +279,8 @@ def __new__(cls: Type[CommandT], *args: Any, **kwargs: Any) -> CommandT:
return self

def __init__(self, func: Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[T]],
Callable[[Concatenate[ContextT, P]], Coro[T]],
], **kwargs: Any):
if not asyncio.iscoroutinefunction(func):
raise TypeError('回调必须是协程。')
Expand Down Expand Up @@ -400,15 +398,15 @@ def __init__(self, func: Union[

@property
def callback(self) -> Union[
Callable[Concatenate[CogT, Context, P], Coro[T]],
Callable[Concatenate[Context, P], Coro[T]],
Callable[[Concatenate[CogT, Context, P]], Coro[T]],
Callable[[Concatenate[Context, P]], Coro[T]],
]:
return self._callback

@callback.setter
def callback(self, function: Union[
Callable[Concatenate[CogT, Context, P], Coro[T]],
Callable[Concatenate[Context, P], Coro[T]],
Callable[[Concatenate[CogT, Context, P]], Coro[T]],
Callable[[Concatenate[Context, P]], Coro[T]],
]) -> None:
self._callback = function
unwrap = unwrap_function(function)
Expand Down Expand Up @@ -1267,8 +1265,8 @@ def command(
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[T]],
Callable[[Concatenate[ContextT, P]], Coro[T]],
]
], Command[CogT, P, T]]:
...
Expand All @@ -1280,7 +1278,7 @@ def command(
cls: Type[CommandT] = ...,
*args: Any,
**kwargs: Any,
) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]:
) -> Callable[[Callable[[Concatenate[ContextT, P]], Coro[Any]]], CommandT]:
...

def command(
Expand All @@ -1289,7 +1287,7 @@ def command(
cls: Type[CommandT] = MISSING,
*args: Any,
**kwargs: Any,
) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]:
) -> Callable[[Callable[[Concatenate[ContextT, P]], Coro[Any]]], CommandT]:
"""调用 :func:`.command` 并通过 :meth:`~.GroupMixin.add_command` 将其添加到内部命令列表的快捷方式装饰器。
Returns
Expand All @@ -1298,7 +1296,7 @@ def command(
将提供的方法转换为命令的装饰器,将其添加到机器人,然后返回它。
"""

def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> CommandT:
def decorator(func: Callable[[Concatenate[ContextT, P]], Coro[Any]]) -> CommandT:
kwargs.setdefault('parent', self)
result = command(name=name, cls=cls, *args, **kwargs)(func)
self.add_command(result)
Expand All @@ -1315,8 +1313,8 @@ def group(
**kwargs: Any,
) -> Callable[[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]]
Callable[[Concatenate[CogT, ContextT, P]], Coro[T]],
Callable[[Concatenate[ContextT, P]], Coro[T]]
]
], Group[CogT, P, T]]:
...
Expand All @@ -1328,7 +1326,7 @@ def group(
cls: Type[GroupT] = ...,
*args: Any,
**kwargs: Any,
) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]:
) -> Callable[[Callable[[Concatenate[ContextT, P]], Coro[Any]]], GroupT]:
...

def group(
Expand All @@ -1337,7 +1335,7 @@ def group(
cls: Type[GroupT] = MISSING,
*args: Any,
**kwargs: Any,
) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]:
) -> Callable[[Callable[[Concatenate[ContextT, P]], Coro[Any]]], GroupT]:
"""调用 :func:`.group` 并通过 :meth:`~.GroupMixin.add_command` 将其添加到内部命令列表的快捷方式装饰器。
Returns
Expand All @@ -1346,7 +1344,7 @@ def group(
将提供的方法转换为 Group 的装饰器,将其添加到机器人,然后返回它。
"""

def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> GroupT:
def decorator(func: Callable[[Concatenate[ContextT, P]], Coro[Any]]) -> GroupT:
kwargs.setdefault('parent', self)
result = group(name=name, cls=cls, *args, **kwargs)(func)
self.add_command(result)
Expand Down Expand Up @@ -1470,8 +1468,8 @@ def command(
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[T]],
Callable[[Concatenate[ContextT, P]], Coro[T]],
]
]
, Command[CogT, P, T]]:
Expand All @@ -1486,8 +1484,8 @@ def command(
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[Any]],
Callable[Concatenate[ContextT, P], Coro[Any]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[Any]],
Callable[[Concatenate[ContextT, P]], Coro[Any]],
]
]
, CommandT]:
Expand All @@ -1501,8 +1499,8 @@ def command(
) -> Callable[
[
Union[
Callable[Concatenate[ContextT, P], Coro[Any]],
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[[Concatenate[ContextT, P]], Coro[Any]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[T]],
]
]
, Union[Command[CogT, P, T], CommandT]]:
Expand Down Expand Up @@ -1531,8 +1529,8 @@ def command(
cls = Command # type: ignore

def decorator(func: Union[
Callable[Concatenate[ContextT, P], Coro[Any]],
Callable[Concatenate[CogT, ContextT, P], Coro[Any]],
Callable[[Concatenate[ContextT, P]], Coro[Any]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[Any]],
]) -> CommandT:
if isinstance(func, Command):
raise TypeError('Callback is already a command.')
Expand All @@ -1549,8 +1547,8 @@ def group(
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[T]],
Callable[[Concatenate[ContextT, P]], Coro[T]],
]
]
, Group[CogT, P, T]]:
Expand All @@ -1565,8 +1563,8 @@ def group(
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[Any]],
Callable[Concatenate[ContextT, P], Coro[Any]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[Any]],
Callable[[Concatenate[ContextT, P]], Coro[Any]],
]
]
, GroupT]:
Expand All @@ -1580,8 +1578,8 @@ def group(
) -> Callable[
[
Union[
Callable[Concatenate[ContextT, P], Coro[Any]],
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[[Concatenate[ContextT, P]], Coro[Any]],
Callable[[Concatenate[CogT, ContextT, P]], Coro[T]],
]
]
, Union[Group[CogT, P, T], GroupT]]:
Expand Down Expand Up @@ -1905,8 +1903,11 @@ async def predicate(ctx: Context) -> bool:
return check(predicate)


def cooldown(rate: int, per: float, type: Union[BucketType, Callable[[Message], Any]] = BucketType.default) -> Callable[
[T], T]:
def cooldown(
rate: int,
per: float,
type: Union[BucketType, Callable[[Message], Any]] = BucketType.default
) -> Callable[[T], T]:
"""为 :class:`.Command` 添加冷却时间的装饰器
冷却时间允许命令在特定时间范围内仅使用特定次数。
Expand All @@ -1924,7 +1925,7 @@ def cooldown(rate: int, per: float, type: Union[BucketType, Callable[[Message],
per: :class:`float`
触发时等待冷却的秒数。
type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]]
冷却时间的类型。如果可调用,则应返回映射的键。
冷却时间的类型。
"""

def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
Expand All @@ -1937,8 +1938,10 @@ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
return decorator # type: ignore


def dynamic_cooldown(cooldown: Union[BucketType, Callable[[Message], Any]], type: BucketType = BucketType.default) -> \
Callable[[T], T]:
def dynamic_cooldown(
cooldown: Union[BucketType, Callable[[Message], Any]],
type: BucketType = BucketType.default
) -> Callable[[T], T]:
"""为 :class:`.Command` 添加动态冷却时间的装饰器
这与 :func:`.cooldown` 的不同之处在于
Expand All @@ -1961,7 +1964,7 @@ def dynamic_cooldown(cooldown: Union[BucketType, Callable[[Message], Any]], type
冷却时间的类型。
"""
if not callable(cooldown):
raise TypeError("必须提供可调用")
raise TypeError("必须提供 Callable")

def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
Expand Down
5 changes: 4 additions & 1 deletion qq/gateway.py
Expand Up @@ -432,7 +432,10 @@ async def received_message(self, msg, /):
except KeyError:
_log.debug('未知事件 %s.', event)
else:
func(data)
if event == 'READY':
await func(data)
else:
func(data)

# remove the dispatched listeners
removed = []
Expand Down
14 changes: 5 additions & 9 deletions qq/guild.py
Expand Up @@ -21,7 +21,6 @@

from __future__ import annotations

import asyncio
import datetime
from typing import (
Dict,
Expand Down Expand Up @@ -152,7 +151,6 @@ def _from_data(self, guild: GuildPayload) -> None:
for r in guild.get('roles', []):
role = Role(guild=self, data=r, state=state)
self._roles[role.id] = role
self._sync()

def _add_channel(self, channel: GuildChannel, /) -> None:
self._channels[channel.id] = channel
Expand All @@ -172,19 +170,17 @@ def __repr__(self) -> str:
inner = ' '.join('%s=%r' % t for t in attrs)
return f'<Guild {inner}>'

def _sync(self) -> None:
# I know it's jank to put a sync requests here,
# but QQ just does not give all the info about guilds unless you requests it
channels = asyncio.run(self._state.http.get_guild_channels(self.id))
result = asyncio.run(self._state.http.get_member(self.id, self._state.user.id))
async def fill_in(self):
channels = await self._state.http.get_guild_channels(self.id)
result = await self._state.http.get_member(self.id, self._state.user.id)

member = Member(data=result,
guild=self, state=self._state)
self._add_member(member)

try:

permissions = asyncio.run(self._state.http.get_permission(self.id))
permissions = await self._state.http.get_permission(self.id)
for permission in permissions['apis']:
permission = Permission(data=permission, state=self._state, guild=self)
self._permission.append(permission)
Expand All @@ -193,7 +189,7 @@ def _sync(self) -> None:
print(e)

try:
roles = asyncio.run(self._state.http.get_roles(self.id))
roles = await self._state.http.get_roles(self.id)
if 'roles' in roles:
for r in roles['roles']:
role = Role(guild=self, data=r, state=self._state)
Expand Down

0 comments on commit 0555902

Please sign in to comment.