Voice¶
discord_http.voice.client module¶
- class discord_http.voice.client.VoiceClient(client, channel)¶
Bases:
objectThe public handle for an active voice connection in a guild.
- Parameters:
client (Client)
channel (PartialChannel)
- channel: PartialChannel¶
The voice channel this client is connected to.
- connection: VoiceConnection¶
The underlying voice connection state machine.
- property loop: AbstractEventLoop¶
The event loop the client runs on.
- async connect(*, timeout=30.0, reconnect=True, reconnect_on_session_invalid=False, self_deaf=False, self_mute=False) None¶
Connect to the voice channel.
- Parameters:
timeout (
float) – The maximum time to wait for the handshake, in seconds.reconnect (
bool) – Whether to attempt reconnection on failure.reconnect_on_session_invalid (
bool) – Whether to reconnect when Discord invalidates the session (close code 4006), e.g. after the channel empties and the DAVE session is torn down. Defaults toFalse(disconnect instead of reconnecting).self_deaf (
bool) – Whether to join self-deafened.self_mute (
bool) – Whether to join self-muted.
- Return type:
- async move_to(channel, *, timeout=10.0) None¶
Move to a different voice channel.
Returns once Discord confirms the move, the voice connection then follows on its own.
- Parameters:
channel (
PartialChannel|int) – The channel to move to, either a channel object or its ID.timeout (
float) – How long to wait for Discord to confirm the move, in seconds.
- Raises:
RuntimeError – If the voice client is not connected.
TimeoutError – If Discord didn’t move the bot, for example without permission to join the channel.
- Return type:
- send_audio_packet(data, *, encode=True) None¶
Frame, encrypt, and transmit a single audio packet over UDP.
- play(audio, *, after=None) None¶
Play an audio source over the connection.
A string is handed to ffmpeg as its input, and ffmpeg opens whatever it names: local files, HTTP(S) and every other protocol it was built with. Do not pass text a user typed without checking it first, otherwise they can make the machine the bot runs on read its own files or reach hosts only it can see. ffmpeg can be limited to a set of protocols with
before_options="-protocol_whitelist http,https,tcp,tls,crypto"onFFmpegOpusAudioorFFmpegPCMAudio.- Parameters:
audio (
AudioSource|str|PathLike|bytes|bytearray|memoryview|IOBase|AsyncIterable[bytes]) – The audio source, path, bytes, or stream to play.after (
Callable[[Exception|None],object] |None) – A callback invoked with any error once playback finishes, it can also beasync def.
- Raises:
RuntimeError – If the voice client is not connected.
- Return type:
discord_http.voice.connection module¶
- class discord_http.voice.connection.VoiceConnection(voice_client)¶
Bases:
objectThe transport and control-plane state machine for a voice connection.
- Parameters:
voice_client (VoiceClient)
- voice_client: VoiceClient¶
The voice client that owns this connection.
- dave_session: DaveManager | None¶
The DAVE/MLS session manager, if a protocol version was negotiated.
- connected_user_ids: set[int]¶
The users Discord reported in the call (ops 11 and 13), used to validate DAVE proposals.
- property backoff: ExponentialBackoff¶
The exponential backoff for reconnects, built lazily from client settings.
- async connect(*, timeout=30.0, reconnect=True, reconnect_on_session_invalid=False, self_deaf=False, self_mute=False) None¶
Establish the full voice connection.
- Parameters:
timeout (
float) – The maximum time to wait for the handshake, in seconds.reconnect (
bool) – Whether to attempt reconnection on failure.reconnect_on_session_invalid (
bool) – Whether to reconnect when Discord invalidates the session (close code 4006), e.g. after the channel empties and the DAVE session is torn down. Defaults toFalse(disconnect instead of reconnecting).self_deaf (
bool) – Whether to join self-deafened.self_mute (
bool) – Whether to join self-muted.
- Raises:
If no shard can be resolved for the guild - If DAVE is required but
daveyis not installed
TimeoutError – If the handshake does not complete within
timeout.VoiceConnectionClosed – If Discord closes the voice connection before it is established.
- Return type:
- async on_session_description(data) None¶
Handle the SESSION_DESCRIPTION (op 4): build the encryptor.
- async on_clients_connect(data) None¶
Handle a CLIENTS_CONNECT (op 11) frame: remember who is in the call.
- async on_client_disconnect(data) None¶
Handle a CLIENT_DISCONNECT (op 13) frame: forget the user’s receive state.
Frees the SSRC mappings and per-SSRC Opus decoder held for the user, so a long-lived connection in a busy channel does not accumulate state for users who have left.
- async on_dave_json(opcode, data) None¶
Handle an inbound JSON DAVE control op (transition/epoch, ops 21/22/24).
These ops arrive as JSON text frames rather than binary DAVE frames, so they carry the decoded
dpayload instead of raw bytes.
- async reinit_dave_session() None¶
Create or reset the DAVE session for the negotiated protocol version.
- Return type:
- can_decrypt() bool¶
Whether incoming Opus payloads are end-to-end encrypted and can be decrypted.
- Return type:
- dave_decrypt_opus(user_id, opus) bytes¶
Decrypt an Opus payload through the DAVE session, if active.
- async close_transport() None¶
Close the websocket and UDP transport without notifying the gateway.
- Return type:
- async move_to(channel, *, timeout=10.0) None¶
Move the connection to a different voice channel.
Returns once Discord confirms the move, the voice connection then follows on its own.
- Parameters:
channel (
PartialChannel) – The channel to move to.timeout (
float) – How long to wait for Discord to confirm the move, in seconds.
- Raises:
RuntimeError – If no shard can be resolved for the guild.
TimeoutError – If Discord didn’t move the bot, for example without permission to join.
- Return type:
discord_http.voice.player module¶
- class discord_http.voice.player.AudioPlayer(source, voice_client, *, after=None)¶
Bases:
objectA drift-corrected
asyncio.Taskplayer that streams anAudioSourceto a voice client.- Parameters:
source (AudioSource)
voice_client (VoiceClient)
- set_source(source) None¶
Hot-swap the audio source without interrupting the player task.
- Parameters:
source (
AudioSource) – The new audio source to read from.- Return type:
- class discord_http.voice.player.AudioSource¶
Bases:
ABCAn abstract audio source yielding one 20ms frame per
read()(Opus packet or 3840-byte s16le PCM).
- discord_http.voice.player.AudioSourceInput = discord_http.voice.player.AudioSource | str | os.PathLike | bytes | bytearray | memoryview | io.IOBase | collections.abc.AsyncIterable[bytes]¶
The set of inputs accepted as audio sources by
VoiceClient.play().
- class discord_http.voice.player.FFmpegOpusAudio(source, *, bitrate=128, before_options=None, options=None, pipe=False, executable='ffmpeg')¶
Bases:
_FFmpegAudioAn audio source that encodes input to Opus with
ffmpeg, extracting raw packets from its Ogg/Opus stream.- Parameters:
- class discord_http.voice.player.FFmpegPCMAudio(source, *, before_options=None, options=None, pipe=False, executable='ffmpeg')¶
Bases:
_FFmpegAudioAn audio source that transcodes input to s16le 48kHz stereo PCM with
ffmpeg(libopus needed to encode).- Parameters:
- class discord_http.voice.player.PCMAudio(stream)¶
Bases:
AudioSourceAn audio source that reads raw s16le 48kHz stereo PCM frames from a binary stream.
- Parameters:
stream (IOBase)
- class discord_http.voice.player.PCMVolumeTransformer(original, volume=1.0)¶
Bases:
AudioSourceA wrapper that scales the volume of a PCM (non-Opus) audio source using the stdlib
arraymodule.- Parameters:
original (AudioSource)
volume (float)
discord_http.voice.receiver module¶
- class discord_http.voice.receiver.VoiceReceiver(voice_client)¶
Bases:
objectConsumes incoming RTP voice packets and dispatches audio to an
AudioSink.- Parameters:
voice_client (VoiceClient)
- voice_client¶
The voice client this receiver belongs to.
- reset() None¶
Drop all SSRC-keyed state for a fresh voice session.
Called on voice READY, where a fresh session has just allocated new SSRCs. Separate from
stop()becausestop()also detaches and finalizes the sink. A reconnect must keep listening with the existing sink while forgetting mappings, decoders and sequence state tied to SSRCs from the previous session.- Return type:
discord_http.voice.sinks module¶
- class discord_http.voice.sinks.AudioSink¶
Bases:
ABCAbstract base class for consumers of received voice audio.
- wants_opus() bool¶
Whether this sink wants raw Opus payloads instead of decoded PCM.
When
False(the default) the receiver decodes packets to PCM before handing them towrite().- Return type:
- class discord_http.voice.sinks.CallbackSink(callback, *, opus=False)¶
Bases:
AudioSinkAudio sink that forwards every received chunk to a callback.
- class discord_http.voice.sinks.VoiceData(user, pcm, opus, timestamp, ssrc)¶
Bases:
objectRepresents a single chunk of received voice audio for one speaker.
- class discord_http.voice.sinks.WaveSink(destination)¶
Bases:
AudioSinkAudio sink that writes received PCM to a single 48kHz 16-bit stereo WAV file.
Audio from all speakers is appended to the one stream in arrival order; it is not mixed. With a single speaker this produces a normal recording, but simultaneous speakers will have their chunks interleaved back-to-back and sound garbled. To handle overlapping speakers, separate the audio per user first (for example with a
CallbackSinkthat routes eachuserto its own file) and mix the results afterwards.
discord_http.voice.dave module¶
- class discord_http.voice.dave.DaveManager(connection)¶
Bases:
objectManages DAVE (E2EE) for a voice connection, degrading to a no-op when davey is absent.
- Parameters:
connection (VoiceConnection)
- property voice_privacy_code: str | None¶
The privacy code users can compare out-of-band to verify the E2EE session, if any.
- can_encrypt() bool¶
Whether outgoing audio is end-to-end encrypted, which starts once a transition is executed.
- Return type:
- can_decrypt() bool¶
Whether incoming audio can be end-to-end decrypted, which starts once a transition is prepared.
- Return type:
- async reinit(version) None¶
Create or reinitialise the MLS session for a given protocol version.
When
versionis greater than0butdaveyis not installed, a clear, actionableRuntimeErroris raised telling the user how to install the optional dependency. When a session is created, its serialized MLS key package is sent to the voice gateway.- Parameters:
version (
int) – The negotiated DAVE protocol version.0disables end-to-end encryption.- Raises:
RuntimeError – If a non-zero DAVE version is requested but
daveyis not installed.- Return type:
- set_passthrough_mode(enabled, expiry=None) None¶
Toggle passthrough mode on the MLS session.
While in passthrough mode the session does not transform media, allowing audio to flow during transitions where some participants are not yet on the new epoch.
- async handle_binary(opcode, payload) None¶
Dispatch a binary DAVE/MLS operation (opcodes 21-31) received from the gateway.
- async handle_json(opcode, data) None¶
Dispatch a JSON DAVE control op (21, 22, 24) received from the gateway.
Unlike the MLS data ops (25-31), the transition/epoch control ops arrive as regular JSON text frames rather than binary frames, so they are routed here with the decoded
dpayload instead of raw bytes.
discord_http.voice.opus module¶
- discord_http.voice.opus.OPUS_SILENCE = b'\xf8\xff\xfe'¶
The magic Opus frame that encodes silence.
- discord_http.voice.opus.SAMPLES_PER_FRAME = 960¶
The number of samples per channel in a single 20ms frame (960).
- discord_http.voice.opus.SAMPLE_RATE = 48000¶
The sample rate Discord expects, in Hz.
- class discord_http.voice.opus.Decoder¶
Bases:
objectA libopus decoder configured for Discord voice (48kHz, stereo).
- static packet_get_samples_per_frame(data) int¶
Return the number of samples per frame for an Opus packet.
- class discord_http.voice.opus.Encoder(application=2049)¶
Bases:
objectA libopus encoder configured for Discord voice (48kHz, stereo).
- Parameters:
application (int)
- application¶
The Opus application type the encoder was created with.
- exception discord_http.voice.opus.OpusError¶
Bases:
DiscordExceptionRaised when libopus returns an error code.
- add_note(object, /)¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback(object, /)¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception discord_http.voice.opus.OpusNotLoaded¶
Bases:
DiscordExceptionRaised when an Opus operation is attempted but libopus is not available.
- add_note(object, /)¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback(object, /)¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- discord_http.voice.opus.is_loaded() bool¶
Whether libopus is currently loaded, attempting a lazy load once if not yet tried.
- Return type:
- discord_http.voice.opus.load_opus(name=None) None¶
Load libopus and configure all of its bindings.
- Parameters:
name (
str|None) – An explicit path or library name to load. When omitted, the system library is located withctypes.util.find_library().- Raises:
OpusError – If an explicit
namewas given but the library could not be loaded.- Return type:
discord_http.voice.enums module¶
- class discord_http.voice.enums.VoiceOpType(*values)¶
Bases:
BaseEnumRepresents the opcode type of a voice gateway payload.
- identify = 0¶
- select_protocol = 1¶
- ready = 2¶
- heartbeat = 3¶
- session_description = 4¶
- speaking = 5¶
- heartbeat_ack = 6¶
- resume = 7¶
- hello = 8¶
- resumed = 9¶
- clients_connect = 11¶
- client_disconnect = 13¶
- dave_prepare_transition = 21¶
- dave_execute_transition = 22¶
- dave_transition_ready = 23¶
- dave_prepare_epoch = 24¶
- dave_mls_external_sender = 25¶
- dave_mls_key_package = 26¶
- dave_mls_proposals = 27¶
- dave_mls_commit_welcome = 28¶
- dave_mls_announce_commit_transition = 29¶
- dave_mls_welcome = 30¶
- dave_mls_invalid_commit_welcome = 31¶
- classmethod try_get(key, default=None) Optional[Self]¶
Try to get an enum member by name or value, returning a default if not found.