diff --git a/disagreement/client.py b/disagreement/client.py index c8e37c1..03fb37b 100644 --- a/disagreement/client.py +++ b/disagreement/client.py @@ -76,7 +76,11 @@ class Client: intents (Optional[int]): The Gateway Intents to use. Defaults to `GatewayIntent.default()`. You might need to enable privileged intents in your bot's application page. loop (Optional[asyncio.AbstractEventLoop]): The event loop to use for asynchronous operations. - Defaults to `asyncio.get_event_loop()`. + Defaults to the running loop + via `asyncio.get_running_loop()`, + or a new loop from + `asyncio.new_event_loop()` if + none is running. command_prefix (Union[str, List[str], Callable[['Client', Message], Union[str, List[str]]]]): The prefix(es) for commands. Defaults to '!'. verbose (bool): If True, print raw HTTP and Gateway traffic for debugging. diff --git a/disagreement/error_handler.py b/disagreement/error_handler.py index 0240cca..e814518 100644 --- a/disagreement/error_handler.py +++ b/disagreement/error_handler.py @@ -14,7 +14,11 @@ def setup_global_error_handler( The handler logs unhandled exceptions so they don't crash the bot. """ if loop is None: - loop = asyncio.get_event_loop() + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) if not logging.getLogger().hasHandlers(): setup_logging(logging.ERROR) diff --git a/disagreement/gateway.py b/disagreement/gateway.py index b22459a..6499607 100644 --- a/disagreement/gateway.py +++ b/disagreement/gateway.py @@ -65,7 +65,11 @@ class GatewayClient: self._max_backoff: float = max_backoff self._ws: Optional[aiohttp.ClientWebSocketResponse] = None - self._loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() + try: + self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() + except RuntimeError: + self._loop = asyncio.new_event_loop() + asyncio.set_event_loop(self._loop) self._heartbeat_interval: Optional[float] = None self._last_sequence: Optional[int] = None self._session_id: Optional[str] = None diff --git a/tests/test_gateway_backoff.py b/tests/test_gateway_backoff.py index a4c3723..f64a62b 100644 --- a/tests/test_gateway_backoff.py +++ b/tests/test_gateway_backoff.py @@ -24,7 +24,7 @@ class DummyDispatcher: class DummyClient: def __init__(self): - self.loop = asyncio.get_event_loop() + self.loop = asyncio.get_running_loop() self.application_id = None # Mock application_id for Client.connect @@ -39,7 +39,7 @@ async def test_client_connect_backoff(monkeypatch): client = Client( token="test_token", intents=0, - loop=asyncio.get_event_loop(), + loop=asyncio.get_running_loop(), command_prefix="!", verbose=False, mention_replies=False,