Voice

This section documents everything related to voice connections.

Classes

VoiceClient

class disnake.VoiceClient[source]

Represents a Discord voice connection.

You do not create these, you typically get them from e.g. VoiceChannel.connect().

Warning

In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through opus.load_opus(). Otherwise, your AudioSources must be opus encoded (e.g. using FFmpegOpusAudio) or the library will not be able to transmit audio.

session_id

The voice connection session ID.

Type:

str

token

The voice connection token.

Type:

str

endpoint

The endpoint we are connecting to.

Type:

str

channel

The voice channel connected to.

Type:

abc.Connectable

loop

The event loop that the voice client is running on.

Type:

asyncio.AbstractEventLoop

property guild[source]

The guild we’re connected to.

Type:

Guild

property user[source]

The user connected to voice (i.e. ourselves).

Type:

ClientUser

property latency[source]

Latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This could be referred to as the Discord Voice WebSocket latency and is an analogue of user’s voice latencies as seen in the Discord client.

New in version 1.4.

Type:

float

property average_latency[source]

Average of most recent 20 HEARTBEAT latencies in seconds.

New in version 1.4.

Type:

float

await disconnect(*, force=False)[source]

This function is a coroutine.

Disconnects this voice client from voice.

await move_to(channel)[source]

This function is a coroutine.

Moves you to a different voice channel.

Parameters:

channel (abc.Snowflake) – The channel to move to. Must be a voice channel.

is_connected()[source]

Indicates if the voice client is connected to voice.

play(source, *, after=None)[source]

Plays an AudioSource.

The finalizer, after is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised.

Parameters:
  • source (AudioSource) – The audio source we’re reading from.

  • after (Callable[[Optional[Exception]], Any]) – The finalizer that is called after the stream is exhausted. This function must have a single parameter, error, that denotes an optional exception that was raised during playing.

Raises:
is_playing()[source]

Indicates if we’re currently playing audio.

is_paused()[source]

Indicates if we’re playing audio, but if we’re paused.

stop()[source]

Stops playing audio.

pause()[source]

Pauses the audio playing.

resume()[source]

Resumes the audio playing.

property source[source]

The audio source being played, if playing.

This property can also be used to change the audio source currently being played.

Type:

Optional[AudioSource]

send_audio_packet(data, *, encode=True)[source]

Sends an audio packet composed of the data.

You must be connected to play audio.

Parameters:
  • data (bytes) – The bytes-like object denoting PCM or Opus voice data.

  • encode (bool) – Indicates if data should be encoded into Opus.

Raises:

VoiceProtocol

class disnake.VoiceProtocol(client, channel)[source]

A class that represents the Discord voice protocol.

This is an abstract class. The library provides a concrete implementation under VoiceClient.

This class allows you to implement a protocol to allow for an external method of sending voice, such as Lavalink or a native library implementation.

These classes are passed to abc.Connectable.connect.

Parameters:
  • client (Client) – The client (or its subclasses) that started the connection request.

  • channel (abc.Connectable) – The voice channel that is being connected to.

await on_voice_state_update(data)[source]

This function is a coroutine.

An abstract method that is called when the client’s voice state has changed. This corresponds to VOICE_STATE_UPDATE.

Parameters:

data (dict) – The raw voice state payload.

await on_voice_server_update(data)[source]

This function is a coroutine.

An abstract method that is called when initially connecting to voice. This corresponds to VOICE_SERVER_UPDATE.

Parameters:

data (dict) – The raw voice server update payload.

await connect(*, timeout, reconnect)[source]

This function is a coroutine.

An abstract method called when the client initiates the connection request.

When a connection is requested initially, the library calls the constructor under __init__ and then calls connect(). If connect() fails at some point then disconnect() is called.

Within this method, to start the voice connection flow it is recommended to use Guild.change_voice_state() to start the flow. After which, on_voice_server_update() and on_voice_state_update() will be called. The order that these two are called is unspecified.

