Skip to main content

djs_voice/
gateway.rs

1//! The adapter between djs-voice and the main gateway (D-315, D-324, D-334).
2
3use std::error::Error;
4
5use djs_model::gateway::payload::UpdateVoiceState;
6
7/// Sends Opcode 4 (Update Voice State) through a shard of the main gateway: how a
8/// [`VoiceManager`](crate::VoiceManager) joins, moves between and leaves voice channels.
9///
10/// The manager picks the guild's shard itself (`(guild_id >> 22) % shard_count`) and calls
11/// [`send`](Self::send) with it; the events Discord answers with reach the manager through
12/// [`VoiceManager::process`](crate::VoiceManager::process). djs-rs's `voice` feature
13/// implements both for its `Client`; with djs-gateway alone, implement this trait over the
14/// shards' `MessageSender`s.
15///
16/// Discord documents the command at
17/// <https://discord.com/developers/docs/events/gateway-events#update-voice-state>.
18///
19/// discord.js counterpart: `DiscordGatewayAdapterLibraryMethods#sendPayload` of
20/// `@discordjs/voice`'s adapters.
21///
22/// # Examples
23///
24/// ```
25/// use std::error::Error;
26///
27/// use djs_model::gateway::payload::UpdateVoiceState;
28/// use djs_voice::VoiceGateway;
29///
30/// /// Hands each command to the shard's own channel.
31/// struct Shards {
32///     senders: Vec<tokio::sync::mpsc::UnboundedSender<UpdateVoiceState>>,
33/// }
34///
35/// impl VoiceGateway for Shards {
36///     fn send(
37///         &self,
38///         shard_id: u32,
39///         command: &UpdateVoiceState,
40///     ) -> Result<(), Box<dyn Error + Send + Sync>> {
41///         let sender = usize::try_from(shard_id)
42///             .ok()
43///             .and_then(|id| self.senders.get(id))
44///             .ok_or("no such shard")?;
45///         sender.send(*command)?;
46///         Ok(())
47///     }
48/// }
49/// ```
50pub trait VoiceGateway: Send + Sync + 'static {
51    /// Sends `command` through the shard `shard_id`.
52    ///
53    /// It is called from async code and must not block: queue the command (djs-gateway's
54    /// `MessageSender::command` does) rather than wait for it to be sent.
55    ///
56    /// # Errors
57    ///
58    /// When the command cannot be sent, for example because the shard is closed; the error
59    /// becomes [`JoinError::Gateway`](crate::JoinError::Gateway), or the result of
60    /// [`Call::leave`](crate::Call::leave).
61    fn send(
62        &self,
63        shard_id: u32,
64        command: &UpdateVoiceState,
65    ) -> Result<(), Box<dyn Error + Send + Sync>>;
66}