Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 0 additions & 32 deletions interactions/api/cache.pyi

This file was deleted.

20 changes: 10 additions & 10 deletions interactions/api/dispatch.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from asyncio import get_event_loop
from asyncio import AbstractEventLoop, get_event_loop
from logging import Logger
from typing import Coroutine, Optional
from typing import Callable, Coroutine, Dict, List, Optional

from interactions.base import get_logger

Expand All @@ -20,26 +20,26 @@ class Listener:
__slots__ = ("loop", "events")

def __init__(self) -> None:
self.loop = get_event_loop()
self.events = {}
self.loop: AbstractEventLoop = get_event_loop()
self.events: Dict[str, List[Callable[..., Coroutine]]] = {}

def dispatch(self, __name: str, *args, **kwargs) -> None:
r"""
Dispatches an event given out by the gateway.

:param __name: The name of the event to dispatch.
:type __name: str
:param \*args: Multiple arguments of the coroutine.
:type \*args: list[Any]
:param \**kwargs: Keyword-only arguments of the coroutine.
:type \**kwargs: dict
:param *args: Multiple arguments of the coroutine.
:type *args: list[Any]
:param **kwargs: Keyword-only arguments of the coroutine.
:type **kwargs: dict
"""
for event in self.events.get(__name, []):

self.loop.create_task(event(*args, **kwargs))
log.debug(f"DISPATCH: {event}")

def register(self, coro: Coroutine, name: Optional[str] = None) -> None:
def register(self, coro: Callable[..., Coroutine], name: Optional[str] = None) -> None:
"""
Registers a given coroutine as an event to be listened to.
If the name of the event is not given, it will then be
Expand All @@ -48,7 +48,7 @@ def register(self, coro: Coroutine, name: Optional[str] = None) -> None:
i.e. : async def on_guild_create -> "ON_GUILD_CREATE" dispatch.

:param coro: The coroutine to register as an event.
:type coro: Coroutine
:type coro: Callable[..., Coroutine]
:param name?: The name to associate the coroutine with. Defaults to None.
:type name: Optional[str]
"""
Expand Down
9 changes: 0 additions & 9 deletions interactions/api/dispatch.pyi

This file was deleted.

14 changes: 0 additions & 14 deletions interactions/api/error.pyi

This file was deleted.

58 changes: 30 additions & 28 deletions interactions/api/gateway/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
)
from sys import platform, version_info
from time import perf_counter
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union

from aiohttp import WSMessage, WSMsgType
from aiohttp import ClientWebSocketResponse, WSMessage, WSMsgType
from aiohttp.http import WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE

from ...base import get_logger
Expand All @@ -31,6 +31,9 @@
from ..models.presence import ClientPresence
from .heartbeat import _Heartbeat

if TYPE_CHECKING:
from ...client.context import _Context

log = get_logger("gateway")

__all__ = ("WebSocketClient",)
Expand Down Expand Up @@ -102,30 +105,30 @@ def __init__(
self._loop = get_event_loop() if version_info < (3, 10) else get_running_loop()
except RuntimeError:
self._loop = new_event_loop()
self._dispatch = Listener()
self._http = HTTPClient(token)
self._client = None
self._closed = False
self._options = {
self._dispatch: Listener = Listener()
self._http: HTTPClient = HTTPClient(token)
self._client: Optional["ClientWebSocketResponse"] = None
self._closed: bool = False
self._options: dict = {
"max_msg_size": 1024**2,
"timeout": 60,
"autoclose": False,
"compress": 0,
}
self._intents = intents
self._intents: Intents = intents
self.__heartbeater: _Heartbeat = _Heartbeat(
loop=self._loop if version_info < (3, 10) else None
)
self.__shard = None
self.__presence = None
self.__task = None
self.session_id = None if session_id is MISSING else session_id
self.sequence = None if sequence is MISSING else sequence
self.ready = Event(loop=self._loop) if version_info < (3, 10) else Event()

self._last_send = perf_counter()
self._last_ack = perf_counter()
self.latency: float("nan") # noqa: F821
self.__shard: Optional[List[Tuple[int]]] = None
self.__presence: Optional[ClientPresence] = None
self.__task: Optional[Task] = None
self.session_id: Optional[str] = None if session_id is MISSING else session_id
self.sequence: Optional[str] = None if sequence is MISSING else sequence
self.ready: Event = Event(loop=self._loop) if version_info < (3, 10) else Event()

self._last_send: float = perf_counter()
self._last_ack: float = perf_counter()
self.latency: float = float("nan") # noqa: F821
# self.latency has to be noqa, this is valid in python but not in Flake8.

async def _manage_heartbeat(self) -> None:
Expand All @@ -142,10 +145,9 @@ async def _manage_heartbeat(self) -> None:
await self.__restart()
break

async def __restart(self):
async def __restart(self) -> None:
"""Restart the client's connection and heartbeat with the Gateway."""
if self.__task:
self.__task: Task
self.__task.cancel()
self._client = None # clear pending waits
self.__heartbeater.event.clear()
Expand Down Expand Up @@ -258,7 +260,7 @@ async def _handle_connection(
log.debug(f"{event}: {data}")
self._dispatch_event(event, data)

async def wait_until_ready(self):
async def wait_until_ready(self) -> None:
"""Waits for the client to become ready according to the Gateway."""
await self.ready.wait()

Expand Down Expand Up @@ -395,15 +397,15 @@ def _dispatch_event(self, event: str, data: dict) -> None: # sourcery no-metric
log.fatal(f"An error occured dispatching {name}: {error}")
self._dispatch.dispatch("raw_socket_create", data)

def __contextualize(self, data: dict) -> object:
def __contextualize(self, data: dict) -> "_Context":
"""
Takes raw data given back from the Gateway
and gives "context" based off of what it is.

:param data: The data from the Gateway.
:type data: dict
:return: The context object.
:rtype: object
:rtype: Any
"""
if data["type"] != InteractionType.PING:
_context: str = ""
Expand All @@ -418,12 +420,12 @@ def __contextualize(self, data: dict) -> object:
_context = "ComponentContext"

data["_client"] = self._http
context: object = getattr(__import__("interactions.client.context"), _context)
context: Type["_Context"] = getattr(__import__("interactions.client.context"), _context)

return context(**data)

def __sub_command_context(
self, data: Union[dict, Option], context: object
self, data: Union[dict, Option], context: "_Context"
) -> Union[Tuple[str], dict]:
"""
Checks if an application command schema has sub commands
Expand Down Expand Up @@ -510,7 +512,7 @@ def _check_auto(option: dict) -> Optional[Tuple[str]]:

return __kwargs

def __option_type_context(self, context: object, type: int) -> dict:
def __option_type_context(self, context: "_Context", type: int) -> dict:
"""
Looks up the type of option respective to the existing
option types.
Expand Down Expand Up @@ -544,11 +546,11 @@ def __option_type_context(self, context: object, type: int) -> dict:
}
return _resolved

async def restart(self):
async def restart(self) -> None:
await self.__restart()

@property
async def __receive_packet_stream(self) -> Optional[Dict[str, Any]]:
async def __receive_packet_stream(self) -> Optional[Union[Dict[str, Any], WSMessage]]:
"""
Receives a stream of packets sent from the Gateway.

Expand Down
77 changes: 0 additions & 77 deletions interactions/api/gateway/client.pyi

This file was deleted.

6 changes: 0 additions & 6 deletions interactions/api/gateway/heartbeat.pyi

This file was deleted.

Loading