Parameters:
  • timeout (float) – The timeout for the connection.

  • reconnect (bool) – Whether reconnection is expected.

await disconnect(*, force)[source]

This function is a coroutine.

An abstract method called when the client terminates the connection.

See cleanup().

Parameters:

force (bool) – Whether the disconnection was forced.

cleanup()[source]

Cleans up the internal state.

This method *must* be called to ensure proper clean-up during a disconnect.

It is advisable to call this from within disconnect() when you are completely done with the voice protocol instance.

This method removes it from the internal state cache that keeps track of currently alive voice clients. Failure to clean-up will cause subsequent connections to report that it’s still connected.

AudioSource

Methods
class disnake.AudioSource[source]

Represents an audio stream.

The audio stream can be Opus encoded or not, however if the audio stream is not Opus encoded then the audio format must be 16-bit 48KHz stereo PCM.

Warning

The audio source reads are done in a separate thread.

read()[source]

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns:

A bytes like object that represents the PCM or Opus data.

Return type:

bytes

is_opus()[source]

Checks if the audio source is already encoded in Opus.

cleanup()[source]

Called when clean-up is needed to be done.

Useful for clearing buffer data or processes after it is done playing audio.

PCMAudio

Attributes
Methods
class disnake.PCMAudio(stream)[source]

Represents raw 16-bit 48KHz stereo PCM audio source.

stream

A file-like object that reads byte data representing raw PCM.

Type:

file object

read()[source]

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns:

A bytes like object that represents the PCM or Opus data.

Return type:

bytes

FFmpegAudio

Methods
class disnake.FFmpegAudio(source, *, executable='ffmpeg', args, **subprocess_kwargs)[source]

Represents an FFmpeg (or AVConv) based AudioSource.

User created AudioSources using FFmpeg differently from how FFmpegPCMAudio and FFmpegOpusAudio work should subclass this.

New in version 1.3.

Danger

As this wraps a subprocess call, ensure that arguments such as executable are not set from direct user input.

cleanup()[source]

Called when clean-up is needed to be done.

Useful for clearing buffer data or processes after it is done playing audio.

FFmpegPCMAudio

Methods
class disnake.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)[source]

An audio source from FFmpeg (or AVConv).

This launches a sub-process to a specific input file given.

Warning

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.

Parameters:
  • source (Union[str, io.BufferedIOBase]) – The input that ffmpeg will take and convert to PCM bytes. If pipe is True then this is a file-like object that is passed to the stdin of ffmpeg.

  • executable (str) –

    The executable name (and path) to use. Defaults to ffmpeg.

    Danger

    As this wraps a subprocess call, ensure that this argument is not set from direct user input.

  • pipe (bool) – If True, denotes that source parameter will be passed to the stdin of ffmpeg. Defaults to False.

  • stderr (Optional[file object]) – A file-like object to pass to the Popen constructor. Could also be an instance of subprocess.PIPE.

  • before_options (Optional[str]) – Extra command line arguments to pass to ffmpeg before the -i flag.

  • options (Optional[str]) – Extra command line arguments to pass to ffmpeg after the -i flag.

Raises:

ClientException – The subprocess failed to be created.

read()[source]

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns:

A bytes like object that represents the PCM or Opus data.

Return type:

bytes

is_opus()[source]

Checks if the audio source is already encoded in Opus.

FFmpegOpusAudio

class disnake.FFmpegOpusAudio(source, *, bitrate=128, codec=None, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)[source]

An audio source from FFmpeg (or AVConv).

This launches a sub-process to a specific input file given. However, rather than producing PCM packets like FFmpegPCMAudio does that need to be encoded to Opus, this class produces Opus packets, skipping the encoding step done by the library.

Alternatively, instead of instantiating this class directly, you can use FFmpegOpusAudio.from_probe() to probe for bitrate and codec information. This can be used to opportunistically skip pointless re-encoding of existing Opus audio data for a boost in performance at the cost of a short initial delay to gather the information. The same can be achieved by passing copy to the codec parameter, but only if you know that the input source is Opus encoded beforehand.

