Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Update Client.run to have a better async I/O usage #2645

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
Prev Previous commit
Next Next commit
chore: Update Client.__aenter__ and Client.run
DA-344 committed Dec 11, 2024

Verified

This commit was signed with the committer’s verified signature.
JLLeitschuh Jonathan Leitschuh
commit 88484e221c486a01d6f0eabdbd3034e03d9c757c
30 changes: 16 additions & 14 deletions discord/client.py
Original file line number Diff line number Diff line change
@@ -267,10 +267,20 @@ def __init__(
self._tasks = set()

async def __aenter__(self) -> Client:
loop = asyncio.get_running_loop()
self.loop = loop
self.http.loop = loop
self._connection.loop = loop
if self.loop is MISSING:
try:
self.loop = asyncio.get_running_loop()
except RuntimeError:
# No event loop was found, this should not happen
# because entering on this context manager means a
# loop is already active, but we need to handle it
# anyways just to prevent future errors.

# Maybe handle different system event loop policies?
self.loop = asyncio.new_event_loop()

self.http.loop = self.loop
self._connection.loop = self.loop

self._ready = asyncio.Event()

@@ -749,11 +759,6 @@ async def start(self, token: str, *, reconnect: bool = True) -> None:
An unexpected keyword argument was received.
"""
# Update the loop to get the running one in case the one set is MISSING
if self.loop is MISSING:
self.loop = asyncio.get_event_loop()
self.http.loop = self.loop
self._connection.loop = self.loop

await self.login(token)
await self.connect(reconnect=reconnect)

@@ -791,11 +796,8 @@ def run(self, token: str, *, reconnect: bool = True) -> None:
"""

async def runner():
try:
await self.start(token, reconnect=reconnect)
finally:
if not self.is_closed():
await self.close()
async with self:
await self.start(token=token, reconnect=reconnect)

run = asyncio.run