Skip to content

Commit bf66870

Browse files
committed
feat: allow bot http to be used as a context manager
example: ```python async with Client(token=os.environ["TOKEN"]) as bot: print("Logged in as", bot.user) data = await bot.http.get_gateway_bot() print(data) ```
1 parent cf272da commit bf66870

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

interactions/client/client.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,18 @@ def __init__(
416416
super().__init__()
417417
self._sanity_check()
418418

419+
async def __aenter__(self) -> "Client":
420+
if not self.token:
421+
raise ValueError(
422+
"Token not found - to use the bot in a context manager, you must pass the token in the Client constructor."
423+
)
424+
await self.login(self.token)
425+
return self
426+
427+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
428+
if not self.is_closed:
429+
await self.stop()
430+
419431
@property
420432
def is_closed(self) -> bool:
421433
"""Returns True if the bot has closed."""

0 commit comments

Comments
 (0)