New in version 1.3.

Warning

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.

Parameters:
  • source (Union[str, io.BufferedIOBase]) – The input that ffmpeg will take and convert to Opus bytes. If pipe is True then this is a file-like object that is passed to the stdin of ffmpeg.

  • bitrate (int) – The bitrate in kbps to encode the output to. Defaults to 128.

  • codec (Optional[str]) –

    The codec to use to encode the audio data. Normally this would be just libopus, but is used by FFmpegOpusAudio.from_probe() to opportunistically skip pointlessly re-encoding Opus audio data by passing copy as the codec value. Any values other than copy, opus, or libopus will be considered libopus. Defaults to libopus.

    Warning

    Do not provide this parameter unless you are certain that the audio input is already Opus encoded. For typical use FFmpegOpusAudio.from_probe() should be used to determine the proper value for this parameter.

  • executable (str) –

    The executable name (and path) to use. Defaults to ffmpeg.

    Danger

    As this wraps a subprocess call, ensure that this argument is not set from direct user input.

  • pipe (bool) – If True, denotes that source parameter will be passed to the stdin of ffmpeg. Defaults to False.

  • stderr (Optional[file object]) – A file-like object to pass to the Popen constructor. Could also be an instance of subprocess.PIPE.

  • before_options (Optional[str]) – Extra command line arguments to pass to ffmpeg before the -i flag.

  • options (Optional[str]) – Extra command line arguments to pass to ffmpeg after the -i flag.

Raises:

ClientException – The subprocess failed to be created.

classmethod await from_probe(source, *, method=None, **kwargs)[source]

This function is a coroutine.

A factory method that creates a FFmpegOpusAudio after probing the input source for audio codec and bitrate information.

Examples

Use this function to create an FFmpegOpusAudio instance instead of the constructor:

source = await disnake.FFmpegOpusAudio.from_probe("song.webm")
voice_client.play(source)

If you are on Windows and don’t have ffprobe installed, use the fallback method to probe using ffmpeg instead:

source = await disnake.FFmpegOpusAudio.from_probe("song.webm", method='fallback')
voice_client.play(source)

Using a custom method of determining codec and bitrate:

def custom_probe(source, executable):
    # some analysis code here
    return codec, bitrate

source = await disnake.FFmpegOpusAudio.from_probe("song.webm", method=custom_probe)
voice_client.play(source)
Parameters:
  • source – Identical to the source parameter for the constructor.

  • method (Optional[Union[str, Callable[str, str]]]) – The probing method used to determine bitrate and codec information. As a string, valid values are native to use ffprobe (or avprobe) and fallback to use ffmpeg (or avconv). As a callable, it must take two string arguments, source and executable. Both parameters are the same values passed to this factory function. executable will default to ffmpeg if not provided as a keyword argument.

  • kwargs – The remaining parameters to be passed to the FFmpegOpusAudio constructor, excluding bitrate and codec.

Raises:
  • AttributeError – Invalid probe method, must be 'native' or 'fallback'.

  • TypeError – Invalid value for probe parameter, must be str or a callable.

Returns:

An instance of this class.

Return type:

FFmpegOpusAudio

classmethod await probe(source, *, method=None, executable=None)[source]

This function is a coroutine.

Probes the input source for bitrate and codec information.

Parameters:
Raises:
  • AttributeError – Invalid probe method, must be 'native' or 'fallback'.

  • TypeError – Invalid value for probe parameter, must be str or a callable.

Returns:

A 2-tuple with the codec and bitrate of the input source.

Return type:

Optional[Tuple[Optional[str], Optional[int]]]

read()[source]

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns:

A bytes like object that represents the PCM or Opus data.

Return type:

bytes

is_opus()[source]

Checks if the audio source is already encoded in Opus.

PCMVolumeTransformer

Attributes
Methods
class disnake.PCMVolumeTransformer(original, volume=1.0)[source]

Transforms a previous AudioSource to have volume controls.

This does not work on audio sources that have AudioSource.is_opus() set to True.

