1mod 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
113#[non_exhaustive]
114pub enum EndReason {
115 Time,
117 Idle,
119 Limit,
121 ProcessedLimit,
123 UserLimit,
125 EmojiLimit,
127 MessageDelete,
129 ChannelDelete,
131 ThreadDelete,
133 GuildDelete,
135 Stopped,
137 Shutdown,
139}
140
141impl EndReason {
142 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
177pub struct CollectorError {
178 reason: EndReason,
179}
180
181impl CollectorError {
182 #[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#[derive(Clone, Debug, PartialEq)]
207#[non_exhaustive]
208pub enum ReactionEvent {
209 Added(Arc<MessageReactionAdd>),
211 Removed(Arc<MessageReactionRemove>),
213 RemovedAll(Arc<MessageReactionRemoveAll>),
216}
217
218impl ReactionEvent {
219 #[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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
248#[non_exhaustive]
249pub struct CollectedReaction {
250 pub emoji: PartialEmoji,
252 pub users: Vec<UserId>,
254}
255
256impl CollectedReaction {
257 #[must_use]
261 pub fn count(&self) -> usize {
262 self.users.len()
263 }
264}
265
266#[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#[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 #[must_use]
291 pub const fn reason(&self) -> EndReason {
292 self.reason
293 }
294
295 #[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
318pub mod mode {
320 #[derive(Debug)]
324 pub struct Stream;
325
326 #[derive(Debug)]
330 pub struct First;
331
332 #[derive(Debug)]
336 pub struct All;
337}
338
339pub 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 #[derive(Debug)]
359 pub enum Action<'a> {
360 Collect {
362 user: Option<UserId>,
363 emoji: Option<&'a PartialEmoji>,
364 component: Option<ComponentType>,
365 },
366 Remove {
368 user: UserId,
369 emoji: &'a PartialEmoji,
370 },
371 Clear,
373 }
374
375 pub trait Item: Sized + Send + 'static {
376 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
450struct 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#[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 pub const fn time(mut self, time: Duration) -> Self {
547 self.options.time = Some(time);
548 self
549 }
550
551 pub const fn idle(mut self, idle: Duration) -> Self {
553 self.options.idle = Some(idle);
554 self
555 }
556
557 pub const fn max(mut self, max: usize) -> Self {
560 self.options.max = Some(max);
561 self
562 }
563
564 pub const fn max_processed(mut self, max: usize) -> Self {
567 self.options.max_processed = Some(max);
568 self
569 }
570
571 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 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 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 pub const fn component_type(mut self, kind: ComponentType) -> Self {
616 self.options.component_type = Some(kind);
617 self
618 }
619
620 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 pub const fn dispose(mut self, dispose: bool) -> Self {
632 self.options.dispose = dispose;
633 self
634 }
635
636 pub const fn max_users(mut self, max: usize) -> Self {
639 self.options.max_users = Some(max);
640 self
641 }
642
643 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 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
702fn 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#[derive(Debug)]
731struct Tally {
732 collected: usize,
733 processed: usize,
734 users: Option<HashMap<UserId, usize>>,
736 emojis: Option<HashMap<String, usize>>,
738 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 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 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#[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 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 pub fn stop(&mut self) {
871 self.finish(EndReason::Stopped);
872 }
873
874 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 #[must_use]
898 pub const fn end_reason(&self) -> Option<EndReason> {
899 self.end
900 }
901
902 #[must_use]
904 pub const fn is_ended(&self) -> bool {
905 self.end.is_some()
906 }
907
908 #[must_use]
913 pub const fn collected(&self) -> usize {
914 self.tally.collected
915 }
916
917 #[must_use]
921 pub const fn processed(&self) -> usize {
922 self.tally.processed
923 }
924
925 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 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 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#[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#[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
1065impl<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
1092impl<B: Backend> Context<B> {
1094 fn channel_guild(&self, channel: ChannelId) -> Option<GuildId> {
1097 self.ops().channel(channel)?.guild_id()
1098 }
1099
1100 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 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 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 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}