Skip to main content

djs_rs/collector/
mod.rs

1//! Collectors: streams of the messages, reactions, component interactions and modal
2//! submissions that arrive while a bot waits for them (D-263–D-269).
3//!
4//! A collector watches one thing — the messages of a channel, the reactions or components of
5//! a message, the components of an interaction's reply, the modals a user submits — and
6//! yields what arrives there as a [`Stream`]: read it with `while let Some(item) =
7//! collector.next().await`. It is configured with a [`CollectorBuilder`]:
8//!
9//! - [`time`](CollectorBuilder::time): end after this long;
10//! - [`idle`](CollectorBuilder::idle): end when nothing was collected for this long;
11//! - [`max`](CollectorBuilder::max): end after collecting this many;
12//! - [`max_processed`](CollectorBuilder::max_processed): end after this many arrived, whether
13//!   the filter accepted them or not;
14//! - [`filter`](CollectorBuilder::filter): collect only what the filter accepts;
15//! - for reactions and components, `max_users`; for reactions, `max_emojis` and
16//!   `dispose` (also yield removals); for components, `component_type`.
17//!
18//! The collector also ends when what it watches is deleted (its message, channel, thread or
19//! guild), when [`Collector::stop`] is called, or when the client shuts down; afterwards
20//! [`Collector::end_reason`] tells why. The `await_*` shortcuts wait for one item
21//! ([`await_component`](crate::ext::MessageExt::await_component),
22//! [`await_modal_submit`](crate::ext::InteractionExt::await_modal_submit): a
23//! `Result<_, CollectorError>`) or collect until the end
24//! ([`await_messages`](crate::Context::await_messages),
25//! [`await_reactions`](crate::ext::MessageExt::await_reactions): a [`Collected`]).
26//!
27//! Collected events still reach the event handlers and the router's routes (D-266): a
28//! collector is one more listener, as in discord.js, so a bot must not answer the same
29//! interaction from a collector and from a route.
30//!
31//! # `Sequential` handlers
32//!
33//! With [`HandlerMode::Sequential`](crate::HandlerMode::Sequential), a handler that waits for
34//! a collector blocks its shard: the collector receives nothing from that shard until it
35//! ends by time (D-267). The client logs a warning when a collector is created in this mode;
36//! the default `Concurrent` mode has no such limit.
37//!
38//! # Examples
39//!
40//! ```no_run
41//! # use std::time::Duration;
42//! # use djs_rs::prelude::*;
43//! # let client = Client::builder("token").build();
44//! client.on(Events::MessageCreate, |ctx, msg| async move {
45//!     if msg.content != "!quiz" {
46//!         return Ok(());
47//!     }
48//!     msg.reply(&ctx, "What is 6 × 7? You have 30 seconds.").await?;
49//!     let author = msg.author.id;
50//!     let answers = ctx
51//!         .await_messages(msg.channel_id)
52//!         .filter(move |answer| answer.author.id == author)
53//!         .max(1)
54//!         .time(Duration::from_secs(30))
55//!         .await;
56//!     match answers.first() {
57//!         Some(answer) if answer.content.trim() == "42" => answer.reply(&ctx, "Correct!").await?,
58//!         Some(answer) => answer.reply(&ctx, "No, it is 42.").await?,
59//!         None => msg.reply(&ctx, "Time is up: it was 42.").await?,
60//!     };
61//!     Ok(())
62//! });
63//! ```
64//!
65//! discord.js counterpart: `Collector` and its subclasses `MessageCollector`,
66//! `ReactionCollector` and `InteractionCollector`.
67
68mod index;
69
70use core::{
71    fmt,
72    future::{Future, IntoFuture},
73    marker::PhantomData,
74    ops::{Deref, DerefMut},
75    pin::Pin,
76    task::{Context as TaskContext, Poll},
77    time::Duration,
78};
79use std::{
80    collections::{HashMap, HashSet},
81    sync::Arc,
82};
83
84use djs_cache::Backend;
85use djs_collection::Collection;
86use djs_model::{
87    component::ComponentType,
88    emoji::PartialEmoji,
89    gateway::Intents,
90    gateway::payload::{
91        MessageCreate, MessageReactionAdd, MessageReactionRemove, MessageReactionRemoveAll,
92    },
93    id::{ChannelId, GuildId, MessageId, UserId},
94};
95use futures_core::Stream;
96use tokio::{
97    sync::mpsc,
98    time::{Instant, Sleep},
99};
100
101pub(crate) use self::index::{
102    Collectors, Key, MemberReply, NONCE_PREFIX, Registration, Signal, Sink,
103};
104use crate::{
105    Context,
106    router::{ComponentInteraction, ModalInteraction},
107};
108
109/// Why a collector ended.
110///
111/// discord.js counterpart: the `reason` of the `end` event (`"time"`, `"limit"`, …).
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
113#[non_exhaustive]
114pub enum EndReason {
115    /// The [`time`](CollectorBuilder::time) elapsed (discord.js: `"time"`).
116    Time,
117    /// Nothing was collected for the [`idle`](CollectorBuilder::idle) time (`"idle"`).
118    Idle,
119    /// [`max`](CollectorBuilder::max) items were collected (`"limit"`).
120    Limit,
121    /// [`max_processed`](CollectorBuilder::max_processed) items arrived (`"processedLimit"`).
122    ProcessedLimit,
123    /// `max_users` different users were collected (`"userLimit"`).
124    UserLimit,
125    /// `max_emojis` different emojis were collected (`"emojiLimit"`).
126    EmojiLimit,
127    /// The watched message was deleted (`"messageDelete"`).
128    MessageDelete,
129    /// The channel was deleted (`"channelDelete"`).
130    ChannelDelete,
131    /// The thread was deleted (`"threadDelete"`).
132    ThreadDelete,
133    /// The guild was deleted, or the bot left it (`"guildDelete"`).
134    GuildDelete,
135    /// [`Collector::stop`] was called (discord.js: `"user"`, the default reason of `stop`).
136    Stopped,
137    /// The client shut down.
138    Shutdown,
139}
140
141impl EndReason {
142    /// A short description, as in the error message of [`CollectorError`].
143    ///
144    /// discord.js counterpart: the `reason` string a collector's `end` event passes.
145    #[must_use]
146    pub const fn as_str(self) -> &'static str {
147        match self {
148            Self::Time => "the time elapsed",
149            Self::Idle => "nothing was collected for the idle time",
150            Self::Limit => "the limit was reached",
151            Self::ProcessedLimit => "the processed limit was reached",
152            Self::UserLimit => "the user limit was reached",
153            Self::EmojiLimit => "the emoji limit was reached",
154            Self::MessageDelete => "the message was deleted",
155            Self::ChannelDelete => "the channel was deleted",
156            Self::ThreadDelete => "the thread was deleted",
157            Self::GuildDelete => "the guild was deleted",
158            Self::Stopped => "the collector was stopped",
159            Self::Shutdown => "the client shut down",
160        }
161    }
162}
163
164impl fmt::Display for EndReason {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.write_str(self.as_str())
167    }
168}
169
170/// The error of the shortcuts that wait for one item
171/// ([`await_component`](crate::ext::MessageExt::await_component),
172/// [`await_modal_submit`](crate::ext::InteractionExt::await_modal_submit)): the collector
173/// ended before anything was collected (D-268).
174///
175/// discord.js counterpart: the `InteractionCollectorError` rejection.
176#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
177pub struct CollectorError {
178    reason: EndReason,
179}
180
181impl CollectorError {
182    /// Why the collector ended.
183    ///
184    /// discord.js counterpart: the `reason` of the error `awaitMessageComponent` rejects with.
185    #[must_use]
186    pub const fn reason(self) -> EndReason {
187        self.reason
188    }
189}
190
191impl fmt::Display for CollectorError {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        write!(f, "nothing was collected: {}", self.reason)
194    }
195}
196
197impl std::error::Error for CollectorError {}
198
199/// What a [reaction collector](crate::ext::MessageExt::reaction_collector) yields.
200///
201/// Removals are only yielded with [`dispose`](CollectorBuilder::dispose), and only for
202/// reactions the collector collected.
203///
204/// discord.js counterpart: the `collect`, `remove` and `dispose` events of
205/// `ReactionCollector`.
206#[derive(Clone, Debug, PartialEq)]
207#[non_exhaustive]
208pub enum ReactionEvent {
209    /// A user added a reaction (discord.js: `collect`).
210    Added(Arc<MessageReactionAdd>),
211    /// A user removed a collected reaction (discord.js: `remove`).
212    Removed(Arc<MessageReactionRemove>),
213    /// All the reactions of the message were removed (discord.js: the collection is
214    /// emptied); the collector's counts start again from zero.
215    RemovedAll(Arc<MessageReactionRemoveAll>),
216}
217
218impl ReactionEvent {
219    /// The reacting user, unless every reaction was removed.
220    ///
221    /// discord.js counterpart: the `user` a `ReactionCollector`'s `collect` and `remove` events pass.
222    #[must_use]
223    pub fn user_id(&self) -> Option<UserId> {
224        match self {
225            Self::Added(reaction) => Some(reaction.user_id),
226            Self::Removed(reaction) => Some(reaction.user_id),
227            Self::RemovedAll(_) => None,
228        }
229    }
230
231    /// The emoji, unless every reaction was removed.
232    ///
233    /// discord.js counterpart: the `reaction.emoji` a `ReactionCollector`'s events pass.
234    #[must_use]
235    pub fn emoji(&self) -> Option<&PartialEmoji> {
236        match self {
237            Self::Added(reaction) => Some(&reaction.emoji),
238            Self::Removed(reaction) => Some(&reaction.emoji),
239            Self::RemovedAll(_) => None,
240        }
241    }
242}
243
244/// One emoji's reactions gathered by [`await_reactions`](crate::ext::MessageExt::await_reactions).
245///
246/// discord.js counterpart: the `MessageReaction` values of `awaitReactions`.
247#[derive(Clone, Debug, PartialEq, Eq)]
248#[non_exhaustive]
249pub struct CollectedReaction {
250    /// The emoji.
251    pub emoji: PartialEmoji,
252    /// The users who reacted with it, in order.
253    pub users: Vec<UserId>,
254}
255
256impl CollectedReaction {
257    /// The number of users who reacted with the emoji.
258    ///
259    /// discord.js counterpart: `MessageReaction#count`.
260    #[must_use]
261    pub fn count(&self) -> usize {
262        self.users.len()
263    }
264}
265
266/// The key of an emoji in [`await_reactions`](crate::ext::MessageExt::await_reactions)' result:
267/// a custom emoji's ID, or a Unicode emoji itself (`"👍"`), like discord.js' reaction keys.
268#[must_use]
269pub fn reaction_key(emoji: &PartialEmoji) -> String {
270    match emoji {
271        PartialEmoji::Custom { id, .. } => id.to_string(),
272        PartialEmoji::Unicode { name } => name.to_string(),
273    }
274}
275
276/// What the collecting shortcuts return (D-268): the [`Collection`] of what was collected
277/// (through `Deref`) and why the collector ended. An empty result is not an error.
278///
279/// discord.js counterpart: the `Collection` of `awaitMessages` / `awaitReactions`.
280#[derive(Clone, Debug)]
281pub struct Collected<K, V> {
282    collection: Collection<K, V>,
283    reason: EndReason,
284}
285
286impl<K, V> Collected<K, V> {
287    /// Why the collector ended.
288    ///
289    /// discord.js counterpart: the `reason` of a collector's `end` event.
290    #[must_use]
291    pub const fn reason(&self) -> EndReason {
292        self.reason
293    }
294
295    /// Returns the collection.
296    ///
297    /// discord.js counterpart: the `Collection` `awaitMessages` and `awaitReactions` resolve to.
298    #[must_use]
299    pub fn into_collection(self) -> Collection<K, V> {
300        self.collection
301    }
302}
303
304impl<K, V> Deref for Collected<K, V> {
305    type Target = Collection<K, V>;
306
307    fn deref(&self) -> &Collection<K, V> {
308        &self.collection
309    }
310}
311
312impl<K, V> DerefMut for Collected<K, V> {
313    fn deref_mut(&mut self) -> &mut Collection<K, V> {
314        &mut self.collection
315    }
316}
317
318/// The kinds of builders: what a [`CollectorBuilder`] makes.
319pub mod mode {
320    /// [`build`](super::CollectorBuilder::build) makes a [`Collector`](super::Collector).
321    ///
322    /// discord.js counterpart: none (a state of `CollectorBuilder`).
323    #[derive(Debug)]
324    pub struct Stream;
325
326    /// Awaiting the builder waits for the first collected item.
327    ///
328    /// discord.js counterpart: none (a state of `CollectorBuilder`).
329    #[derive(Debug)]
330    pub struct First;
331
332    /// Awaiting the builder collects until the collector ends.
333    ///
334    /// discord.js counterpart: none (a state of `CollectorBuilder`).
335    #[derive(Debug)]
336    pub struct All;
337}
338
339/// What collectors can yield: [`ComponentInteraction`], [`ModalInteraction`],
340/// `Arc<MessageCreate>` and [`ReactionEvent`]. This trait is sealed.
341///
342/// discord.js counterpart: none (what a collector can collect).
343pub trait Collectable: sealed::Item {}
344
345impl Collectable for ComponentInteraction {}
346impl Collectable for ModalInteraction {}
347impl Collectable for Arc<MessageCreate> {}
348impl Collectable for ReactionEvent {}
349
350mod sealed {
351    use super::{
352        Arc, ComponentInteraction, ComponentType, MessageCreate, ModalInteraction, PartialEmoji,
353        ReactionEvent, UserId,
354    };
355    use crate::collector::{Sink, index::Tx};
356
357    /// What an item does to its collector.
358    #[derive(Debug)]
359    pub enum Action<'a> {
360        /// Collect it, if the filter accepts it.
361        Collect {
362            user: Option<UserId>,
363            emoji: Option<&'a PartialEmoji>,
364            component: Option<ComponentType>,
365        },
366        /// A collected reaction was removed.
367        Remove {
368            user: UserId,
369            emoji: &'a PartialEmoji,
370        },
371        /// Every reaction was removed.
372        Clear,
373    }
374
375    pub trait Item: Sized + Send + 'static {
376        /// The index entry sending these items.
377        fn sink(tx: Tx<Self>) -> Sink;
378
379        fn action(&self) -> Action<'_>;
380    }
381
382    impl Item for ComponentInteraction {
383        fn sink(tx: Tx<Self>) -> Sink {
384            Sink::Components(tx)
385        }
386
387        fn action(&self) -> Action<'_> {
388            Action::Collect {
389                user: self.interaction().author().map(|user| user.id),
390                emoji: None,
391                component: Some(self.component_type),
392            }
393        }
394    }
395
396    impl Item for ModalInteraction {
397        fn sink(tx: Tx<Self>) -> Sink {
398            Sink::Modals(tx)
399        }
400
401        fn action(&self) -> Action<'_> {
402            Action::Collect {
403                user: self.interaction().author().map(|user| user.id),
404                emoji: None,
405                component: None,
406            }
407        }
408    }
409
410    impl Item for Arc<MessageCreate> {
411        fn sink(tx: Tx<Self>) -> Sink {
412            Sink::Messages(tx)
413        }
414
415        fn action(&self) -> Action<'_> {
416            Action::Collect {
417                user: Some(self.author.id),
418                emoji: None,
419                component: None,
420            }
421        }
422    }
423
424    impl Item for ReactionEvent {
425        fn sink(tx: Tx<Self>) -> Sink {
426            Sink::Reactions(tx)
427        }
428
429        fn action(&self) -> Action<'_> {
430            match self {
431                Self::Added(reaction) => Action::Collect {
432                    user: Some(reaction.user_id),
433                    emoji: Some(&reaction.emoji),
434                    component: None,
435                },
436                Self::Removed(reaction) => Action::Remove {
437                    user: reaction.user_id,
438                    emoji: &reaction.emoji,
439                },
440                Self::RemovedAll(_) => Action::Clear,
441            }
442        }
443    }
444}
445
446use sealed::Action;
447
448type Filter<T> = Box<dyn FnMut(&T) -> bool + Send>;
449
450/// A collector's settings.
451struct Options<T> {
452    time: Option<Duration>,
453    idle: Option<Duration>,
454    max: Option<usize>,
455    max_processed: Option<usize>,
456    max_users: Option<usize>,
457    max_emojis: Option<usize>,
458    dispose: bool,
459    component_type: Option<ComponentType>,
460    filter: Option<Filter<T>>,
461}
462
463impl<T> Default for Options<T> {
464    fn default() -> Self {
465        Self {
466            time: None,
467            idle: None,
468            max: None,
469            max_processed: None,
470            max_users: None,
471            max_emojis: None,
472            dispose: false,
473            component_type: None,
474            filter: None,
475        }
476    }
477}
478
479impl<T> fmt::Debug for Options<T> {
480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481        f.debug_struct("Options")
482            .field("time", &self.time)
483            .field("idle", &self.idle)
484            .field("max", &self.max)
485            .field("max_processed", &self.max_processed)
486            .field("max_users", &self.max_users)
487            .field("max_emojis", &self.max_emojis)
488            .field("dispose", &self.dispose)
489            .field("component_type", &self.component_type)
490            .field("filter", &self.filter.is_some())
491            .finish()
492    }
493}
494
495/// Configures a collector; made by the extension methods (`component_collector`,
496/// `await_messages`, …) and the [`Context`] methods taking IDs.
497///
498/// `T` is what the collector yields; `M` is what the builder makes
499/// ([`mode::Stream`]: [`build`](Self::build) a [`Collector`]; [`mode::First`] and
500/// [`mode::All`]: `.await` the builder). The collector is registered when it is built or
501/// awaited, not before.
502///
503/// discord.js counterpart: the collector options (`CollectorOptions`,
504/// `MessageCollectorOptions`, `ReactionCollectorOptions`, `InteractionCollectorOptions`).
505#[must_use = "a collector builder collects nothing until it is built or awaited"]
506pub struct CollectorBuilder<T: Collectable, M = mode::Stream> {
507    collectors: Arc<Collectors>,
508    sequential: bool,
509    intents: Intents,
510    key: Key,
511    guild: Option<GuildId>,
512    channel: Option<ChannelId>,
513    options: Options<T>,
514    mode: PhantomData<fn() -> M>,
515}
516
517impl<T: Collectable, M> fmt::Debug for CollectorBuilder<T, M> {
518    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
519        f.debug_struct("CollectorBuilder")
520            .field("key", &self.key)
521            .field("options", &self.options)
522            .finish_non_exhaustive()
523    }
524}
525
526impl<T: Collectable, M> CollectorBuilder<T, M> {
527    pub(crate) fn new<B: Backend>(
528        ctx: &Context<B>,
529        key: Key,
530        guild: Option<GuildId>,
531        channel: Option<ChannelId>,
532    ) -> Self {
533        Self {
534            collectors: Arc::clone(ctx.collectors()),
535            sequential: ctx.is_sequential(),
536            intents: ctx.intents(),
537            key,
538            guild,
539            channel,
540            options: Options::default(),
541            mode: PhantomData,
542        }
543    }
544
545    /// Ends the collector after `time` (discord.js: `time`).
546    pub const fn time(mut self, time: Duration) -> Self {
547        self.options.time = Some(time);
548        self
549    }
550
551    /// Ends the collector when nothing was collected for `idle` (discord.js: `idle`).
552    pub const fn idle(mut self, idle: Duration) -> Self {
553        self.options.idle = Some(idle);
554        self
555    }
556
557    /// Ends the collector after collecting `max` items (discord.js: `max`). For reactions
558    /// with [`dispose`](Self::dispose), a removal gives its place back, as in discord.js.
559    pub const fn max(mut self, max: usize) -> Self {
560        self.options.max = Some(max);
561        self
562    }
563
564    /// Ends the collector after `max` items arrived, whether the
565    /// [`filter`](Self::filter) accepted them or not (discord.js: `maxProcessed`).
566    pub const fn max_processed(mut self, max: usize) -> Self {
567        self.options.max_processed = Some(max);
568        self
569    }
570
571    /// Collects only the items `filter` accepts (discord.js: `filter`). Rejected items still
572    /// count for [`max_processed`](Self::max_processed). The filter runs where the collector
573    /// is polled, never on the shard.
574    pub fn filter(mut self, filter: impl FnMut(&T) -> bool + Send + 'static) -> Self {
575        self.options.filter = Some(Box::new(filter));
576        self
577    }
578
579    /// Registers the collector and starts its timers.
580    fn start(self) -> Collector<T> {
581        if self.sequential {
582            tracing::warn!(
583                "a collector was created in the Sequential handler mode: a handler waiting for \
584                 it blocks its shard, so it receives nothing from that shard (D-267)"
585            );
586        }
587        let (tx, rx) = mpsc::unbounded_channel();
588        let sink = T::sink(tx);
589        // The event it collects (the first of its kinds) needs one of its intents (D-271).
590        crate::client::warn_missing_intents(self.intents, sink.kinds().first().copied());
591        let registration = self
592            .collectors
593            .register(self.key, self.guild, self.channel, sink);
594        let now = Instant::now();
595        let timer = |duration: Option<Duration>| {
596            duration
597                .and_then(|duration| now.checked_add(duration))
598                .map(|deadline| Box::pin(tokio::time::sleep_until(deadline)))
599        };
600        Collector {
601            time: timer(self.options.time),
602            idle: timer(self.options.idle),
603            rx,
604            registration: Some(registration),
605            tally: Tally::new(&self.options),
606            options: self.options,
607            end: None,
608        }
609    }
610}
611
612impl<M> CollectorBuilder<ComponentInteraction, M> {
613    /// Collects only components of this type (discord.js: `componentType`); others are
614    /// ignored, not even processed.
615    pub const fn component_type(mut self, kind: ComponentType) -> Self {
616        self.options.component_type = Some(kind);
617        self
618    }
619
620    /// Ends the collector when `max` different users were collected (discord.js:
621    /// `maxUsers`).
622    pub const fn max_users(mut self, max: usize) -> Self {
623        self.options.max_users = Some(max);
624        self
625    }
626}
627
628impl<M> CollectorBuilder<ReactionEvent, M> {
629    /// Also yields the removal of collected reactions ([`ReactionEvent::Removed`],
630    /// [`ReactionEvent::RemovedAll`]; discord.js: `dispose`).
631    pub const fn dispose(mut self, dispose: bool) -> Self {
632        self.options.dispose = dispose;
633        self
634    }
635
636    /// Ends the collector when `max` different users were collected (discord.js:
637    /// `maxUsers`).
638    pub const fn max_users(mut self, max: usize) -> Self {
639        self.options.max_users = Some(max);
640        self
641    }
642
643    /// Ends the collector when `max` different emojis were collected (discord.js:
644    /// `maxEmojis`).
645    pub const fn max_emojis(mut self, max: usize) -> Self {
646        self.options.max_emojis = Some(max);
647        self
648    }
649}
650
651impl<T: Collectable> CollectorBuilder<T, mode::Stream> {
652    /// Registers the collector: it collects from now until it ends.
653    ///
654    /// discord.js counterpart: `createMessageCollector`, `createReactionCollector`,
655    /// `createMessageComponentCollector`.
656    pub fn build(self) -> Collector<T> {
657        self.start()
658    }
659}
660
661impl<T: Collectable> IntoFuture for CollectorBuilder<T, mode::First> {
662    type Output = Result<T, CollectorError>;
663    type IntoFuture = AwaitFirst<T>;
664
665    fn into_future(mut self) -> AwaitFirst<T> {
666        self.options.max = Some(1);
667        AwaitFirst {
668            collector: self.start(),
669        }
670    }
671}
672
673macro_rules! await_all {
674    ($item:ty => Collected<$key:ty, $value:ty>, $gather:expr) => {
675        impl IntoFuture for CollectorBuilder<$item, mode::All> {
676            type Output = Collected<$key, $value>;
677            type IntoFuture = AwaitAll<$item, $key, $value>;
678
679            fn into_future(self) -> Self::IntoFuture {
680                AwaitAll {
681                    collector: self.start(),
682                    collection: Some(Collection::new()),
683                    gather: $gather,
684                }
685            }
686        }
687    };
688}
689
690await_all!(
691    Arc<MessageCreate> => Collected<MessageId, Arc<MessageCreate>>,
692    |collection, message| {
693        collection.insert(message.id, message);
694    }
695);
696
697await_all!(
698    ReactionEvent => Collected<String, CollectedReaction>,
699    gather_reaction
700);
701
702/// Adds a reaction event to the reactions gathered by `await_reactions`.
703fn gather_reaction(collection: &mut Collection<String, CollectedReaction>, event: ReactionEvent) {
704    match event {
705        ReactionEvent::Added(reaction) => {
706            collection
707                .as_index_map_mut()
708                .entry(reaction_key(&reaction.emoji))
709                .or_insert_with(|| CollectedReaction {
710                    emoji: reaction.emoji.clone(),
711                    users: Vec::new(),
712                })
713                .users
714                .push(reaction.user_id);
715        }
716        ReactionEvent::Removed(reaction) => {
717            let key = reaction_key(&reaction.emoji);
718            if let Some(gathered) = collection.as_index_map_mut().get_mut(&key) {
719                gathered.users.retain(|&user| user != reaction.user_id);
720                if gathered.users.is_empty() {
721                    collection.as_index_map_mut().shift_remove(&key);
722                }
723            }
724        }
725        ReactionEvent::RemovedAll(_) => collection.clear(),
726    }
727}
728
729/// The counts behind a collector's limits.
730#[derive(Debug)]
731struct Tally {
732    collected: usize,
733    processed: usize,
734    /// Collected items per user (with `max_users`, or reactions with `dispose`).
735    users: Option<HashMap<UserId, usize>>,
736    /// Collected reactions per emoji (with `max_emojis`, or `dispose`).
737    emojis: Option<HashMap<String, usize>>,
738    /// The collected reactions (with `dispose`): a removal of another one is not yielded.
739    pairs: Option<HashSet<(UserId, String)>>,
740}
741
742impl Tally {
743    fn new<T>(options: &Options<T>) -> Self {
744        Self {
745            collected: 0,
746            processed: 0,
747            users: (options.max_users.is_some() || options.dispose).then(HashMap::new),
748            emojis: (options.max_emojis.is_some() || options.dispose).then(HashMap::new),
749            pairs: options.dispose.then(HashSet::new),
750        }
751    }
752
753    fn collect(&mut self, user: Option<UserId>, emoji: Option<&PartialEmoji>) {
754        self.collected += 1;
755        if let (Some(users), Some(user)) = (&mut self.users, user) {
756            *users.entry(user).or_default() += 1;
757        }
758        if let (Some(emojis), Some(emoji)) = (&mut self.emojis, emoji) {
759            *emojis.entry(reaction_key(emoji)).or_default() += 1;
760        }
761        if let (Some(pairs), Some(user), Some(emoji)) = (&mut self.pairs, user, emoji) {
762            pairs.insert((user, reaction_key(emoji)));
763        }
764    }
765
766    /// Takes a removed reaction out of the counts; `false` if it was not collected.
767    fn remove(&mut self, user: UserId, emoji: &PartialEmoji) -> bool {
768        let key = reaction_key(emoji);
769        let Some(pairs) = &mut self.pairs else {
770            return false;
771        };
772        let Some((_, key)) = pairs.take(&(user, key)) else {
773            return false;
774        };
775        self.collected = self.collected.saturating_sub(1);
776        if let Some(users) = &mut self.users {
777            decrement(users, &user);
778        }
779        if let Some(emojis) = &mut self.emojis {
780            decrement(emojis, &key);
781        }
782        true
783    }
784
785    fn clear(&mut self) {
786        self.collected = 0;
787        if let Some(users) = &mut self.users {
788            users.clear();
789        }
790        if let Some(emojis) = &mut self.emojis {
791            emojis.clear();
792        }
793        if let Some(pairs) = &mut self.pairs {
794            pairs.clear();
795        }
796    }
797
798    /// The limit this tally reached, if any (in discord.js' order).
799    fn limit<T>(&self, options: &Options<T>) -> Option<EndReason> {
800        let reached = |max: Option<usize>, count: usize| max.is_some_and(|max| count >= max);
801        if reached(options.max, self.collected) {
802            Some(EndReason::Limit)
803        } else if reached(options.max_processed, self.processed) {
804            Some(EndReason::ProcessedLimit)
805        } else if reached(
806            options.max_emojis,
807            self.emojis.as_ref().map_or(0, HashMap::len),
808        ) {
809            Some(EndReason::EmojiLimit)
810        } else if reached(
811            options.max_users,
812            self.users.as_ref().map_or(0, HashMap::len),
813        ) {
814            Some(EndReason::UserLimit)
815        } else {
816            None
817        }
818    }
819}
820
821fn decrement<K: core::hash::Hash + Eq>(counts: &mut HashMap<K, usize>, key: &K) {
822    if let Some(count) = counts.get_mut(key) {
823        *count -= 1;
824        if *count == 0 {
825            counts.remove(key);
826        }
827    }
828}
829
830/// A running collector: a [`Stream`] of what it collects, ending (`None`) when the collector
831/// ends; [`end_reason`](Self::end_reason) then tells why.
832///
833/// Dropping the collector unregisters it. What arrives while it is not polled waits in its
834/// queue; a collector kept but never polled keeps collecting until it ends.
835///
836/// discord.js counterpart: `MessageCollector`, `ReactionCollector`, `InteractionCollector`
837/// (the `collect` event and the `end` event's reason).
838#[must_use = "a collector collects nothing unless it is polled"]
839pub struct Collector<T: Collectable> {
840    rx: mpsc::UnboundedReceiver<Signal<T>>,
841    registration: Option<Registration>,
842    options: Options<T>,
843    tally: Tally,
844    time: Option<Pin<Box<Sleep>>>,
845    idle: Option<Pin<Box<Sleep>>>,
846    end: Option<EndReason>,
847}
848
849impl<T: Collectable> fmt::Debug for Collector<T> {
850    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851        f.debug_struct("Collector")
852            .field("options", &self.options)
853            .field("collected", &self.tally.collected)
854            .field("processed", &self.tally.processed)
855            .field("end", &self.end)
856            .finish_non_exhaustive()
857    }
858}
859
860impl<T: Collectable> Collector<T> {
861    /// Waits for the next collected item; `None` once the collector ended.
862    ///
863    /// discord.js counterpart: the `collect` event of `Collector`.
864    pub async fn next(&mut self) -> Option<T> {
865        core::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
866    }
867
868    /// Ends the collector now (discord.js: `Collector#stop`); its reason is
869    /// [`EndReason::Stopped`]. Items that arrived but were not read are dropped.
870    pub fn stop(&mut self) {
871        self.finish(EndReason::Stopped);
872    }
873
874    /// Restarts the timers: `time` and `idle` count again from now, with new durations where
875    /// given (discord.js: `Collector#resetTimer`). Does nothing once the collector ended.
876    pub fn reset_timer(&mut self, time: Option<Duration>, idle: Option<Duration>) {
877        if self.end.is_some() {
878            return;
879        }
880        if time.is_some() {
881            self.options.time = time;
882        }
883        if idle.is_some() {
884            self.options.idle = idle;
885        }
886        let now = Instant::now();
887        let restart = |timer: &mut Option<Pin<Box<Sleep>>>, duration: Option<Duration>| {
888            *timer = duration
889                .and_then(|duration| now.checked_add(duration))
890                .map(|deadline| Box::pin(tokio::time::sleep_until(deadline)));
891        };
892        restart(&mut self.time, self.options.time);
893        restart(&mut self.idle, self.options.idle);
894    }
895
896    /// Why the collector ended, or `None` while it runs (discord.js: `endReason`).
897    #[must_use]
898    pub const fn end_reason(&self) -> Option<EndReason> {
899        self.end
900    }
901
902    /// Whether the collector ended (discord.js: `ended`).
903    #[must_use]
904    pub const fn is_ended(&self) -> bool {
905        self.end.is_some()
906    }
907
908    /// The number of items collected so far (for reactions with `dispose`, without the
909    /// removed ones).
910    ///
911    /// discord.js counterpart: `Collector#collected` (its `size`).
912    #[must_use]
913    pub const fn collected(&self) -> usize {
914        self.tally.collected
915    }
916
917    /// The number of items that arrived so far, whether the filter accepted them or not.
918    ///
919    /// discord.js counterpart: none (discord.js counts only the collected items).
920    #[must_use]
921    pub const fn processed(&self) -> usize {
922        self.tally.processed
923    }
924
925    /// Ends the collector: unregisters it and stops its timers.
926    fn finish(&mut self, reason: EndReason) {
927        if self.end.is_none() {
928            self.end = Some(reason);
929            self.registration = None;
930            self.time = None;
931            self.idle = None;
932            self.rx.close();
933        }
934    }
935
936    /// Runs one arrived item through the type, the filter and the limits; returns it if it
937    /// is collected (or a yielded removal).
938    fn process(&mut self, item: T) -> Option<T> {
939        let accepted = match item.action() {
940            Action::Collect {
941                user,
942                emoji,
943                component,
944            } => {
945                if self
946                    .options
947                    .component_type
948                    .is_some_and(|wanted| component != Some(wanted))
949                {
950                    return None;
951                }
952                self.tally.processed += 1;
953                let accepted = self
954                    .options
955                    .filter
956                    .as_mut()
957                    .is_none_or(|filter| filter(&item));
958                if accepted {
959                    self.tally.collect(user, emoji);
960                    if let (Some(idle), Some(timer)) = (self.options.idle, &mut self.idle)
961                        && let Some(deadline) = Instant::now().checked_add(idle)
962                    {
963                        timer.as_mut().reset(deadline);
964                    }
965                }
966                accepted
967            }
968            Action::Remove { user, emoji } => {
969                self.options.dispose && self.tally.remove(user, emoji)
970            }
971            Action::Clear => {
972                self.tally.clear();
973                self.options.dispose
974            }
975        };
976        if let Some(reason) = self.tally.limit(&self.options) {
977            // The item that reached the limit is still yielded; the next poll ends.
978            self.finish(reason);
979        }
980        accepted.then_some(item)
981    }
982}
983
984impl<T: Collectable> Stream for Collector<T> {
985    type Item = T;
986
987    fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<T>> {
988        let this = self.get_mut();
989        loop {
990            if this.end.is_some() {
991                return Poll::Ready(None);
992            }
993            if this
994                .time
995                .as_mut()
996                .is_some_and(|timer| timer.as_mut().poll(cx).is_ready())
997            {
998                this.finish(EndReason::Time);
999                continue;
1000            }
1001            if this
1002                .idle
1003                .as_mut()
1004                .is_some_and(|timer| timer.as_mut().poll(cx).is_ready())
1005            {
1006                this.finish(EndReason::Idle);
1007                continue;
1008            }
1009            match this.rx.poll_recv(cx) {
1010                Poll::Pending => return Poll::Pending,
1011                Poll::Ready(Some(Signal::Item(item))) => {
1012                    if let Some(item) = this.process(item) {
1013                        return Poll::Ready(Some(item));
1014                    }
1015                }
1016                Poll::Ready(Some(Signal::End(reason))) => this.finish(reason),
1017                Poll::Ready(None) => this.finish(EndReason::Shutdown),
1018            }
1019        }
1020    }
1021}
1022
1023/// The future of a shortcut waiting for one item (`await_component`, `await_modal_submit`).
1024///
1025/// discord.js counterpart: the promise of `awaitMessageComponent` and `awaitModalSubmit`.
1026#[must_use = "futures do nothing unless polled"]
1027#[derive(Debug)]
1028pub struct AwaitFirst<T: Collectable> {
1029    collector: Collector<T>,
1030}
1031
1032impl<T: Collectable> Future for AwaitFirst<T> {
1033    type Output = Result<T, CollectorError>;
1034
1035    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
1036        let collector = &mut self.get_mut().collector;
1037        match Pin::new(&mut *collector).poll_next(cx) {
1038            Poll::Ready(Some(item)) => Poll::Ready(Ok(item)),
1039            Poll::Ready(None) => Poll::Ready(Err(CollectorError {
1040                reason: collector.end.unwrap_or(EndReason::Shutdown),
1041            })),
1042            Poll::Pending => Poll::Pending,
1043        }
1044    }
1045}
1046
1047/// The future of a shortcut collecting until the end (`await_messages`, `await_reactions`).
1048///
1049/// discord.js counterpart: the promise of `awaitMessages` and `awaitReactions`.
1050#[must_use = "futures do nothing unless polled"]
1051pub struct AwaitAll<T: Collectable, K, V> {
1052    collector: Collector<T>,
1053    collection: Option<Collection<K, V>>,
1054    gather: fn(&mut Collection<K, V>, T),
1055}
1056
1057impl<T: Collectable, K, V> fmt::Debug for AwaitAll<T, K, V> {
1058    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1059        f.debug_struct("AwaitAll")
1060            .field("collector", &self.collector)
1061            .finish_non_exhaustive()
1062    }
1063}
1064
1065// Nothing in it is pinned structurally: the collector is moved around freely.
1066impl<T: Collectable, K, V> Unpin for AwaitAll<T, K, V> {}
1067
1068impl<T: Collectable, K, V> Future for AwaitAll<T, K, V> {
1069    type Output = Collected<K, V>;
1070
1071    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
1072        let this = self.get_mut();
1073        loop {
1074            match Pin::new(&mut this.collector).poll_next(cx) {
1075                Poll::Ready(Some(item)) => {
1076                    if let Some(collection) = &mut this.collection {
1077                        (this.gather)(collection, item);
1078                    }
1079                }
1080                Poll::Ready(None) => {
1081                    return Poll::Ready(Collected {
1082                        collection: this.collection.take().unwrap_or_default(),
1083                        reason: this.collector.end.unwrap_or(EndReason::Shutdown),
1084                    });
1085                }
1086                Poll::Pending => return Poll::Pending,
1087            }
1088        }
1089    }
1090}
1091
1092/// Collectors by ID, for code that holds IDs rather than the channel or the message.
1093impl<B: Backend> Context<B> {
1094    /// The guild of `channel`, if the cache knows it (so that the guild's deletion ends the
1095    /// collector).
1096    fn channel_guild(&self, channel: ChannelId) -> Option<GuildId> {
1097        self.ops().channel(channel)?.guild_id()
1098    }
1099
1100    /// A collector of the messages sent in `channel` (D-263, D-269).
1101    ///
1102    /// It ends at its limits, or when the channel, thread or guild is deleted. Needs the
1103    /// `GUILD_MESSAGES` or `DIRECT_MESSAGES` intent (and `MESSAGE_CONTENT` to read guild
1104    /// messages' content).
1105    ///
1106    /// discord.js counterpart: `TextChannel#createMessageCollector`.
1107    ///
1108    /// # Examples
1109    ///
1110    /// ```no_run
1111    /// # use std::time::Duration;
1112    /// # use djs_rs::prelude::*;
1113    /// # async fn example(ctx: Context, msg: djs_rs::model::message::Message) {
1114    /// let mut messages = ctx
1115    ///     .message_collector(msg.channel_id)
1116    ///     .time(Duration::from_secs(60))
1117    ///     .build();
1118    /// while let Some(message) = messages.next().await {
1119    ///     println!("{}: {}", message.author.username, message.content);
1120    /// }
1121    /// # }
1122    /// ```
1123    pub fn message_collector(&self, channel: ChannelId) -> CollectorBuilder<Arc<MessageCreate>> {
1124        let guild = self.channel_guild(channel);
1125        CollectorBuilder::new(self, Key::Channel(channel), guild, Some(channel))
1126    }
1127
1128    /// Collects the messages sent in `channel` until the collector ends, like
1129    /// [`message_collector`](Self::message_collector); set a limit (`time`, `max`, …), or it
1130    /// only ends with the channel.
1131    ///
1132    /// discord.js counterpart: `TextChannel#awaitMessages`.
1133    pub fn await_messages(
1134        &self,
1135        channel: ChannelId,
1136    ) -> CollectorBuilder<Arc<MessageCreate>, mode::All> {
1137        let guild = self.channel_guild(channel);
1138        CollectorBuilder::new(self, Key::Channel(channel), guild, Some(channel))
1139    }
1140
1141    /// A collector of the component interactions (buttons, select menus) on every message of
1142    /// `channel`.
1143    ///
1144    /// discord.js counterpart: `TextChannel#createMessageComponentCollector`.
1145    pub fn component_collector(
1146        &self,
1147        channel: ChannelId,
1148    ) -> CollectorBuilder<ComponentInteraction> {
1149        let guild = self.channel_guild(channel);
1150        CollectorBuilder::new(self, Key::Channel(channel), guild, Some(channel))
1151    }
1152
1153    /// Waits for one component interaction on any message of `channel`; set a
1154    /// [`time`](CollectorBuilder::time), or it only ends with the channel.
1155    ///
1156    /// # Errors
1157    ///
1158    /// [`CollectorError`] with the reason if the collector ended first.
1159    ///
1160    /// discord.js counterpart: `TextChannel#awaitMessageComponent`.
1161    pub fn await_component(
1162        &self,
1163        channel: ChannelId,
1164    ) -> CollectorBuilder<ComponentInteraction, mode::First> {
1165        let guild = self.channel_guild(channel);
1166        CollectorBuilder::new(self, Key::Channel(channel), guild, Some(channel))
1167    }
1168}