Parameters:
  • original (AudioSource) – The original AudioSource to transform.

  • volume (float) – The initial volume to set it to. See volume for more info.

Raises:
property volume[source]

Retrieves or sets the volume as a floating point percentage (e.g. 1.0 for 100%).

cleanup()[source]

Called when clean-up is needed to be done.

Useful for clearing buffer data or processes after it is done playing audio.

read()[source]

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns:

A bytes like object that represents the PCM or Opus data.

Return type:

bytes

Opus Library

disnake.opus.load_opus(name)[source]

Loads the libopus shared library for use with voice.

If this function is not called then the library uses the function ctypes.util.find_library() and then loads that one if available.

Not loading a library and attempting to use PCM based AudioSources will lead to voice not working.

This function propagates the exceptions thrown.

Warning

The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if there’s a mismatch in bitness then the load will throw an exception.

Note

On Windows, this function should not need to be called as the binaries are automatically loaded.

Note

On Windows, the .dll extension is not necessary. However, on Linux the full extension is required to load the library, e.g. libopus.so.1. On Linux however, ctypes.util.find_library() will usually find the library automatically without you having to call this.

Parameters:

name (str) – The filename of the shared library.

disnake.opus.is_loaded()[source]

Function to check if opus lib is successfully loaded either via the ctypes.util.find_library() call of load_opus().

This must return True for voice to work.

Returns:

Indicates if the opus library has been loaded.

Return type:

bool

Discord Models

VoiceState

class disnake.VoiceState[source]

Represents a Discord user’s voice state.

deaf

Whether the user is currently deafened by the guild.

Type:

bool

mute

Whether the user is currently muted by the guild.

Type:

bool

self_mute

Whether the user is currently muted by their own accord.

Type:

bool

self_deaf

Whether the user is currently deafened by their own accord.

Type:

bool

self_stream

Whether the user is currently streaming via ‘Go Live’ feature.

New in version 1.3.

Type:

bool

self_video

Whether the user is currently broadcasting video.

Type:

bool

suppress

Whether the user is suppressed from speaking.

Only applies to stage channels.

New in version 1.7.

Type:

bool

requested_to_speak_at

An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be None if they are not requesting to speak anymore or have been accepted to speak.

Only applies to stage channels.

New in version 1.7.

Type:

Optional[datetime.datetime]

afk

Whether the user is currently in the AFK channel in the guild.

Type:

bool

channel

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

Type:

Optional[Union[VoiceChannel, StageChannel]]

VoiceRegion

class disnake.VoiceRegion[source]

Represents a Discord voice region.

x == y

Checks if two VoiceRegions are equal.

New in version 2.9.

x != y

Checks if two VoiceRegions are not equal.

New in version 2.9.

str(x)

Returns the voice region’s ID.

New in version 2.5.

id

Unique ID for the region.

Type:

str

name

The name of the region.

Type:

str

optimal

True for a single region that is closest to your client.

Type:

bool

deprecated

Whether this is a deprecated voice region (avoid switching to these).

Type:

bool

custom

Whether this is a custom voice region (used for events/etc).

Type:

bool

Enumerations

PartyType

class disnake.PartyType[source]

Represents the type of a voice channel activity/application.

poker

The “Poker Night” activity.

betrayal

The “Betrayal.io” activity.

fishing

The “Fishington.io” activity.

chess

The “Chess In The Park” activity.

letter_tile

The “Letter Tile” activity.

word_snack

The “Word Snacks” activity.

doodle_crew

The “Doodle Crew” activity.

checkers

The “Checkers In The Park” activity.

New in version 2.3.

spellcast

The “SpellCast” activity.

New in version 2.3.

watch_together

The “Watch Together” activity, a Youtube application.

New in version 2.3.

sketch_heads

The “Sketch Heads” activity.

New in version 2.4.

ocho

The “Ocho” activity.

New in version 2.4.

gartic_phone

The “Gartic Phone” activity.

New in version 2.9.

Events