Use asyncio.get_running_loop fallback (#50)

This commit is contained in:
Slipstream 2025-06-11 14:27:11 -06:00 committed by GitHub
parent 3158d76e90
commit 15d95bc786
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 17 additions and 5 deletions

View File

@ -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.

View File

@ -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)

View File

@ -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

View File

@ -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,