djs_rs/client.rs
1//! The high-level [`Client`].
2
3use core::{
4 ops::Range,
5 pin::Pin,
6 sync::atomic::{AtomicBool, AtomicU32, Ordering},
7 task::{Context as TaskContext, Poll},
8 time::Duration,
9};
10use std::{
11 future::Future,
12 sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock},
13};
14
15use djs_cache::{Backend, Cache, CacheConfig, DashMapBackend};
16#[cfg(feature = "gateway")]
17use djs_gateway::{
18 Compression, Config, IdentifyQueue, LocalIdentifyQueue, ReceiveErrorKind, SendError, Shard,
19 ShardState, create_shards,
20};
21use djs_model::gateway::{DispatchEvent, GatewayEvent, Intents, payload::UpdatePresence};
22use djs_rest::Rest;
23use futures_core::Stream;
24use tokio::{
25 sync::{mpsc, watch},
26 task::JoinSet,
27 time::{Instant, MissedTickBehavior},
28};
29
30use crate::{
31 Context, Error,
32 collector::EndReason,
33 context::Shared,
34 dispatch::{ReadySeen, ShardTracker, convert},
35 event::{Dispatch, Event, EventKind, ShardEvent, payload},
36 handler::{ErasedHandler, Handler, HandlerError, Registry},
37 router::{
38 AutocompleteInteraction, CommandInteraction, ComponentInteraction, ModalInteraction, Route,
39 },
40};
41
42fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
43 mutex.lock().unwrap_or_else(PoisonError::into_inner)
44}
45
46/// Logs a warning naming the events of `kinds` that none of `intents` covers: Discord never
47/// sends them to this client (D-271).
48pub(crate) fn warn_missing_intents(intents: Intents, kinds: impl IntoIterator<Item = EventKind>) {
49 use core::fmt::Write as _;
50
51 let mut missing = String::new();
52 for kind in kinds {
53 let needed = kind.intents();
54 if !needed.is_empty() && !intents.intersects(needed) {
55 let separator = if missing.is_empty() { "" } else { ", " };
56 let _ = write!(missing, "{separator}{} ({needed:?})", kind.name());
57 }
58 }
59 if !missing.is_empty() {
60 tracing::warn!(
61 events = %missing,
62 "these events are never received without one of their intents; add them with \
63 ClientBuilder::intents"
64 );
65 }
66}
67
68/// How event handlers are executed (D-028).
69///
70/// discord.js counterpart: none (discord.js runs every listener as its event comes, like `HandlerMode::Concurrent`).
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
72#[non_exhaustive]
73pub enum HandlerMode {
74 /// Every handler invocation runs in its own tokio task, so a slow handler never delays
75 /// other events (the discord.js behaviour). Handlers may run in any order and concurrently.
76 #[default]
77 Concurrent,
78 /// Handlers run one after another, in event order, on the shard's task. Use this when the
79 /// order of events matters more than throughput; a slow handler delays all later events of
80 /// its shard (and, if it blocks long enough, the shard's heartbeats).
81 Sequential,
82}
83
84#[cfg(feature = "gateway")]
85#[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
86/// Which shards a [`Client`] runs (D-146).
87///
88/// A shard is one gateway connection; each carries the events of a part of the bot's guilds.
89/// Discord requires sharding from 2 500 guilds on and recommends a shard count in Get Gateway
90/// Bot. Every shard runs in its own tokio task, and shards take turns identifying as Discord's
91/// `max_concurrency` allows.
92///
93/// discord.js counterpart: the `shards` and `shardCount` client options (where `'auto'` is
94/// opt-in; here it is the default).
95#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
96#[non_exhaustive]
97pub enum Shards {
98 /// As many shards as Discord recommends, all in this process (the default).
99 #[default]
100 Auto,
101 /// This many shards, all in this process.
102 Count(u32),
103 /// Only the shards numbered `range` out of `total`, to split a bot over several
104 /// processes.
105 ///
106 /// Each process identifies its shards through its own queue, so start the processes one
107 /// after another (or give them shards of different rate-limit buckets) to stay within
108 /// Discord's identify limit.
109 Range {
110 /// The shards this process runs.
111 range: Range<u32>,
112 /// The bot's total shard count, across all processes.
113 total: u32,
114 },
115}
116
117/// A Discord bot client: connects to the gateway, keeps the session alive and dispatches events
118/// to registered handlers.
119///
120/// Cheap to [`Clone`]; clones share the same handlers, connection and cache.
121///
122/// The client keeps a [`Cache`] only when one is configured with [`ClientBuilder::cache`]
123/// (D-170); unlike discord.js, a bot that does not need one pays nothing for it. `B` is the
124/// cache's storage [`Backend`] (D-172): code that does not name it gets [`DashMapBackend`],
125/// and [`ClientBuilder::cache_backend`] picks another.
126///
127/// discord.js counterpart: `Client`.
128///
129/// # Examples
130///
131/// ```no_run
132/// use djs_rs::prelude::*;
133///
134/// #[tokio::main]
135/// async fn main() -> Result<(), djs_rs::Error> {
136/// let client = Client::builder(std::env::var("DISCORD_TOKEN").unwrap())
137/// .intents(Intents::GUILDS | Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT)
138/// .build();
139///
140/// client.on(Events::ClientReady, |_ctx, ready| async move {
141/// println!("logged in as {}", ready.user.tag());
142/// Ok(())
143/// });
144///
145/// client.on(Events::MessageCreate, |ctx, msg| async move {
146/// if msg.content == "!ping" {
147/// msg.reply(&ctx, "Pong!").await?;
148/// }
149/// Ok(())
150/// });
151///
152/// client.login().await
153/// }
154/// ```
155pub struct Client<B: Backend = DashMapBackend> {
156 inner: Arc<Inner<B>>,
157}
158
159struct Inner<B: Backend> {
160 token: Box<str>,
161 intents: Intents,
162 rest: Rest,
163 #[cfg(feature = "gateway")]
164 compression: Compression,
165 #[cfg(feature = "gateway")]
166 gateway_url: Option<Box<str>>,
167 #[cfg(feature = "gateway")]
168 shards: Shards,
169 #[cfg(feature = "gateway")]
170 presence: Option<UpdatePresence>,
171 mode: HandlerMode,
172 cache: Option<Arc<Cache<B>>>,
173 registry: RwLock<Arc<Registry<B>>>,
174 subscribers: Mutex<Vec<mpsc::UnboundedSender<ShardEvent>>>,
175 has_subscribers: AtomicBool,
176 running: AtomicBool,
177 /// The shards of the current `login` and how many of them have been ready (D-224).
178 shard_count: AtomicU32,
179 ready_shards: AtomicU32,
180 /// The application ID, the collectors and the shards' senders, shared with every
181 /// [`Context`].
182 shared: Arc<Shared>,
183 compiled: Compiled<B>,
184 /// The assignment of a cluster process (D-300).
185 #[cfg(feature = "sharding")]
186 cluster: Option<crate::sharding::ClusterAssignment>,
187 /// The commands this cluster process handles, by name (D-308).
188 #[cfg(feature = "sharding")]
189 commands: RwLock<std::collections::HashMap<&'static str, crate::sharding::Handler<Client<B>>>>,
190 /// The state and latency of each shard of a cluster process, for its stats (D-310).
191 #[cfg(feature = "sharding")]
192 shard_slots: RwLock<Vec<Arc<crate::sharding::ShardSlot>>>,
193 /// The bot's voice calls (D-345).
194 #[cfg(feature = "voice")]
195 voice: crate::voice::VoiceManager,
196 /// `voice()` checked the intents and the token once (D-346).
197 #[cfg(feature = "voice")]
198 voice_checked: std::sync::Once,
199}
200
201/// A future boxed inside this crate (D-287).
202type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
203
204/// The entry points of the client's code that depends on the cache backend, called through
205/// function pointers (D-287). [`Client::builder`] — not generic — sets the ones compiled in
206/// this crate for [`DashMapBackend`], and [`ClientBuilder::cache_backend`] the generic ones, so
207/// a bot that keeps the default backend does not compile the client's event loop in its own
208/// crate again on every edit.
209struct Compiled<B: Backend> {
210 build: fn(ClientBuilder<B>) -> Client<B>,
211 #[cfg(feature = "gateway")]
212 login: for<'a> fn(&'a Client<B>) -> BoxFuture<'a, Result<(), Error>>,
213}
214
215impl<B: Backend> Compiled<B> {
216 /// The entry points for `B`, compiled in the crate that names `B`.
217 fn generic() -> Self {
218 #[cfg(feature = "gateway")]
219 fn login<B: Backend>(client: &Client<B>) -> BoxFuture<'_, Result<(), Error>> {
220 Box::pin(client.login_inner())
221 }
222 Self {
223 build: ClientBuilder::build_inner,
224 #[cfg(feature = "gateway")]
225 login: login::<B>,
226 }
227 }
228}
229
230impl<B: Backend> Clone for Compiled<B> {
231 fn clone(&self) -> Self {
232 *self
233 }
234}
235
236impl<B: Backend> Copy for Compiled<B> {}
237
238impl<B: Backend> core::fmt::Debug for Compiled<B> {
239 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
240 f.debug_struct("Compiled").finish_non_exhaustive()
241 }
242}
243
244impl<B: Backend> Clone for Client<B> {
245 fn clone(&self) -> Self {
246 Self {
247 inner: Arc::clone(&self.inner),
248 }
249 }
250}
251
252impl<B: Backend> core::fmt::Debug for Client<B> {
253 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
254 f.debug_struct("Client")
255 .field("intents", &self.inner.intents)
256 .field("mode", &self.inner.mode)
257 .field("cache", &self.inner.cache)
258 .field("running", &self.inner.running.load(Ordering::Relaxed))
259 .finish_non_exhaustive()
260 }
261}
262
263impl Client {
264 /// Returns a builder for a client authenticated with `token` (without the `Bot ` prefix).
265 ///
266 /// discord.js counterpart: `new Client(options)`.
267 pub fn builder(token: impl Into<String>) -> ClientBuilder {
268 Self::builder_with(token.into())
269 }
270
271 /// [`builder`](Self::builder) without its generic argument, so that it — and with it the
272 /// client's code for the default backend, through [`Compiled`] — is compiled in this crate
273 /// only (D-287). Never inlined into a bot's crate, for the same reason.
274 #[inline(never)]
275 fn builder_with(token: String) -> ClientBuilder {
276 ClientBuilder {
277 token,
278 intents: Intents::empty(),
279 rest: None,
280 #[cfg(feature = "gateway")]
281 compression: Compression::default(),
282 #[cfg(feature = "gateway")]
283 gateway_url: None,
284 #[cfg(feature = "gateway")]
285 shards: Shards::default(),
286 #[cfg(feature = "gateway")]
287 presence: None,
288 mode: HandlerMode::default(),
289 cache: None,
290 backend: DashMapBackend::new(),
291 compiled: Compiled::generic(),
292 #[cfg(feature = "sharding")]
293 cluster: None,
294 }
295 }
296}
297
298impl<B: Backend> Client<B> {
299 /// Registers a handler for an event.
300 ///
301 /// The handler receives a [`Context`] and the event payload behind an [`Arc`] (shared by all
302 /// handlers of the event). It returns `Result<(), HandlerError>`: use `?` freely — errors are
303 /// logged through `tracing` at `error` level. Handlers can be added at any time, including
304 /// while the client is running.
305 ///
306 /// discord.js counterpart: `client.on(event, listener)`.
307 ///
308 /// # Examples
309 ///
310 /// ```no_run
311 /// # use djs_rs::prelude::*;
312 /// # let client = Client::builder("token").build();
313 /// client.on(Events::MessageCreate, |ctx, msg| async move {
314 /// if msg.content == "!ping" {
315 /// msg.reply(&ctx, "Pong!").await?;
316 /// }
317 /// Ok(())
318 /// });
319 /// ```
320 pub fn on<E, F, Fut>(&self, event: E, handler: F) -> &Self
321 where
322 E: Event,
323 F: Fn(Context<B>, Arc<E::Payload>) -> Fut + Send + Sync + 'static,
324 Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
325 {
326 let _ = event;
327 if self.inner.running.load(Ordering::Acquire) {
328 // Registered while running: login already checked the others (D-271).
329 warn_missing_intents(self.inner.intents, [E::KIND]);
330 }
331 let handler: Arc<dyn ErasedHandler<B>> = Arc::new(Handler::<E, F>::new(handler));
332 let mut registry = self
333 .inner
334 .registry
335 .write()
336 .unwrap_or_else(PoisonError::into_inner);
337 *registry = Arc::new(registry.with(E::KIND, handler));
338 self
339 }
340
341 /// Replaces the handler table with one changed by `change` (copy-on-write).
342 fn change_registry(&self, change: impl FnOnce(&mut Registry<B>)) -> &Self {
343 let mut registry = self
344 .inner
345 .registry
346 .write()
347 .unwrap_or_else(PoisonError::into_inner);
348 let mut next = Registry::clone(®istry);
349 change(&mut next);
350 *registry = Arc::new(next);
351 self
352 }
353
354 /// Routes the command `name` to `handler` (the [router](crate::router), D-251–D-253).
355 ///
356 /// `name` is the command's full name as Discord shows it, with single spaces: `"ping"`,
357 /// `"mod ban"` (a subcommand), `"mod config set"` (a subcommand in a group), or the name
358 /// of a user or message command. A route for `"mod"` or `"mod config"` also receives the
359 /// subcommands below it that have no route of their own. Registering a name again
360 /// replaces its handler; routes can be added while the client runs.
361 ///
362 /// The handler receives a [`CommandInteraction`](crate::router::CommandInteraction): the
363 /// command's data (`get_string`, …) and its responses (`reply`, …). Like event handlers it
364 /// returns `Result<(), HandlerError>`, and errors are logged. The router only routes:
365 /// commands are registered with Discord through [`Context::commands`] (D-255), and
366 /// [`Events::InteractionCreate`](crate::Events::InteractionCreate) still fires.
367 ///
368 /// discord.js has no counterpart (a `switch` on `interaction.commandName`).
369 ///
370 /// # Examples
371 ///
372 /// ```no_run
373 /// # use djs_rs::prelude::*;
374 /// # let client = Client::builder("token").build();
375 /// client.command("ping", |ctx, cmd| async move {
376 /// cmd.reply(&ctx, "Pong!").await?;
377 /// Ok(())
378 /// });
379 /// client.command("mod ban", |ctx, cmd| async move {
380 /// let reason = cmd.get_string("reason").unwrap_or("no reason");
381 /// cmd.reply(&ctx, format!("Banned: {reason}")).await?;
382 /// Ok(())
383 /// });
384 /// ```
385 pub fn command<F, Fut>(&self, name: &str, handler: F) -> &Self
386 where
387 F: Fn(Context<B>, CommandInteraction) -> Fut + Send + Sync + 'static,
388 Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
389 {
390 let route = Arc::new(Route::new(name, handler));
391 self.change_registry(|registry| {
392 registry.routes.commands.insert(name.into(), route);
393 })
394 }
395
396 /// Routes the autocomplete interactions of the command `name` to `handler`; `name` is
397 /// matched like in [`command`](Self::command). The handler receives an
398 /// [`AutocompleteInteraction`](crate::router::AutocompleteInteraction) and answers with
399 /// [`respond`](crate::ext::InteractionExt::respond).
400 ///
401 /// discord.js counterpart: an `interactionCreate` listener checking `isAutocomplete()` and `commandName`.
402 ///
403 /// # Examples
404 ///
405 /// ```no_run
406 /// # use djs_rs::{model::{application_command::Choice, interaction::AutocompleteChoices}, prelude::*};
407 /// # let client = Client::builder("token").build();
408 /// client.autocomplete("search", |ctx, search| async move {
409 /// let typed = search.focused_value().unwrap_or_default();
410 /// let choices = vec![Choice::new(format!("{typed}…"), typed.into())];
411 /// search.respond(&ctx, AutocompleteChoices::String(choices)).await?;
412 /// Ok(())
413 /// });
414 /// ```
415 pub fn autocomplete<F, Fut>(&self, name: &str, handler: F) -> &Self
416 where
417 F: Fn(Context<B>, AutocompleteInteraction) -> Fut + Send + Sync + 'static,
418 Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
419 {
420 let route = Arc::new(Route::new(name, handler));
421 self.change_registry(|registry| {
422 registry.routes.autocomplete.insert(name.into(), route);
423 })
424 }
425
426 /// Routes the buttons and select menus whose custom ID is `name`, or starts with `name:`,
427 /// to `handler` (D-254). What follows the `:` is the handler's
428 /// [`args`](crate::router::ComponentInteraction::args): a button `delete:123` reaches the
429 /// route `"delete"` with the arguments `123`. Registering a name again replaces its
430 /// handler.
431 ///
432 /// discord.js counterpart: an `interactionCreate` listener checking `isMessageComponent()` and `customId`.
433 ///
434 /// # Panics
435 ///
436 /// Panics if `name` contains a `:` (it could never match).
437 ///
438 /// # Examples
439 ///
440 /// ```no_run
441 /// # use djs_rs::prelude::*;
442 /// # let client = Client::builder("token").build();
443 /// client.component("delete", |ctx, button| async move {
444 /// let message_id = button.args();
445 /// button.update(&ctx, format!("Deleted {message_id}")).await?;
446 /// Ok(())
447 /// });
448 /// ```
449 #[track_caller]
450 pub fn component<F, Fut>(&self, name: &str, handler: F) -> &Self
451 where
452 F: Fn(Context<B>, ComponentInteraction) -> Fut + Send + Sync + 'static,
453 Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
454 {
455 assert!(
456 !name.contains(':'),
457 "a component route name cannot contain `:`: {name:?}"
458 );
459 let route = Arc::new(Route::new(name, handler));
460 self.change_registry(|registry| {
461 registry.routes.components.insert(name.into(), route);
462 })
463 }
464
465 /// Routes the modals whose custom ID is `name`, or starts with `name:`, to `handler`, like
466 /// [`component`](Self::component). The handler receives a
467 /// [`ModalInteraction`](crate::router::ModalInteraction) with the submitted fields.
468 ///
469 /// discord.js counterpart: an `interactionCreate` listener checking `isModalSubmit()` and `customId`.
470 ///
471 /// # Panics
472 ///
473 /// Panics if `name` contains a `:` (it could never match).
474 ///
475 /// # Examples
476 ///
477 /// ```no_run
478 /// # use djs_rs::prelude::*;
479 /// # let client = Client::builder("token").build();
480 /// client.modal("feedback", |ctx, modal| async move {
481 /// let text = modal.text_value("text").unwrap_or_default();
482 /// modal.reply(&ctx, format!("Thanks for: {text}")).await?;
483 /// Ok(())
484 /// });
485 /// ```
486 #[track_caller]
487 pub fn modal<F, Fut>(&self, name: &str, handler: F) -> &Self
488 where
489 F: Fn(Context<B>, ModalInteraction) -> Fut + Send + Sync + 'static,
490 Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
491 {
492 assert!(
493 !name.contains(':'),
494 "a modal route name cannot contain `:`: {name:?}"
495 );
496 let route = Arc::new(Route::new(name, handler));
497 self.change_registry(|registry| {
498 registry.routes.modals.insert(name.into(), route);
499 })
500 }
501
502 /// The intents the registered handlers, routes and running collectors need (D-272): the
503 /// union of their events' [`Event::INTENTS`], to print or compare with the client's.
504 ///
505 /// Requesting all of them receives every such event; a bot may still leave some out (for
506 /// example `DIRECT_MESSAGES` when it only reads guild messages). It does not include
507 /// [`Intents::MESSAGE_CONTENT`], which changes what message events contain rather than
508 /// which arrive. The client's intents stay what [`ClientBuilder::intents`] set; at login
509 /// it warns about events none of them covers (D-271).
510 ///
511 /// discord.js has no counterpart.
512 ///
513 /// # Examples
514 ///
515 /// ```no_run
516 /// # use djs_rs::prelude::*;
517 /// let client = Client::builder("token").intents(Intents::GUILDS).build();
518 /// client.on(Events::MessageReactionAdd, |_ctx, _reaction| async move { Ok(()) });
519 /// assert!(client.required_intents().contains(Intents::GUILD_MESSAGE_REACTIONS));
520 /// ```
521 #[must_use]
522 pub fn required_intents(&self) -> Intents {
523 self.listened()
524 .fold(Intents::empty(), |intents, kind| intents | kind.intents())
525 }
526
527 /// The events registered handlers, routes and running collectors listen to.
528 fn listened(&self) -> impl Iterator<Item = EventKind> {
529 let registry = self.registry();
530 let collectors = Arc::clone(&self.inner.shared.collectors);
531 EventKind::ALL.into_iter().filter(move |&kind| {
532 !registry.get(kind).is_empty()
533 || (kind == EventKind::InteractionCreate && !registry.routes.is_empty())
534 || collectors.wants(kind)
535 })
536 }
537
538 /// Returns a stream of every event the client receives (D-029).
539 ///
540 /// This is the alternative to [`on`](Self::on) for full control. Each call creates an
541 /// independent subscriber that receives every event from the moment it was created.
542 ///
543 /// **Note:** the stream is unbounded — consume it promptly, or drop it, to avoid
544 /// accumulating events in memory.
545 ///
546 /// discord.js counterpart: none (discord.js delivers events to listeners only).
547 ///
548 /// # Examples
549 ///
550 /// ```no_run
551 /// # use djs_rs::{event::Dispatch, prelude::*};
552 /// # async fn run(client: Client) {
553 /// let mut events = client.events();
554 /// tokio::spawn(async move {
555 /// while let Some(event) = events.next().await {
556 /// if let Dispatch::MessageCreate(message) = event.event {
557 /// println!("{}", message.content);
558 /// }
559 /// }
560 /// });
561 /// client.login().await.unwrap();
562 /// # }
563 /// ```
564 #[must_use]
565 pub fn events(&self) -> EventStream {
566 let (tx, rx) = mpsc::unbounded_channel();
567 lock(&self.inner.subscribers).push(tx);
568 self.inner.has_subscribers.store(true, Ordering::Release);
569 EventStream { rx }
570 }
571
572 /// Returns the REST client.
573 ///
574 /// discord.js counterpart: `Client#rest`.
575 #[must_use]
576 pub fn rest(&self) -> &Rest {
577 &self.inner.rest
578 }
579
580 /// Returns the bot's voice calls: join voice channels, play audio, leave (D-345).
581 ///
582 /// The manager is there from the start; the client sends its Opcode 4 through the
583 /// guild's shard and passes it the voice events. Joins need the client logged in, with
584 /// the guild's shard in this process, and the `GUILD_VOICE_STATES` intent: the first
585 /// call warns when the intent is missing (D-346). [`shutdown`](Self::shutdown) leaves
586 /// every call (D-348).
587 ///
588 /// discord.js counterpart: `joinVoiceChannel({ adapterCreator: guild.voiceAdapterCreator,
589 /// … })` of `@discordjs/voice`.
590 ///
591 /// # Examples
592 ///
593 /// ```no_run
594 /// # use djs_rs::{model::id::{ChannelId, GuildId}, prelude::*};
595 /// # async fn run(client: Client, guild: GuildId, channel: ChannelId)
596 /// # -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
597 /// use djs_rs::voice::Input;
598 ///
599 /// let call = client.voice().join(guild, channel).await?;
600 /// call.play(Input::ogg_file("song.opus").await?);
601 /// # Ok(()) }
602 /// ```
603 #[cfg(feature = "voice")]
604 #[cfg_attr(docsrs, doc(cfg(feature = "voice")))]
605 #[must_use]
606 pub fn voice(&self) -> &crate::voice::VoiceManager {
607 self.inner.voice_checked.call_once(|| {
608 if !self.inner.intents.contains(Intents::GUILD_VOICE_STATES) {
609 tracing::warn!(
610 "voice needs the GUILD_VOICE_STATES intent: without it the bot never gets \
611 its voice state and joins time out; add it with ClientBuilder::intents"
612 );
613 }
614 if crate::voice::bot_id(&self.inner.token).is_none() {
615 tracing::warn!(
616 "the token does not start with the bot's ID, so voice cannot recognize \
617 the bot's voice state and joins time out"
618 );
619 }
620 });
621 &self.inner.voice
622 }
623
624 /// Leaves the voice calls of shard `number` before it closes (D-348). Their Opcode 4 is
625 /// queued, not waited for: the closed session takes the bot out of its channels anyway.
626 #[cfg(feature = "voice")]
627 async fn leave_calls(&self, number: u32) {
628 let total = self.inner.shared.total_shards.load(Ordering::Acquire);
629 let mut leaving = tokio::task::JoinSet::new();
630 for call in self.inner.voice.calls() {
631 if crate::voice::shard_of(call.guild_id(), total) == number {
632 leaving.spawn(async move {
633 let _ = call.leave().await;
634 });
635 }
636 }
637 // Closing a voice connection waits for its server a second at most.
638 let all = async { while leaving.join_next().await.is_some() {} };
639 let _ = tokio::time::timeout(core::time::Duration::from_secs(2), all).await;
640 }
641
642 /// Returns the cache, or `None` if the client was built without one (the default, D-170).
643 ///
644 /// Every event is applied to the cache before its handlers run (D-171), so a handler sees
645 /// the state after its event. Handlers reach the cache through [`Context::cache`] too.
646 ///
647 /// discord.js counterpart: the managers' `cache` collections (`client.guilds.cache`,
648 /// `client.users.cache`, …), which always exist there.
649 ///
650 /// # Examples
651 ///
652 /// ```no_run
653 /// use djs_rs::{cache::CacheConfig, prelude::*};
654 ///
655 /// let client = Client::builder("token")
656 /// .intents(Intents::GUILDS)
657 /// .cache(CacheConfig::default())
658 /// .build();
659 ///
660 /// client.on(Events::MessageCreate, |ctx, msg| async move {
661 /// let cache = ctx.cache().expect("the client has a cache");
662 /// if let Some(guild) = msg.guild_id.and_then(|id| cache.guilds().get(id)) {
663 /// println!("a message in {}", guild.name);
664 /// }
665 /// Ok(())
666 /// });
667 /// ```
668 #[must_use]
669 pub fn cache(&self) -> Option<&Cache<B>> {
670 self.inner.cache.as_deref()
671 }
672
673 /// This process's cluster, for a client built with [`ClientBuilder::cluster`]: its
674 /// assignment, the commands it handles and its requests to the other clusters (D-301).
675 /// `None` for any other client.
676 ///
677 /// discord.js counterpart: `Client#shard`.
678 #[cfg(feature = "sharding")]
679 #[cfg_attr(docsrs, doc(cfg(feature = "sharding")))]
680 #[must_use]
681 pub fn cluster(&self) -> Option<crate::sharding::ClusterClient<B>> {
682 self.inner
683 .cluster
684 .is_some()
685 .then(|| crate::sharding::ClusterClient::new(self.clone()))
686 }
687
688 #[cfg(feature = "sharding")]
689 pub(crate) fn assignment(&self) -> Option<&crate::sharding::ClusterAssignment> {
690 self.inner.cluster.as_ref()
691 }
692
693 /// The open connection to the manager, while a cluster process is logged in.
694 #[cfg(feature = "sharding")]
695 pub(crate) fn link(&self) -> Option<Arc<crate::sharding::Link>> {
696 self.inner
697 .shared
698 .link
699 .lock()
700 .unwrap_or_else(PoisonError::into_inner)
701 .clone()
702 }
703
704 #[cfg(feature = "sharding")]
705 pub(crate) fn add_cluster_command(
706 &self,
707 name: &'static str,
708 handler: crate::sharding::Handler<Client<B>>,
709 ) {
710 self.inner
711 .commands
712 .write()
713 .unwrap_or_else(PoisonError::into_inner)
714 .insert(name, handler);
715 }
716
717 #[cfg(feature = "sharding")]
718 fn shard_slot(&self, number: u32) -> Option<Arc<crate::sharding::ShardSlot>> {
719 self.inner
720 .shard_slots
721 .read()
722 .unwrap_or_else(PoisonError::into_inner)
723 .iter()
724 .find(|slot| slot.number() == number)
725 .cloned()
726 }
727
728 /// The state and latency of this cluster process's shards.
729 #[cfg(feature = "sharding")]
730 pub(crate) fn shard_stats(&self) -> Vec<crate::sharding::ShardStats> {
731 self.inner
732 .shard_slots
733 .read()
734 .unwrap_or_else(PoisonError::into_inner)
735 .iter()
736 .map(|slot| slot.stats())
737 .collect()
738 }
739
740 #[cfg(feature = "sharding")]
741 pub(crate) fn cluster_command(
742 &self,
743 name: &str,
744 ) -> Option<crate::sharding::Handler<Client<B>>> {
745 self.inner
746 .commands
747 .read()
748 .unwrap_or_else(PoisonError::into_inner)
749 .get(name)
750 .cloned()
751 }
752}
753
754/// Logging in and running the shards (the `gateway` feature, D-395).
755#[cfg(feature = "gateway")]
756#[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
757impl<B: Backend> Client<B> {
758 /// Connects to Discord and processes events until [`shutdown`](Self::shutdown) is called or
759 /// the connection fails fatally.
760 ///
761 /// The connection heals itself: disconnects are resumed and failures retried with backoff.
762 ///
763 /// The client asks Discord ([Get Gateway Bot]) for the gateway URL, the recommended shard
764 /// count and `max_concurrency`, then runs every shard chosen with
765 /// [`ClientBuilder::shards`] in its own task. A fatal error on any shard stops them all.
766 /// Get Gateway Bot is skipped if both [`ClientBuilder::gateway_url`] and a fixed shard
767 /// count are configured (shards then identify one at a time), and in a cluster process
768 /// (`ClientBuilder::cluster`, with the `sharding` feature), which gets them from its
769 /// manager.
770 ///
771 /// [Get Gateway Bot]: https://docs.discord.com/developers/events/gateway#get-gateway-bot
772 ///
773 /// discord.js counterpart: `Client#login`.
774 ///
775 /// # Errors
776 ///
777 /// Returns [`Error::Rest`] if the gateway URL cannot be fetched (for example because the
778 /// token is invalid), [`Error::SessionStartLimit`] if Discord's daily session start limit
779 /// does not allow starting every shard, [`Error::Gateway`] on a fatal gateway close (invalid
780 /// token, disallowed intents, …), or [`Error::AlreadyRunning`] if the client is already
781 /// logged in.
782 ///
783 /// # Panics
784 ///
785 /// Re-raises a panic of a shard's task (only possible with [`HandlerMode::Sequential`], when
786 /// a handler panics).
787 pub fn login(&self) -> impl Future<Output = Result<(), Error>> + Send + '_ {
788 (self.inner.compiled.login)(self)
789 }
790
791 /// [`login`](Self::login)'s body, reached through [`Compiled`].
792 async fn login_inner(&self) -> Result<(), Error> {
793 if self.inner.running.swap(true, Ordering::AcqRel) {
794 return Err(Error::AlreadyRunning);
795 }
796 let result = self.run().await;
797 self.inner.running.store(false, Ordering::Release);
798 result
799 }
800
801 /// Updates the bot's presence (status and activities) on every running shard. Each shard
802 /// also keeps it for its later sessions (D-148).
803 ///
804 /// Has no effect if the client is not running; set the presence to start with through
805 /// [`ClientBuilder::presence`].
806 ///
807 /// discord.js counterpart: `ClientUser#setPresence`.
808 ///
809 /// # Errors
810 ///
811 /// Returns [`SendError::Closed`] if a shard has stopped (the client is shutting down);
812 /// the other shards are still updated.
813 ///
814 /// # Examples
815 ///
816 /// ```no_run
817 /// use djs_rs::{
818 /// model::gateway::{Activity, Status, payload::UpdatePresence},
819 /// prelude::*,
820 /// };
821 ///
822 /// # let client = Client::builder("token").build();
823 /// let handle = client.clone();
824 /// client.on(Events::MessageCreate, move |_ctx, msg| {
825 /// let client = handle.clone();
826 /// async move {
827 /// if msg.content == "!busy" {
828 /// let busy = UpdatePresence::new(Status::DoNotDisturb, [Activity::custom("Busy")]);
829 /// client.set_presence(&busy)?;
830 /// }
831 /// Ok(())
832 /// }
833 /// });
834 /// ```
835 pub fn set_presence(&self, presence: &UpdatePresence) -> Result<(), SendError> {
836 let mut result = Ok(());
837 let shards = self
838 .inner
839 .shared
840 .shards
841 .read()
842 .unwrap_or_else(PoisonError::into_inner);
843 for (_, sender) in shards.iter() {
844 if let Err(error) = sender.update_presence(presence) {
845 result = result.and(Err(error));
846 }
847 }
848 result
849 }
850
851 /// Asks a running client to disconnect; [`login`](Self::login) then returns `Ok(())`.
852 ///
853 /// The session is invalidated (the bot appears offline). Has no effect if the client is not
854 /// running.
855 ///
856 /// discord.js counterpart: `Client#destroy`.
857 pub fn shutdown(&self) {
858 self.inner.shared.shutdown.send_replace(true);
859 }
860
861 async fn run(&self) -> Result<(), Error> {
862 let inner = &*self.inner;
863 warn_missing_intents(inner.intents, self.listened());
864 inner.shared.shutdown.send_replace(false);
865 // Subscribed before anything can wait, so a shutdown during start-up is not missed.
866 let shutdown = inner.shared.shutdown.subscribe();
867 // A cluster process stays connected to its manager while it runs (D-300).
868 #[cfg(feature = "sharding")]
869 let manager = match &inner.cluster {
870 Some(assignment) => {
871 let commands = Arc::new(crate::sharding::Table {
872 client: self.clone(),
873 started: std::time::Instant::now(),
874 });
875 Some(
876 assignment
877 .connect(Arc::clone(&inner.shared), commands)
878 .await?,
879 )
880 }
881 None => None,
882 };
883
884 let plan = self.plan().await?;
885 #[cfg(feature = "sharding")]
886 if inner.cluster.is_some() {
887 *inner
888 .shard_slots
889 .write()
890 .unwrap_or_else(PoisonError::into_inner) = plan
891 .range
892 .clone()
893 .map(|number| Arc::new(crate::sharding::ShardSlot::new(number)))
894 .collect();
895 }
896 tracing::info!(
897 shards = ?plan.range,
898 total = plan.total,
899 max_concurrency = plan.max_concurrency,
900 "starting shards"
901 );
902 let identify_queue: Arc<dyn IdentifyQueue> =
903 Arc::new(LocalIdentifyQueue::new(plan.max_concurrency));
904 // The manager is the IDENTIFY queue of every cluster process (D-299).
905 #[cfg(feature = "sharding")]
906 let identify_queue = manager
907 .as_ref()
908 .map_or(identify_queue, crate::sharding::Connection::identify_queue);
909 let mut config = Config::builder(&*inner.token, inner.intents)
910 .gateway_url(plan.url)
911 .compression(inner.compression)
912 .identify_queue(identify_queue);
913 if let Some(presence) = &inner.presence {
914 config = config.presence(presence.clone());
915 }
916 let config = config.build();
917
918 inner
919 .shard_count
920 .store(plan.range.end - plan.range.start, Ordering::Release);
921 inner
922 .shared
923 .total_shards
924 .store(plan.total, Ordering::Release);
925 inner.ready_shards.store(0, Ordering::Release);
926
927 let mut sweepers = self.spawn_sweepers();
928 let mut tasks = JoinSet::new();
929 for shard in create_shards(plan.range, plan.total, config) {
930 inner
931 .shared
932 .shards
933 .write()
934 .unwrap_or_else(PoisonError::into_inner)
935 .push((shard.id().number(), shard.sender()));
936 let (client, shutdown) = (self.clone(), shutdown.clone());
937 tasks.spawn(async move { client.run_shard(shard, shutdown).await });
938 }
939
940 let mut result = Ok(());
941 while let Some(finished) = tasks.join_next().await {
942 match finished {
943 Ok(Ok(())) => {}
944 Ok(Err(error)) => {
945 if result.is_ok() {
946 // A fatal error on one shard stops the whole client.
947 inner.shared.shutdown.send_replace(true);
948 result = Err(error);
949 }
950 }
951 // Tasks are only cancelled when the set is dropped, so this is a panic.
952 Err(error) => {
953 if let Ok(panic) = error.try_into_panic() {
954 std::panic::resume_unwind(panic);
955 }
956 }
957 }
958 }
959 inner
960 .shared
961 .shards
962 .write()
963 .unwrap_or_else(PoisonError::into_inner)
964 .clear();
965 // The collectors waiting for this client's events end with it.
966 inner.shared.collectors.end_all(EndReason::Shutdown);
967 sweepers.shutdown().await;
968 result
969 }
970
971 /// Spawns one task for each periodic sweep of the cache's [`SweepConfig`](djs_cache::SweepConfig)
972 /// (D-167). The tasks run until the returned set is shut down or dropped.
973 fn spawn_sweepers(&self) -> JoinSet<()> {
974 let mut tasks = JoinSet::new();
975 let Some(cache) = &self.inner.cache else {
976 return tasks;
977 };
978 let sweepers = cache.config().sweepers();
979 if let Some(sweep) = sweepers.messages {
980 let cache = Arc::clone(cache);
981 tasks.spawn(every(sweep.interval, "messages", move || {
982 cache.sweep_messages_older_than(sweep.lifetime)
983 }));
984 }
985 if let Some(sweep) = sweepers.threads {
986 let cache = Arc::clone(cache);
987 tasks.spawn(every(sweep.interval, "threads", move || {
988 cache.sweep_archived_threads(sweep.lifetime)
989 }));
990 }
991 tasks
992 }
993
994 /// A shard's `READY`: keeps the application ID (D-245) and, at the last shard's first
995 /// `READY`, emits `ClientReady` (D-224).
996 fn on_ready(
997 &self,
998 seen: ReadySeen,
999 counted_ready: &mut bool,
1000 registry: &Registry<B>,
1001 out: &mut Vec<Dispatch>,
1002 ) {
1003 // The same application on every shard and every login.
1004 let _ = self.inner.shared.application_id.set(seen.application_id);
1005 if *counted_ready {
1006 return;
1007 }
1008 *counted_ready = true;
1009 let ready_shards = self.inner.ready_shards.fetch_add(1, Ordering::AcqRel) + 1;
1010 if ready_shards == self.inner.shard_count.load(Ordering::Acquire)
1011 && let Some(ready) = seen.ready
1012 && self.wants(registry, EventKind::ClientReady)
1013 {
1014 out.push(Dispatch::ClientReady(ready));
1015 }
1016 }
1017
1018 /// Drives one shard until shutdown or a fatal error, emitting its events and its lifecycle
1019 /// events (D-226).
1020 async fn run_shard(
1021 &self,
1022 mut shard: Shard,
1023 mut shutdown: watch::Receiver<bool>,
1024 ) -> Result<(), Error> {
1025 let ctx = Context::new(
1026 self.inner.rest.clone(),
1027 shard.id(),
1028 shard.sender(),
1029 self.inner.cache.clone(),
1030 Arc::clone(&self.inner.shared),
1031 );
1032 let mut tracker = ShardTracker::default();
1033 let mut out = Vec::new();
1034 // Whether the session was established and not lost since (for `ShardReconnecting`).
1035 let mut active = false;
1036 // The dispatches received while resuming: Discord's replay (for `ShardResume`).
1037 let mut replayed = 0;
1038 // Whether this shard already counted towards `ClientReady`.
1039 let mut counted_ready = false;
1040 // A cluster process reports its shards' state and latency (D-310).
1041 #[cfg(feature = "sharding")]
1042 let mut reporter = crate::sharding::Reporter::new(self.shard_slot(shard.id().number()));
1043 loop {
1044 let event = tokio::select! {
1045 biased;
1046 changed = shutdown.changed() => {
1047 if changed.is_err() || *shutdown.borrow() {
1048 #[cfg(feature = "voice")]
1049 self.leave_calls(shard.id().number()).await;
1050 shard.close().await;
1051 return Ok(());
1052 }
1053 continue;
1054 }
1055 event = shard.next_event() => event,
1056 };
1057 let registry = self.registry();
1058 match event {
1059 Some(Ok(GatewayEvent::Dispatch(_, event))) => {
1060 if shard.state() == ShardState::Resuming {
1061 replayed += 1;
1062 }
1063 let resumed = matches!(event, DispatchEvent::Resumed);
1064 #[cfg(feature = "voice")]
1065 self.inner.voice.process(&event);
1066 convert(
1067 event,
1068 self.inner.cache.as_deref(),
1069 &mut tracker,
1070 |kind| self.wants(®istry, kind),
1071 &mut out,
1072 );
1073 if resumed {
1074 let replay = core::mem::take(&mut replayed);
1075 if self.wants(®istry, EventKind::ShardResume) {
1076 out.push(Dispatch::ShardResume(Arc::new(payload::ShardResume {
1077 replayed: replay,
1078 })));
1079 }
1080 }
1081 if let Some(seen) = tracker.take_ready() {
1082 self.on_ready(seen, &mut counted_ready, ®istry, &mut out);
1083 }
1084 }
1085 Some(Ok(GatewayEvent::InvalidSession(false))) => {
1086 if self.wants(®istry, EventKind::Invalidated) {
1087 out.push(Dispatch::Invalidated(Arc::new(payload::Invalidated)));
1088 }
1089 }
1090 #[cfg(feature = "sharding")]
1091 Some(Ok(GatewayEvent::HeartbeatAck)) => reporter.latency(shard.latency()),
1092 Some(Ok(_)) => {}
1093 Some(Err(error)) if error.is_fatal() => {
1094 if let ReceiveErrorKind::FatallyClosed { code } = error.kind() {
1095 let disconnect = Dispatch::ShardDisconnect(Arc::new(*code));
1096 self.emit(&ctx, ®istry, disconnect).await;
1097 }
1098 return Err(error.into());
1099 }
1100 Some(Err(error)) => {
1101 tracing::warn!(shard = %shard.id(), %error, "gateway error, recovering");
1102 if self.wants(®istry, EventKind::ShardError) {
1103 out.push(Dispatch::ShardError(Arc::new(error)));
1104 }
1105 }
1106 None => return Ok(()),
1107 }
1108 // A lost connection shows as the shard leaving `Active`; it reconnects by itself.
1109 let state = shard.state();
1110 if active
1111 && !matches!(
1112 state,
1113 ShardState::Active | ShardState::Closed | ShardState::FatallyClosed(_)
1114 )
1115 && self.wants(®istry, EventKind::ShardReconnecting)
1116 {
1117 out.push(Dispatch::ShardReconnecting(Arc::new(
1118 payload::ShardReconnecting,
1119 )));
1120 }
1121 active = state == ShardState::Active;
1122 #[cfg(feature = "sharding")]
1123 reporter.state(state);
1124 for dispatch in out.drain(..) {
1125 self.emit(&ctx, ®istry, dispatch).await;
1126 }
1127 }
1128 }
1129
1130 /// Works out the gateway URL, the shards to run and the identify concurrency, asking
1131 /// Discord unless both the URL and the shard count are configured.
1132 async fn plan(&self) -> Result<Plan, Error> {
1133 let inner = &*self.inner;
1134 // A cluster process gets everything from its manager (D-305).
1135 #[cfg(feature = "sharding")]
1136 if let Some(assignment) = &inner.cluster {
1137 return Ok(Plan {
1138 url: inner
1139 .gateway_url
1140 .as_deref()
1141 .unwrap_or(assignment.gateway_url())
1142 .to_owned(),
1143 range: assignment.shards(),
1144 total: assignment.total_shards(),
1145 max_concurrency: assignment.max_concurrency(),
1146 });
1147 }
1148 let fixed = match &inner.shards {
1149 Shards::Auto => None,
1150 Shards::Count(count) => Some((0..*count, *count)),
1151 Shards::Range { range, total } => Some((range.clone(), *total)),
1152 };
1153 if let (Some(url), Some((range, total))) = (&inner.gateway_url, fixed.clone()) {
1154 return Ok(Plan {
1155 url: url.to_string(),
1156 range,
1157 total,
1158 max_concurrency: 1,
1159 });
1160 }
1161
1162 let gateway = inner.rest.get_gateway_bot().await?;
1163 let (range, total) = fixed.unwrap_or_else(|| {
1164 let total = gateway.shards.max(1);
1165 (0..total, total)
1166 });
1167 let limit = &gateway.session_start_limit;
1168 let required = range.end - range.start;
1169 if limit.remaining < required {
1170 return Err(Error::SessionStartLimit {
1171 required,
1172 remaining: limit.remaining,
1173 reset_after: Duration::from_millis(limit.reset_after),
1174 });
1175 }
1176 let url = match &inner.gateway_url {
1177 Some(url) => url.to_string(),
1178 None => gateway.url.into(),
1179 };
1180 Ok(Plan {
1181 url,
1182 range,
1183 total,
1184 max_concurrency: limit.max_concurrency,
1185 })
1186 }
1187}
1188
1189impl<B: Backend> Client<B> {
1190 /// The current handlers (registration replaces the table, so this is a snapshot).
1191 fn registry(&self) -> Arc<Registry<B>> {
1192 Arc::clone(
1193 &self
1194 .inner
1195 .registry
1196 .read()
1197 .unwrap_or_else(PoisonError::into_inner),
1198 )
1199 }
1200
1201 /// Whether anyone listens to `kind`: a handler, or an event stream (which never receives
1202 /// [`Raw`](crate::event::Raw)).
1203 fn wants(&self, registry: &Registry<B>, kind: EventKind) -> bool {
1204 !registry.get(kind).is_empty()
1205 || (kind == EventKind::InteractionCreate && !registry.routes.is_empty())
1206 || self.inner.shared.collectors.wants(kind)
1207 || (kind != EventKind::Raw && self.inner.has_subscribers.load(Ordering::Acquire))
1208 }
1209
1210 /// Delivers one event to the event streams and to its handlers (D-028).
1211 async fn emit(&self, ctx: &Context<B>, registry: &Registry<B>, dispatch: Dispatch) {
1212 self.emit_as(ctx, registry, dispatch, self.inner.mode).await;
1213 }
1214
1215 /// [`emit`](Self::emit), with the handlers run as `mode` says.
1216 async fn emit_as(
1217 &self,
1218 ctx: &Context<B>,
1219 registry: &Registry<B>,
1220 dispatch: Dispatch,
1221 mode: HandlerMode,
1222 ) {
1223 let inner = &*self.inner;
1224 if !matches!(dispatch, Dispatch::Raw(_)) && inner.has_subscribers.load(Ordering::Acquire) {
1225 let mut subscribers = lock(&inner.subscribers);
1226 subscribers.retain(|subscriber| {
1227 subscriber
1228 .send(ShardEvent {
1229 shard: ctx.core().shard_id(),
1230 event: dispatch.clone(),
1231 })
1232 .is_ok()
1233 });
1234 inner
1235 .has_subscribers
1236 .store(!subscribers.is_empty(), Ordering::Release);
1237 }
1238
1239 let Some(kind) = dispatch.kind() else {
1240 return;
1241 };
1242 // The collectors watching the event's IDs (D-264); they do not take it from the
1243 // handlers (D-266).
1244 inner.shared.collectors.deliver(kind, &dispatch);
1245 let handlers = registry.get(kind);
1246 // The interaction routes run after the `InteractionCreate` handlers (D-255).
1247 let routed = match &dispatch {
1248 Dispatch::InteractionCreate(event) if !registry.routes.is_empty() => Some(event),
1249 _ => None,
1250 };
1251 match mode {
1252 HandlerMode::Concurrent => {
1253 for handler in handlers {
1254 handler.spawn(ctx, &dispatch);
1255 }
1256 if let Some(event) = routed {
1257 registry.routes.spawn(ctx, event);
1258 }
1259 }
1260 HandlerMode::Sequential => {
1261 for handler in handlers {
1262 if let Some(future) = handler.call(ctx, &dispatch) {
1263 future.await;
1264 }
1265 }
1266 if let Some(future) = routed.and_then(|event| registry.routes.call(ctx, event)) {
1267 future.await;
1268 }
1269 }
1270 }
1271 }
1272}
1273
1274#[cfg(feature = "http-interactions")]
1275impl<B: Backend> Client<B> {
1276 /// Returns an endpoint answering the interactions Discord posts to the app's
1277 /// Interactions Endpoint URL with this client's routes and handlers (D-398): see
1278 /// [`http_interactions`](crate::http_interactions). `public_key` is the app's public key
1279 /// from the Developer Portal (General Information), in hexadecimal.
1280 ///
1281 /// The client needs no [`login`](Self::login) for it; a client that is also logged in
1282 /// (a hybrid bot) gives HTTP interactions the context of their guild's shard (D-403).
1283 ///
1284 /// discord.js counterpart: none (discord.js only receives interactions over the gateway).
1285 ///
1286 /// # Errors
1287 ///
1288 /// Returns [`InvalidPublicKey`](crate::http_interactions::InvalidPublicKey) if
1289 /// `public_key` is not 64 hexadecimal digits of a valid Ed25519 key.
1290 pub fn interactions_endpoint(
1291 &self,
1292 public_key: &str,
1293 ) -> Result<
1294 crate::http_interactions::InteractionsEndpoint<B>,
1295 crate::http_interactions::InvalidPublicKey,
1296 > {
1297 crate::http_interactions::InteractionsEndpoint::new(self.clone(), public_key)
1298 }
1299
1300 /// Dispatches an HTTP interaction like a gateway one (D-398): the cache, the event
1301 /// streams and collectors, then the `InteractionCreate` handlers and the routes, one
1302 /// after another in the returned future (each request has its own). The receiver gets
1303 /// the initial response (D-399).
1304 pub(crate) fn dispatch_http(
1305 &self,
1306 event: djs_model::gateway::payload::InteractionCreate,
1307 ) -> (
1308 crate::http_interactions::InitialReceiver,
1309 BoxFuture<'static, ()>,
1310 ) {
1311 let inner = &*self.inner;
1312 let state = &inner.shared;
1313 // The application ID is known from the first interaction too (D-245).
1314 let _ = state.application_id.set(event.application_id);
1315 let (inline, initial) = crate::http_interactions::Inline::new(event.id);
1316 // The guild's shard, if this client also runs it (D-403); DMs go to shard 0.
1317 #[cfg(feature = "gateway")]
1318 let ctx = {
1319 let total = state.total_shards.load(Ordering::Acquire);
1320 let (shard, sender) = if total == 0 {
1321 (
1322 djs_model::gateway::ShardId::ONE,
1323 djs_gateway::MessageSender::detached(),
1324 )
1325 } else {
1326 let number = event.guild_id.map_or(0, |guild| {
1327 djs_model::gateway::ShardId::for_guild(guild, total).number()
1328 });
1329 let sender = state
1330 .shard(number)
1331 .unwrap_or_else(djs_gateway::MessageSender::detached);
1332 (djs_model::gateway::ShardId::new(number, total), sender)
1333 };
1334 let (rest, cache) = (inner.rest.clone(), inner.cache.clone());
1335 Context::http(rest, shard, sender, cache, Arc::clone(state), inline)
1336 };
1337 #[cfg(not(feature = "gateway"))]
1338 let ctx = Context::http(
1339 inner.rest.clone(),
1340 djs_model::gateway::ShardId::ONE,
1341 inner.cache.clone(),
1342 Arc::clone(state),
1343 inline,
1344 );
1345 let mut out = Vec::with_capacity(1);
1346 convert(
1347 DispatchEvent::InteractionCreate(Box::new(event)),
1348 inner.cache.as_deref(),
1349 &mut ShardTracker::default(),
1350 |kind| kind == EventKind::InteractionCreate,
1351 &mut out,
1352 );
1353 let client = self.clone();
1354 let registry = self.registry();
1355 let work = async move {
1356 for dispatch in out {
1357 client
1358 .emit_as(&ctx, ®istry, dispatch, HandlerMode::Sequential)
1359 .await;
1360 }
1361 };
1362 (initial, Box::pin(work))
1363 }
1364}
1365
1366#[cfg(feature = "gateway")]
1367/// Runs `sweep` every `period`, first after one `period`, logging what it swept as `resource`.
1368///
1369/// A zero period disables the sweep (it would run without pause); a period too long to
1370/// schedule never runs.
1371async fn every(period: Duration, resource: &'static str, sweep: impl Fn() -> usize) {
1372 if period.is_zero() {
1373 tracing::warn!(resource, "a cache sweep with a zero interval is disabled");
1374 return;
1375 }
1376 let Some(start) = Instant::now().checked_add(period) else {
1377 return;
1378 };
1379 let mut interval = tokio::time::interval_at(start, period);
1380 interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
1381 loop {
1382 interval.tick().await;
1383 let swept = sweep();
1384 tracing::debug!(resource, swept, "swept the cache");
1385 }
1386}
1387
1388#[cfg(feature = "gateway")]
1389/// What [`Client::login`] starts: the gateway URL, the shards and the identify concurrency.
1390struct Plan {
1391 url: String,
1392 range: Range<u32>,
1393 total: u32,
1394 max_concurrency: u32,
1395}
1396
1397/// Configures and builds a [`Client`]. Created by [`Client::builder`].
1398///
1399/// `B` is the cache backend (D-172), switched with [`cache_backend`](Self::cache_backend).
1400///
1401/// discord.js counterpart: `ClientOptions`.
1402#[derive(Debug)]
1403#[must_use = "a builder does nothing until `build` is called"]
1404pub struct ClientBuilder<B: Backend = DashMapBackend> {
1405 token: String,
1406 intents: Intents,
1407 rest: Option<Rest>,
1408 #[cfg(feature = "gateway")]
1409 compression: Compression,
1410 #[cfg(feature = "gateway")]
1411 gateway_url: Option<Box<str>>,
1412 #[cfg(feature = "gateway")]
1413 shards: Shards,
1414 #[cfg(feature = "gateway")]
1415 presence: Option<UpdatePresence>,
1416 mode: HandlerMode,
1417 cache: Option<CacheConfig>,
1418 backend: B,
1419 compiled: Compiled<B>,
1420 #[cfg(feature = "sharding")]
1421 cluster: Option<crate::sharding::ClusterAssignment>,
1422}
1423
1424impl<B: Backend> ClientBuilder<B> {
1425 /// Sets the gateway intents — the groups of events to receive (default: none).
1426 ///
1427 /// Only request what the bot needs. Privileged intents
1428 /// ([`Intents::PRIVILEGED`]) must be enabled in the Developer Portal first.
1429 ///
1430 /// discord.js counterpart: the `intents` option of `ClientOptions`.
1431 pub const fn intents(mut self, intents: Intents) -> Self {
1432 self.intents = intents;
1433 self
1434 }
1435
1436 /// Uses a preconfigured REST client (for example with a proxy or custom timeouts) instead
1437 /// of one built from the token.
1438 ///
1439 /// discord.js counterpart: the `rest` option of `ClientOptions`.
1440 pub fn rest(mut self, rest: Rest) -> Self {
1441 self.rest = Some(rest);
1442 self
1443 }
1444
1445 #[cfg(feature = "gateway")]
1446 #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
1447 /// Sets the gateway transport compression (default: `zstd-stream` when the feature is
1448 /// enabled).
1449 ///
1450 /// discord.js counterpart: the `ws.compression` option of `ClientOptions`.
1451 pub const fn compression(mut self, compression: Compression) -> Self {
1452 self.compression = compression;
1453 self
1454 }
1455
1456 #[cfg(feature = "gateway")]
1457 #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
1458 /// Connects to this gateway URL instead of the one from Get Gateway Bot (useful for
1459 /// proxies and tests).
1460 ///
1461 /// Get Gateway Bot is still called for [`Shards::Auto`]; with a fixed shard count too, the
1462 /// client does not call it at all and shards identify one at a time (`max_concurrency` 1).
1463 ///
1464 /// discord.js counterpart: none (discord.js always asks Get Gateway Bot).
1465 pub fn gateway_url(mut self, url: impl Into<String>) -> Self {
1466 self.gateway_url = Some(url.into().into_boxed_str());
1467 self
1468 }
1469
1470 #[cfg(feature = "gateway")]
1471 #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
1472 /// Sets which shards to run (default [`Shards::Auto`]: as many as Discord recommends).
1473 ///
1474 /// discord.js counterpart: the `shards` and `shardCount` options of `ClientOptions`.
1475 ///
1476 /// # Panics
1477 ///
1478 /// Panics on a shard count of `0`, or a range that is empty or reaches past `total`.
1479 ///
1480 /// # Examples
1481 ///
1482 /// ```
1483 /// use djs_rs::{Client, Shards};
1484 ///
1485 /// // Shards 0–7 of 16 run in this process; another process runs 8–15.
1486 /// let client = Client::builder("my-token")
1487 /// .shards(Shards::Range { range: 0..8, total: 16 })
1488 /// .build();
1489 /// ```
1490 #[track_caller]
1491 pub fn shards(mut self, shards: Shards) -> Self {
1492 match &shards {
1493 Shards::Auto => {}
1494 Shards::Count(count) => assert!(*count > 0, "the shard count must not be zero"),
1495 Shards::Range { range, total } => assert!(
1496 range.start < range.end && range.end <= *total,
1497 "shard range {range:?} must be non-empty and within the total of {total}"
1498 ),
1499 }
1500 self.shards = shards;
1501 self
1502 }
1503
1504 /// Makes this client the one of a cluster process started by a
1505 /// [`ClusterManager`](crate::sharding::ClusterManager) (D-300): it runs the assignment's
1506 /// shards ([`Shards::Range`]), connects to the manager when it logs in, and shuts down
1507 /// when the manager asks or goes away. Get the assignment from
1508 /// [`sharding::process`](crate::sharding::process).
1509 ///
1510 /// The client then does not call Get Gateway Bot: the gateway URL and `max_concurrency`
1511 /// come from the manager (D-305, a [`gateway_url`](Self::gateway_url) set here still
1512 /// wins), and its shards wait for their IDENTIFY turns from the manager (D-299).
1513 ///
1514 /// discord.js counterpart: what `new Client()` reads from the environment in a shard
1515 /// process (`client.shard`).
1516 #[cfg(feature = "sharding")]
1517 #[cfg_attr(docsrs, doc(cfg(feature = "sharding")))]
1518 pub fn cluster(mut self, assignment: crate::sharding::ClusterAssignment) -> Self {
1519 self.shards = Shards::Range {
1520 range: assignment.shards(),
1521 total: assignment.total_shards(),
1522 };
1523 self.cluster = Some(assignment);
1524 self
1525 }
1526
1527 #[cfg(feature = "gateway")]
1528 #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
1529 /// Sets the presence (status and activities) every shard starts with (default: none, the
1530 /// bot appears online without an activity). Change it later with [`Client::set_presence`].
1531 ///
1532 /// discord.js counterpart: the `presence` client option.
1533 ///
1534 /// # Examples
1535 ///
1536 /// ```
1537 /// use djs_rs::{
1538 /// Client,
1539 /// model::gateway::{Activity, Status, payload::UpdatePresence},
1540 /// };
1541 ///
1542 /// let client = Client::builder("my-token")
1543 /// .presence(UpdatePresence::new(Status::Online, [Activity::playing("with Rust")]))
1544 /// .build();
1545 /// ```
1546 pub fn presence(mut self, presence: UpdatePresence) -> Self {
1547 self.presence = Some(presence);
1548 self
1549 }
1550
1551 /// Sets how handlers are executed (default [`HandlerMode::Concurrent`]).
1552 ///
1553 /// discord.js counterpart: none (discord.js runs every listener as its event comes).
1554 pub const fn handler_mode(mut self, mode: HandlerMode) -> Self {
1555 self.mode = mode;
1556 self
1557 }
1558
1559 /// Gives the client a [`Cache`] configured by `config` (default: no cache, D-170).
1560 ///
1561 /// The client applies every event to the cache before running its handlers (D-171), and
1562 /// runs the periodic sweeps of [`CacheConfig::sweepers`] while it is logged in. Read it
1563 /// with [`Client::cache`] and [`Context::cache`]. What the cache can fill depends on the
1564 /// [intents](Self::intents): members need [`Intents::GUILD_MEMBERS`], presences
1565 /// [`Intents::GUILD_PRESENCES`], messages [`Intents::GUILD_MESSAGES`] or
1566 /// [`Intents::DIRECT_MESSAGES`], and so on.
1567 ///
1568 /// discord.js counterpart: the `makeCache` and `sweepers` client options. discord.js
1569 /// always caches; [`CacheConfig::discord_js`] caches what it caches by default.
1570 ///
1571 /// # Examples
1572 ///
1573 /// ```
1574 /// use djs_rs::{
1575 /// Client,
1576 /// cache::{CacheConfig, Limit, Resource},
1577 /// model::gateway::Intents,
1578 /// };
1579 ///
1580 /// let config = CacheConfig::builder()
1581 /// .members(Limit::Unlimited)
1582 /// .messages(Limit::Max(50))
1583 /// .build();
1584 /// let client = Client::builder("my-token")
1585 /// .intents(Intents::GUILDS | Intents::GUILD_MEMBERS | Intents::GUILD_MESSAGES)
1586 /// .cache(config)
1587 /// .build();
1588 /// let cache = client.cache().unwrap();
1589 /// assert!(cache.config().is_enabled(Resource::Member));
1590 /// assert!(!cache.config().is_enabled(Resource::Presence));
1591 /// ```
1592 pub fn cache(mut self, config: CacheConfig) -> Self {
1593 self.cache = Some(config);
1594 self
1595 }
1596
1597 /// Keeps the cache in stores created by `backend` instead of the default
1598 /// [`DashMapBackend`] (D-172), and enables the cache: with
1599 /// [`CacheConfig::default`] unless [`cache`](Self::cache) is called too (in any order).
1600 ///
1601 /// discord.js counterpart: the `makeCache` option of `ClientOptions`.
1602 ///
1603 /// # Examples
1604 ///
1605 /// ```
1606 /// use djs_rs::{Client, cache::DashMapBackend};
1607 ///
1608 /// // Any `djs_cache::Backend` works; this is the default one, named explicitly.
1609 /// let client: Client<DashMapBackend> = Client::builder("my-token")
1610 /// .cache_backend(DashMapBackend::new())
1611 /// .build();
1612 /// assert!(client.cache().is_some());
1613 /// ```
1614 pub fn cache_backend<C: Backend>(self, backend: C) -> ClientBuilder<C> {
1615 ClientBuilder {
1616 token: self.token,
1617 intents: self.intents,
1618 rest: self.rest,
1619 #[cfg(feature = "gateway")]
1620 compression: self.compression,
1621 #[cfg(feature = "gateway")]
1622 gateway_url: self.gateway_url,
1623 #[cfg(feature = "gateway")]
1624 shards: self.shards,
1625 #[cfg(feature = "gateway")]
1626 presence: self.presence,
1627 mode: self.mode,
1628 cache: Some(self.cache.unwrap_or_default()),
1629 backend,
1630 compiled: Compiled::generic(),
1631 #[cfg(feature = "sharding")]
1632 cluster: self.cluster,
1633 }
1634 }
1635
1636 /// Builds the client. It does not connect until [`Client::login`] is called.
1637 ///
1638 /// discord.js counterpart: `new Client(options)`.
1639 #[must_use]
1640 pub fn build(self) -> Client<B> {
1641 (self.compiled.build)(self)
1642 }
1643
1644 /// [`build`](Self::build)'s body, reached through [`Compiled`].
1645 fn build_inner(self) -> Client<B> {
1646 let compiled = self.compiled;
1647 // Without the `hyper` feature this panics unless a `Rest` with a transport was given (D-405).
1648 let rest = self
1649 .rest
1650 .unwrap_or_else(|| Rest::builder().token(self.token.clone()).build());
1651 let backend = self.backend;
1652 let cache = self
1653 .cache
1654 .map(|config| Arc::new(Cache::with_backend(config, backend)));
1655 let shared = Arc::new(Shared {
1656 sequential: self.mode == HandlerMode::Sequential,
1657 intents: self.intents,
1658 ..Shared::default()
1659 });
1660 // The real ID, or one that matches no voice state (`voice()` warns, D-345).
1661 #[cfg(feature = "voice")]
1662 let voice = crate::voice::VoiceManager::new(
1663 crate::voice::bot_id(&self.token).unwrap_or(crate::model::id::UserId::new(u64::MAX)),
1664 1,
1665 crate::voice::ClientGateway {
1666 shared: Arc::clone(&shared),
1667 },
1668 );
1669 Client {
1670 inner: Arc::new(Inner {
1671 token: self.token.into_boxed_str(),
1672 intents: self.intents,
1673 rest,
1674 #[cfg(feature = "gateway")]
1675 compression: self.compression,
1676 #[cfg(feature = "gateway")]
1677 gateway_url: self.gateway_url,
1678 #[cfg(feature = "gateway")]
1679 shards: self.shards,
1680 #[cfg(feature = "gateway")]
1681 presence: self.presence,
1682 mode: self.mode,
1683 cache,
1684 registry: RwLock::new(Arc::new(Registry::default())),
1685 subscribers: Mutex::new(Vec::new()),
1686 has_subscribers: AtomicBool::new(false),
1687 running: AtomicBool::new(false),
1688 shard_count: AtomicU32::new(0),
1689 ready_shards: AtomicU32::new(0),
1690 shared,
1691 compiled,
1692 #[cfg(feature = "sharding")]
1693 cluster: self.cluster,
1694 #[cfg(feature = "sharding")]
1695 commands: RwLock::default(),
1696 #[cfg(feature = "sharding")]
1697 shard_slots: RwLock::default(),
1698 #[cfg(feature = "voice")]
1699 voice,
1700 #[cfg(feature = "voice")]
1701 voice_checked: std::sync::Once::new(),
1702 }),
1703 }
1704 }
1705}
1706
1707/// A stream of every event a [`Client`] receives. Created by [`Client::events`].
1708///
1709/// Implements [`Stream`]; [`next`](Self::next) is provided so no extension trait is needed.
1710///
1711/// discord.js counterpart: none (discord.js delivers events to listeners only).
1712#[derive(Debug)]
1713pub struct EventStream {
1714 rx: mpsc::UnboundedReceiver<ShardEvent>,
1715}
1716
1717impl EventStream {
1718 /// Waits for the next event. Returns `None` once the client has been dropped.
1719 ///
1720 /// discord.js counterpart: none (discord.js delivers events to listeners only).
1721 pub async fn next(&mut self) -> Option<ShardEvent> {
1722 self.rx.recv().await
1723 }
1724}
1725
1726impl Stream for EventStream {
1727 type Item = ShardEvent;
1728
1729 fn poll_next(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<ShardEvent>> {
1730 self.rx.poll_recv(cx)
1731 }
1732}
1733
1734#[cfg(test)]
1735mod tests {
1736 use core::time::Duration;
1737 use std::{
1738 io,
1739 sync::{Arc, Mutex},
1740 };
1741
1742 use djs_model::gateway::Intents;
1743
1744 #[cfg(feature = "gateway")]
1745 use super::every;
1746 use super::warn_missing_intents;
1747 use crate::event::EventKind;
1748
1749 /// A log writer into a shared buffer.
1750 #[derive(Clone, Default)]
1751 struct Logs(Arc<Mutex<Vec<u8>>>);
1752
1753 impl io::Write for Logs {
1754 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1755 self.0.lock().unwrap().extend_from_slice(bytes);
1756 Ok(bytes.len())
1757 }
1758
1759 fn flush(&mut self) -> io::Result<()> {
1760 Ok(())
1761 }
1762 }
1763
1764 #[test]
1765 fn events_without_their_intents_are_warned_about() {
1766 let logs = Logs::default();
1767 let writer = logs.clone();
1768 let subscriber = tracing_subscriber::fmt()
1769 .with_writer(move || writer.clone())
1770 .with_ansi(false)
1771 .finish();
1772 tracing::subscriber::with_default(subscriber, || {
1773 warn_missing_intents(
1774 Intents::GUILDS | Intents::DIRECT_MESSAGES,
1775 [
1776 EventKind::MessageReactionAdd,
1777 EventKind::GuildCreate,
1778 EventKind::InteractionCreate,
1779 // One of its two intents is enough.
1780 EventKind::MessageCreate,
1781 EventKind::PresenceUpdate,
1782 ],
1783 );
1784 warn_missing_intents(Intents::GUILDS, [EventKind::GuildCreate]);
1785 });
1786 let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
1787 assert_eq!(logs.lines().count(), 1, "{logs}");
1788 assert!(logs.contains("messageReactionAdd"), "{logs}");
1789 assert!(logs.contains("presenceUpdate"), "{logs}");
1790 assert!(!logs.contains("guildCreate"), "{logs}");
1791 assert!(!logs.contains("messageCreate"), "{logs}");
1792 }
1793
1794 #[cfg(feature = "gateway")]
1795 #[tokio::test]
1796 async fn sweeps_that_cannot_be_scheduled_return_at_once() {
1797 for period in [Duration::ZERO, Duration::MAX] {
1798 let sweep = every(period, "test", || unreachable!("must not sweep"));
1799 tokio::time::timeout(Duration::from_secs(5), sweep)
1800 .await
1801 .unwrap();
1802 }
1803 }
1804}