Skip to main content

djs_rs/
voice.rs

1//! Voice: [djs-voice](djs_voice) plugged into the [`Client`](crate::Client) (D-315,
2//! D-345–D-348), behind the `voice` feature.
3//!
4//! [`Client::voice`](crate::Client::voice) gives the client's [`VoiceManager`]: the client
5//! sends its Opcode 4 through the guild's shard and passes it the voice events, so a bot
6//! only joins and plays. Everything here is djs-voice's API, re-exported.
7//!
8//! The client needs the `GUILD_VOICE_STATES` intent: without it the bot never learns its
9//! voice state, and joins time out (the first `client.voice()` warns about it, D-346).
10//!
11//! discord.js counterpart: `@discordjs/voice` with `guild.voiceAdapterCreator`.
12//!
13//! # Examples
14//!
15//! ```no_run
16//! use djs_rs::{model::gateway::Intents, prelude::*, voice::Input};
17//!
18//! # async fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
19//! let client = Client::builder("token")
20//!     .intents(Intents::GUILDS | Intents::GUILD_VOICE_STATES)
21//!     .build();
22//! let voice = client.voice().clone();
23//! client.on(Events::MessageCreate, move |_ctx, msg| {
24//!     let voice = voice.clone();
25//!     async move {
26//!         if msg.content == "!play"
27//!             && let Some(guild_id) = msg.guild_id
28//!         {
29//!             # let channel_id = djs_rs::model::id::ChannelId::new(1);
30//!             let call = voice.join(guild_id, channel_id).await?;
31//!             call.play(Input::ogg_file("song.opus").await?);
32//!         }
33//!         Ok(())
34//!     }
35//! });
36//! client.login().await?;
37//! # Ok(()) }
38//! ```
39
40use core::sync::atomic::Ordering;
41use std::{error::Error, sync::Arc};
42
43pub use djs_voice::*;
44
45use crate::{
46    context::Shared,
47    model::{
48        gateway::payload::UpdateVoiceState,
49        id::{GuildId, UserId},
50    },
51};
52
53/// The [`VoiceGateway`] of a client: Opcode 4 through the guild's shard, picked with the
54/// total shard count of the current `login` (the manager is made before it is known).
55pub(crate) struct ClientGateway {
56    pub(crate) shared: Arc<Shared>,
57}
58
59impl VoiceGateway for ClientGateway {
60    fn send(
61        &self,
62        _shard_id: u32,
63        command: &UpdateVoiceState,
64    ) -> Result<(), Box<dyn Error + Send + Sync>> {
65        let total = self.shared.total_shards.load(Ordering::Acquire);
66        if total == 0 {
67            return Err("the client is not logged in".into());
68        }
69        let shard = shard_of(command.guild_id, total);
70        let sender = self
71            .shared
72            .shard(shard)
73            .ok_or_else(|| format!("the guild's shard {shard} does not run in this process"))?;
74        sender.command(command)?;
75        Ok(())
76    }
77}
78
79/// The shard of a guild: `(guild_id >> 22) % total`, as Discord documents.
80pub(crate) fn shard_of(guild_id: GuildId, total: u32) -> u32 {
81    let shard = (guild_id.get() >> 22) % u64::from(total.max(1));
82    // Below `total`, a `u32`.
83    u32::try_from(shard).unwrap_or_default()
84}
85
86/// The bot's ID from its token, whose first part is the ID in base64 (D-345); `None` for a
87/// token of another shape.
88pub(crate) fn bot_id(token: &str) -> Option<UserId> {
89    let encoded = token.split('.').next()?;
90    let mut decoded = Vec::with_capacity(encoded.len() * 3 / 4);
91    let mut bits = 0_u32;
92    let mut count = 0;
93    for byte in encoded.bytes().filter(|&byte| byte != b'=') {
94        let value = match byte {
95            b'A'..=b'Z' => byte - b'A',
96            b'a'..=b'z' => byte - b'a' + 26,
97            b'0'..=b'9' => byte - b'0' + 52,
98            b'+' | b'-' => 62,
99            b'/' | b'_' => 63,
100            _ => return None,
101        };
102        bits = (bits << 6) | u32::from(value);
103        count += 6;
104        if count >= 8 {
105            count -= 8;
106            // The byte that just completed: the low eight bits above the leftover ones.
107            decoded.push(u8::try_from((bits >> count) & 0xFF).ok()?);
108        }
109    }
110    let id = core::str::from_utf8(&decoded).ok()?.parse().ok()?;
111    UserId::new_checked(id)
112}
113
114#[cfg(test)]
115mod tests {
116    use super::{bot_id, shard_of};
117    use crate::model::id::{GuildId, UserId};
118
119    #[test]
120    fn the_bot_id_is_read_from_the_token() {
121        // "123456789012345678" in base64, with and without padding, and URL-safe.
122        assert_eq!(
123            bot_id("MTIzNDU2Nzg5MDEyMzQ1Njc4.not.checked"),
124            Some(UserId::new(123_456_789_012_345_678))
125        );
126        // "12345" needs padding.
127        assert_eq!(bot_id("MTIzNDU=.x.y"), Some(UserId::new(12_345)));
128        assert_eq!(bot_id("MTIzNDU.x.y"), Some(UserId::new(12_345)));
129        assert_eq!(bot_id("test-token"), None, "not base64 of an ID");
130        assert_eq!(bot_id(""), None);
131        assert_eq!(bot_id("MA.x.y"), None, "the ID 0");
132        assert_eq!(bot_id("!!!.x.y"), None);
133    }
134
135    #[test]
136    fn guilds_map_to_their_shards() {
137        assert_eq!(shard_of(GuildId::new(1 << 22), 2), 1);
138        assert_eq!(shard_of(GuildId::new(3 << 22), 2), 1);
139        assert_eq!(shard_of(GuildId::new(4 << 22), 2), 0);
140        assert_eq!(shard_of(GuildId::new(41_771_983_423_143_937), 1), 0);
141    }
142}