diff --git a/disagreement/voice_client.py b/disagreement/voice_client.py index bd3cd62..41df380 100644 --- a/disagreement/voice_client.py +++ b/disagreement/voice_client.py @@ -259,5 +259,20 @@ class VoiceClient: self._udp.close() if self._udp_receive_thread: self._udp_receive_thread.join(timeout=1) - if self._sink: - self._sink.close() + if self._sink: + self._sink.close() + + async def __aenter__(self) -> "VoiceClient": + """Enter the context manager by connecting to the voice gateway.""" + await self.connect() + return self + + async def __aexit__( + self, + exc_type: Optional[type], + exc: Optional[BaseException], + tb: Optional[BaseException], + ) -> bool: + """Exit the context manager and close the connection.""" + await self.close() + return False diff --git a/docs/voice_client.md b/docs/voice_client.md index a328a1b..fca81ec 100644 --- a/docs/voice_client.md +++ b/docs/voice_client.md @@ -9,15 +9,17 @@ import asyncio import os import disagreement -vc = disagreement.VoiceClient( - os.environ["DISCORD_VOICE_ENDPOINT"], - os.environ["DISCORD_SESSION_ID"], - os.environ["DISCORD_VOICE_TOKEN"], - int(os.environ["DISCORD_GUILD_ID"]), - int(os.environ["DISCORD_USER_ID"]), -) +async def main(): + async with disagreement.VoiceClient( + os.environ["DISCORD_VOICE_ENDPOINT"], + os.environ["DISCORD_SESSION_ID"], + os.environ["DISCORD_VOICE_TOKEN"], + int(os.environ["DISCORD_GUILD_ID"]), + int(os.environ["DISCORD_USER_ID"]), + ) as vc: + await vc.send_audio_frame(b"...") -asyncio.run(vc.connect()) +asyncio.run(main()) ``` After connecting you can send raw Opus frames: @@ -41,7 +43,7 @@ You can switch sources while connected: await vc.play(FFmpegAudioSource("other.mp3")) ``` -Call `await vc.close()` when finished. +The connection will be closed automatically when leaving the `async with` block. ## Fetching Available Voice Regions