djs_rs/ext.rs
1//! Methods on Discord structures (discord.js-style "structures" behaviour, D-220).
2//!
3//! djs-rs keeps the data types of `djs-model` and `djs-cache` plain and adds behaviour through
4//! extension traits that take the handler [`Context`] explicitly — `msg.reply(&ctx, "Pong!")` —
5//! instead of storing a client reference inside every structure as discord.js does. This keeps
6//! structures small, `Clone` cheap and free of reference cycles.
7//!
8//! Each trait is implemented for the model type *and* the cached type (D-233), and so works on
9//! anything that dereferences to one of them, such as event payloads. The methods delegate to
10//! the [managers](crate::manager) and return what they return: the cached type in an `Arc`.
11//!
12//! | Trait | Implemented for |
13//! |---|---|
14//! | [`MessageExt`] | [`Message`], [`CachedMessage`] |
15//! | [`ChannelExt`] | [`Channel`] (also the cached type) |
16//! | [`UserExt`] | [`User`], [`CachedUser`] |
17//! | [`MemberExt`] | [`CachedMember`], the [`GuildMemberAdd`] and [`GuildMemberUpdate`] payloads (the model [`Member`](djs_model::guild::Member) does not know its guild) |
18//! | [`GuildExt`] | [`Guild`], [`CachedGuild`] |
19//! | [`WebhookExt`] | [`Webhook`] |
20//! | [`InteractionExt`] | [`Interaction`] (and so the [`InteractionCreate`](djs_model::gateway::payload::InteractionCreate) payload), the [router](crate::router)'s wrappers |
21//!
22//! Import the traits with [`prelude`](crate::prelude).
23
24use std::{future::Future, sync::Arc, time::Duration};
25
26use djs_cache::{Backend, CachedGuild, CachedMember, CachedMessage, CachedUser};
27use djs_collection::Collection;
28use djs_model::{
29 audit_log::AuditLog,
30 channel::Channel,
31 gateway::payload::{GuildMemberAdd, GuildMemberUpdate, MessageCreate},
32 guild::{Guild, Integration},
33 id::{
34 ApplicationId, ChannelId, GuildId, IntegrationId, InteractionId, MessageId, RoleId, UserId,
35 WebhookId,
36 },
37 interaction::{
38 AutocompleteCallbackData, AutocompleteChoices, DeferredCallbackData, Interaction,
39 InteractionResponse, MessageCallbackData, ModalCallbackData,
40 },
41 invite::InviteWithMetadata,
42 message::{Message, MessageFlags, MessageReference},
43 permissions::Permissions,
44 rest::{
45 CreateChannelInvite, CreateFollowupMessage, CreateGuildBan, CreateMessage, CreateWebhook,
46 EditMessage, EditWebhookMessage, ExecuteWebhook, GetGuildAuditLog, ModifyGuild,
47 ModifyGuildChannel, ModifyGuildMember, ModifyWebhook, SendSoundboardSound,
48 StartThreadFromMessage,
49 },
50 user::User,
51 util::Timestamp,
52 webhook::Webhook,
53};
54use djs_rest::{Error, ReactionEmoji};
55
56use crate::{
57 Context,
58 collector::{CollectorBuilder, Key, ReactionEvent, mode},
59 manager::{
60 AutoModerationRuleManager, BanManager, EmojiManager, GuildChannelManager,
61 GuildCommandManager, MemberManager, MessageManager, OverwriteTarget, RoleManager,
62 ScheduledEventManager, SoundboardSoundManager, StageInstanceManager, StickerManager,
63 ThreadManager, ThreadMemberManager,
64 },
65 router::{ComponentInteraction, ModalInteraction},
66 webhook::WebhookError,
67};
68
69/// Actions on a message: [`Message`] or [`CachedMessage`].
70///
71/// This trait is sealed.
72///
73/// discord.js counterpart: the methods of `Message`.
74///
75/// # Examples
76///
77/// ```no_run
78/// # use djs_rs::prelude::*;
79/// # let client = Client::builder("token").build();
80/// client.on(Events::MessageCreate, |ctx, msg| async move {
81/// if msg.content == "!ping" {
82/// let reply = msg.reply(&ctx, "Pong!").await?;
83/// reply.react(&ctx, "🏓").await?;
84/// }
85/// Ok(())
86/// });
87/// ```
88pub trait MessageExt: sealed::Message {
89 /// Replies to this message in the same channel: the reply references this message
90 /// (Discord shows it as a reply). Accepts anything that converts into a
91 /// [`CreateMessage`], such as `&str` or `String`. The reply is cached.
92 ///
93 /// discord.js counterpart: `Message#reply`.
94 ///
95 /// # Errors
96 ///
97 /// Returns the REST error if the message could not be sent (see
98 /// [`Rest::create_message`](djs_rest::Rest::create_message)).
99 fn reply<B: Backend>(
100 &self,
101 ctx: &Context<B>,
102 body: impl Into<CreateMessage>,
103 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
104 let (channel_id, message_id) = self.ids();
105 let mut body = body.into();
106 body.message_reference = Some(MessageReference::reply(message_id));
107 ctx.messages(channel_id).send(body)
108 }
109
110 /// Edits this message ([`MessageManager::edit`]).
111 ///
112 /// discord.js counterpart: `Message#edit`.
113 ///
114 /// # Errors
115 ///
116 /// Returns the REST error if the request failed.
117 fn edit<B: Backend>(
118 &self,
119 ctx: &Context<B>,
120 body: &EditMessage,
121 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
122 let (channel_id, message_id) = self.ids();
123 ctx.messages(channel_id).edit(message_id, body)
124 }
125
126 /// Deletes this message ([`MessageManager::delete`]).
127 ///
128 /// discord.js counterpart: `Message#delete`.
129 ///
130 /// # Errors
131 ///
132 /// Returns the REST error if the request failed.
133 fn delete<B: Backend>(
134 &self,
135 ctx: &Context<B>,
136 ) -> impl Future<Output = Result<(), Error>> + Send {
137 let (channel_id, message_id) = self.ids();
138 ctx.messages(channel_id).delete(message_id)
139 }
140
141 /// Reacts to this message ([`MessageManager::react`]): a `&str` for a Unicode emoji, or a
142 /// custom [`ReactionEmoji`].
143 ///
144 /// discord.js counterpart: `Message#react`.
145 ///
146 /// # Errors
147 ///
148 /// Returns the REST error if the request failed.
149 fn react<'e, B: Backend>(
150 &self,
151 ctx: &Context<B>,
152 emoji: impl Into<ReactionEmoji<'e>>,
153 ) -> impl Future<Output = Result<(), Error>> + Send {
154 let (channel_id, message_id) = self.ids();
155 ctx.messages(channel_id).react(message_id, emoji)
156 }
157
158 /// Pins this message ([`MessageManager::pin`]).
159 ///
160 /// discord.js counterpart: `Message#pin`.
161 ///
162 /// # Errors
163 ///
164 /// Returns the REST error if the request failed.
165 fn pin<B: Backend>(
166 &self,
167 ctx: &Context<B>,
168 reason: Option<&str>,
169 ) -> impl Future<Output = Result<(), Error>> + Send {
170 let (channel_id, message_id) = self.ids();
171 ctx.messages(channel_id).pin(message_id, reason)
172 }
173
174 /// Unpins this message ([`MessageManager::unpin`]).
175 ///
176 /// discord.js counterpart: `Message#unpin`.
177 ///
178 /// # Errors
179 ///
180 /// Returns the REST error if the request failed.
181 fn unpin<B: Backend>(
182 &self,
183 ctx: &Context<B>,
184 reason: Option<&str>,
185 ) -> impl Future<Output = Result<(), Error>> + Send {
186 let (channel_id, message_id) = self.ids();
187 ctx.messages(channel_id).unpin(message_id, reason)
188 }
189
190 /// Starts a thread from this message ([`MessageManager::start_thread`]).
191 ///
192 /// discord.js counterpart: `Message#startThread`.
193 ///
194 /// # Errors
195 ///
196 /// Returns the REST error if the request failed.
197 fn start_thread<B: Backend>(
198 &self,
199 ctx: &Context<B>,
200 body: &StartThreadFromMessage,
201 reason: Option<&str>,
202 ) -> impl Future<Output = Result<Arc<Channel>, Error>> + Send {
203 let (channel_id, message_id) = self.ids();
204 ctx.messages(channel_id)
205 .start_thread(message_id, body, reason)
206 }
207
208 /// Publishes this announcement-channel message to the following channels
209 /// ([`MessageManager::crosspost`]).
210 ///
211 /// discord.js counterpart: `Message#crosspost`.
212 ///
213 /// # Errors
214 ///
215 /// Returns the REST error if the request failed.
216 fn crosspost<B: Backend>(
217 &self,
218 ctx: &Context<B>,
219 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
220 let (channel_id, message_id) = self.ids();
221 ctx.messages(channel_id).crosspost(message_id)
222 }
223
224 /// Removes a reaction from this message: the bot's own with `user: None`, or another
225 /// user's ([`MessageManager::remove_reaction`]).
226 ///
227 /// discord.js counterpart: `ReactionUserManager#remove`.
228 ///
229 /// # Errors
230 ///
231 /// Returns the REST error if the request failed.
232 fn remove_reaction<'e, B: Backend>(
233 &self,
234 ctx: &Context<B>,
235 emoji: impl Into<ReactionEmoji<'e>>,
236 user: Option<UserId>,
237 ) -> impl Future<Output = Result<(), Error>> + Send {
238 let (channel_id, message_id) = self.ids();
239 ctx.messages(channel_id)
240 .remove_reaction(message_id, emoji, user)
241 }
242
243 /// Removes every reaction from this message ([`MessageManager::remove_all_reactions`]).
244 ///
245 /// discord.js counterpart: `ReactionManager#removeAll`.
246 ///
247 /// # Errors
248 ///
249 /// Returns the REST error if the request failed.
250 fn remove_all_reactions<B: Backend>(
251 &self,
252 ctx: &Context<B>,
253 ) -> impl Future<Output = Result<(), Error>> + Send {
254 let (channel_id, message_id) = self.ids();
255 ctx.messages(channel_id).remove_all_reactions(message_id)
256 }
257
258 /// A collector of the reactions added to this message (D-263, D-269); with
259 /// [`dispose`](CollectorBuilder::dispose) it also yields their removals.
260 ///
261 /// It ends at its limits, or when the message, its channel, thread or guild is deleted.
262 /// Needs the `GUILD_MESSAGE_REACTIONS` or `DIRECT_MESSAGE_REACTIONS` intent.
263 ///
264 /// discord.js counterpart: `Message#createReactionCollector`.
265 ///
266 /// # Examples
267 ///
268 /// ```no_run
269 /// # use std::time::Duration;
270 /// # use djs_rs::{collector::ReactionEvent, prelude::*};
271 /// # async fn example(ctx: Context, poll: djs_rs::model::message::Message) {
272 /// let mut votes = poll
273 /// .reaction_collector(&ctx)
274 /// .time(Duration::from_secs(60))
275 /// .build();
276 /// while let Some(ReactionEvent::Added(vote)) = votes.next().await {
277 /// println!("{} voted {:?}", vote.user_id, vote.emoji.name());
278 /// }
279 /// # }
280 /// ```
281 fn reaction_collector<B: Backend>(&self, ctx: &Context<B>) -> CollectorBuilder<ReactionEvent> {
282 let (channel_id, message_id) = self.ids();
283 CollectorBuilder::new(
284 ctx,
285 Key::Message(message_id),
286 self.guild(),
287 Some(channel_id),
288 )
289 }
290
291 /// Collects the reactions added to this message until the collector ends, gathered by
292 /// emoji ([`reaction_key`](crate::collector::reaction_key)); set a limit (`time`, `max`,
293 /// …), or it only ends with the message.
294 ///
295 /// discord.js counterpart: `Message#awaitReactions`.
296 ///
297 /// # Examples
298 ///
299 /// ```no_run
300 /// # use std::time::Duration;
301 /// # use djs_rs::prelude::*;
302 /// # async fn example(ctx: Context, poll: djs_rs::model::message::Message) {
303 /// let votes = poll.await_reactions(&ctx).time(Duration::from_secs(60)).await;
304 /// let yes = votes.get("👍").map_or(0, |reaction| reaction.count());
305 /// println!("{yes} yes votes ({})", votes.reason());
306 /// # }
307 /// ```
308 fn await_reactions<B: Backend>(
309 &self,
310 ctx: &Context<B>,
311 ) -> CollectorBuilder<ReactionEvent, mode::All> {
312 let (channel_id, message_id) = self.ids();
313 CollectorBuilder::new(
314 ctx,
315 Key::Message(message_id),
316 self.guild(),
317 Some(channel_id),
318 )
319 }
320
321 /// A collector of the component interactions (buttons, select menus) on this message.
322 ///
323 /// It ends at its limits, or when the message, its channel, thread or guild is deleted.
324 ///
325 /// discord.js counterpart: `Message#createMessageComponentCollector`.
326 ///
327 /// # Examples
328 ///
329 /// ```no_run
330 /// # use std::time::Duration;
331 /// # use djs_rs::prelude::*;
332 /// # async fn example(ctx: Context, menu: djs_rs::model::message::Message) -> Result<(), HandlerError> {
333 /// let mut clicks = menu
334 /// .component_collector(&ctx)
335 /// .idle(Duration::from_secs(120))
336 /// .build();
337 /// while let Some(click) = clicks.next().await {
338 /// click.reply(&ctx, format!("You pressed {}", click.custom_id)).await?;
339 /// }
340 /// # Ok(())
341 /// # }
342 /// ```
343 fn component_collector<B: Backend>(
344 &self,
345 ctx: &Context<B>,
346 ) -> CollectorBuilder<ComponentInteraction> {
347 let (channel_id, message_id) = self.ids();
348 CollectorBuilder::new(
349 ctx,
350 Key::Message(message_id),
351 self.guild(),
352 Some(channel_id),
353 )
354 }
355
356 /// Waits for one component interaction on this message (D-268); set a
357 /// [`time`](CollectorBuilder::time), or it only ends with the message.
358 ///
359 /// discord.js counterpart: `Message#awaitMessageComponent`.
360 ///
361 /// # Errors
362 ///
363 /// [`CollectorError`](crate::collector::CollectorError) with the reason if the collector
364 /// ended first ([`EndReason::Time`](crate::collector::EndReason::Time), …).
365 ///
366 /// # Examples
367 ///
368 /// ```no_run
369 /// # use std::time::Duration;
370 /// # use djs_rs::prelude::*;
371 /// # async fn example(ctx: Context, prompt: djs_rs::model::message::Message) -> Result<(), HandlerError> {
372 /// match prompt.await_component(&ctx).time(Duration::from_secs(30)).await {
373 /// Ok(click) if click.custom_id == "confirm" => click.update(&ctx, "Confirmed").await?,
374 /// Ok(click) => click.update(&ctx, "Cancelled").await?,
375 /// Err(_) => println!("no answer in 30 seconds"),
376 /// }
377 /// # Ok(())
378 /// # }
379 /// ```
380 fn await_component<B: Backend>(
381 &self,
382 ctx: &Context<B>,
383 ) -> CollectorBuilder<ComponentInteraction, mode::First> {
384 let (channel_id, message_id) = self.ids();
385 CollectorBuilder::new(
386 ctx,
387 Key::Message(message_id),
388 self.guild(),
389 Some(channel_id),
390 )
391 }
392}
393
394impl MessageExt for Message {}
395impl MessageExt for CachedMessage {}
396
397/// Actions on a [`Channel`] (the model type, which is also the type the cache keeps).
398///
399/// This trait is sealed.
400///
401/// discord.js counterpart: the methods of `BaseChannel` and its subclasses.
402///
403/// # Examples
404///
405/// ```no_run
406/// # use djs_rs::prelude::*;
407/// # let client = Client::builder("token").build();
408/// client.on(Events::ThreadCreate, |ctx, thread| async move {
409/// thread.send(&ctx, "Welcome to the thread!").await?;
410/// Ok(())
411/// });
412/// ```
413pub trait ChannelExt: sealed::Channel {
414 /// The manager of this channel's messages.
415 ///
416 /// discord.js counterpart: `TextChannel#messages`.
417 fn messages<'a, B: Backend>(&self, ctx: &'a Context<B>) -> MessageManager<'a, B> {
418 ctx.messages(self.channel_id())
419 }
420
421 /// Sends a message to this channel ([`MessageManager::send`]).
422 ///
423 /// discord.js counterpart: `TextChannel#send`.
424 ///
425 /// # Errors
426 ///
427 /// Returns the REST error if the message could not be sent.
428 fn send<B: Backend>(
429 &self,
430 ctx: &Context<B>,
431 body: impl Into<CreateMessage>,
432 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
433 ctx.messages(self.channel_id()).send(body)
434 }
435
436 /// Shows the bot as typing in this channel ([`ChannelManager::send_typing`](crate::manager::ChannelManager::send_typing)).
437 ///
438 /// discord.js counterpart: `TextChannel#sendTyping`.
439 ///
440 /// # Errors
441 ///
442 /// Returns the REST error if the request failed.
443 fn send_typing<B: Backend>(
444 &self,
445 ctx: &Context<B>,
446 ) -> impl Future<Output = Result<(), Error>> + Send {
447 ctx.channels().send_typing(self.channel_id())
448 }
449
450 /// Deletes 2 to 100 recent messages of this channel ([`MessageManager::bulk_delete`]).
451 ///
452 /// discord.js counterpart: `TextChannel#bulkDelete`.
453 ///
454 /// # Errors
455 ///
456 /// Returns the REST error if the request failed.
457 fn bulk_delete<B: Backend>(
458 &self,
459 ctx: &Context<B>,
460 message_ids: Vec<MessageId>,
461 reason: Option<&str>,
462 ) -> impl Future<Output = Result<(), Error>> + Send {
463 ctx.messages(self.channel_id())
464 .bulk_delete(message_ids, reason)
465 }
466
467 /// Edits this guild channel ([`ChannelManager::edit`](crate::manager::ChannelManager::edit)).
468 ///
469 /// discord.js counterpart: `GuildChannel#edit`.
470 ///
471 /// # Errors
472 ///
473 /// Returns the REST error if the request failed.
474 fn edit<B: Backend>(
475 &self,
476 ctx: &Context<B>,
477 body: &ModifyGuildChannel,
478 reason: Option<&str>,
479 ) -> impl Future<Output = Result<Arc<Channel>, Error>> + Send {
480 ctx.channels().edit(self.channel_id(), body, reason)
481 }
482
483 /// Deletes this channel ([`ChannelManager::delete`](crate::manager::ChannelManager::delete)).
484 ///
485 /// discord.js counterpart: `GuildChannel#delete`.
486 ///
487 /// # Errors
488 ///
489 /// Returns the REST error if the request failed.
490 fn delete<B: Backend>(
491 &self,
492 ctx: &Context<B>,
493 reason: Option<&str>,
494 ) -> impl Future<Output = Result<Channel, Error>> + Send {
495 ctx.channels().delete(self.channel_id(), reason)
496 }
497
498 /// Sets this channel's permission overwrite for a role or a member, replacing it (D-235,
499 /// [`ChannelManager::set_permissions`](crate::manager::ChannelManager::set_permissions)).
500 ///
501 /// discord.js counterpart: `PermissionOverwriteManager#create`.
502 ///
503 /// # Errors
504 ///
505 /// Returns the REST error if the request failed.
506 fn set_permissions<B: Backend>(
507 &self,
508 ctx: &Context<B>,
509 target: impl Into<OverwriteTarget>,
510 allow: Permissions,
511 deny: Permissions,
512 reason: Option<&str>,
513 ) -> impl Future<Output = Result<(), Error>> + Send {
514 ctx.channels()
515 .set_permissions(self.channel_id(), target, allow, deny, reason)
516 }
517
518 /// Removes this channel's permission overwrite for a role or a member
519 /// ([`ChannelManager::delete_permissions`](crate::manager::ChannelManager::delete_permissions)).
520 ///
521 /// discord.js counterpart: `PermissionOverwriteManager#delete`.
522 ///
523 /// # Errors
524 ///
525 /// Returns the REST error if the request failed.
526 fn delete_permissions<B: Backend>(
527 &self,
528 ctx: &Context<B>,
529 target: impl Into<OverwriteTarget>,
530 reason: Option<&str>,
531 ) -> impl Future<Output = Result<(), Error>> + Send {
532 ctx.channels()
533 .delete_permissions(self.channel_id(), target, reason)
534 }
535
536 /// Creates a webhook in this channel ([`WebhookManager::create`](crate::manager::WebhookManager::create)).
537 ///
538 /// discord.js counterpart: `TextChannel#createWebhook`.
539 ///
540 /// # Errors
541 ///
542 /// Returns the REST error if the request failed.
543 fn create_webhook<B: Backend>(
544 &self,
545 ctx: &Context<B>,
546 body: &CreateWebhook,
547 reason: Option<&str>,
548 ) -> impl Future<Output = Result<Webhook, Error>> + Send {
549 ctx.webhooks().create(self.channel_id(), body, reason)
550 }
551
552 /// The webhooks of this channel ([`WebhookManager::list_channel`](crate::manager::WebhookManager::list_channel)).
553 ///
554 /// discord.js counterpart: `TextChannel#fetchWebhooks`.
555 ///
556 /// # Errors
557 ///
558 /// Returns the REST error if the request failed.
559 fn webhooks<B: Backend>(
560 &self,
561 ctx: &Context<B>,
562 ) -> impl Future<Output = Result<Collection<WebhookId, Webhook>, Error>> + Send {
563 ctx.webhooks().list_channel(self.channel_id())
564 }
565
566 /// Creates an invite to this channel ([`InviteManager::create`](crate::manager::InviteManager::create)).
567 ///
568 /// discord.js counterpart: `TextChannel#createInvite`.
569 ///
570 /// # Errors
571 ///
572 /// Returns the REST error if the request failed.
573 fn create_invite<B: Backend>(
574 &self,
575 ctx: &Context<B>,
576 body: &CreateChannelInvite,
577 reason: Option<&str>,
578 ) -> impl Future<Output = Result<InviteWithMetadata, Error>> + Send {
579 ctx.invites().create(self.channel_id(), body, reason)
580 }
581
582 /// The invites to this channel ([`InviteManager::list_channel`](crate::manager::InviteManager::list_channel)).
583 ///
584 /// discord.js counterpart: `TextChannel#fetchInvites`.
585 ///
586 /// # Errors
587 ///
588 /// Returns the REST error if the request failed.
589 fn invites<B: Backend>(
590 &self,
591 ctx: &Context<B>,
592 ) -> impl Future<Output = Result<Collection<String, InviteWithMetadata>, Error>> + Send {
593 ctx.invites().list_channel(self.channel_id())
594 }
595
596 /// The manager of this channel's threads: create, list archived (D-242).
597 ///
598 /// discord.js counterpart: `TextChannel#threads`.
599 fn threads<'a, B: Backend>(&self, ctx: &'a Context<B>) -> ThreadManager<'a, B> {
600 ctx.threads(self.channel_id())
601 }
602
603 /// The manager of this thread's members: add, remove, join, leave (D-242).
604 ///
605 /// discord.js counterpart: `ThreadChannel#members`.
606 fn thread_members<'a, B: Backend>(&self, ctx: &'a Context<B>) -> ThreadMemberManager<'a, B> {
607 ctx.thread_members(self.channel_id())
608 }
609
610 /// Plays a soundboard sound in this voice channel
611 /// ([`ChannelManager::send_soundboard_sound`](crate::manager::ChannelManager::send_soundboard_sound)).
612 ///
613 /// discord.js counterpart: `VoiceChannel#sendSoundboardSound`.
614 ///
615 /// # Errors
616 ///
617 /// Returns the REST error if the request failed.
618 fn send_soundboard_sound<B: Backend>(
619 &self,
620 ctx: &Context<B>,
621 body: &SendSoundboardSound,
622 ) -> impl Future<Output = Result<(), Error>> + Send {
623 ctx.channels()
624 .send_soundboard_sound(self.channel_id(), body)
625 }
626
627 /// A collector of the messages sent in this channel
628 /// ([`Context::message_collector`]).
629 ///
630 /// discord.js counterpart: `TextChannel#createMessageCollector`.
631 fn message_collector<B: Backend>(
632 &self,
633 ctx: &Context<B>,
634 ) -> CollectorBuilder<Arc<MessageCreate>> {
635 ctx.message_collector(self.channel_id())
636 }
637
638 /// Collects the messages sent in this channel until the collector ends
639 /// ([`Context::await_messages`]).
640 ///
641 /// discord.js counterpart: `TextChannel#awaitMessages`.
642 fn await_messages<B: Backend>(
643 &self,
644 ctx: &Context<B>,
645 ) -> CollectorBuilder<Arc<MessageCreate>, mode::All> {
646 ctx.await_messages(self.channel_id())
647 }
648
649 /// A collector of the component interactions on every message of this channel
650 /// ([`Context::component_collector`]).
651 ///
652 /// discord.js counterpart: `TextChannel#createMessageComponentCollector`.
653 fn component_collector<B: Backend>(
654 &self,
655 ctx: &Context<B>,
656 ) -> CollectorBuilder<ComponentInteraction> {
657 ctx.component_collector(self.channel_id())
658 }
659
660 /// Waits for one component interaction on any message of this channel
661 /// ([`Context::await_component`]).
662 ///
663 /// discord.js counterpart: `TextChannel#awaitMessageComponent`.
664 ///
665 /// # Errors
666 ///
667 /// [`CollectorError`](crate::collector::CollectorError) with the reason if the collector
668 /// ended first.
669 fn await_component<B: Backend>(
670 &self,
671 ctx: &Context<B>,
672 ) -> CollectorBuilder<ComponentInteraction, mode::First> {
673 ctx.await_component(self.channel_id())
674 }
675}
676
677impl ChannelExt for Channel {}
678
679/// Actions on a user: [`User`] or [`CachedUser`].
680///
681/// This trait is sealed.
682///
683/// discord.js counterpart: the methods of `User`.
684///
685/// # Examples
686///
687/// ```no_run
688/// # use djs_rs::prelude::*;
689/// # let client = Client::builder("token").build();
690/// client.on(Events::GuildMemberAdd, |ctx, join| async move {
691/// join.user.send(&ctx, "Welcome!").await?;
692/// Ok(())
693/// });
694/// ```
695pub trait UserExt: sealed::User {
696 /// Sends a direct message to this user ([`UserManager::send`](crate::manager::UserManager::send)).
697 ///
698 /// discord.js counterpart: `User#send`.
699 ///
700 /// # Errors
701 ///
702 /// Returns the REST error if a request failed.
703 fn send<B: Backend>(
704 &self,
705 ctx: &Context<B>,
706 body: impl Into<CreateMessage>,
707 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
708 ctx.users().send(self.user_id(), body)
709 }
710
711 /// The DM channel with this user ([`UserManager::create_dm`](crate::manager::UserManager::create_dm)).
712 ///
713 /// discord.js counterpart: `User#createDM`.
714 ///
715 /// # Errors
716 ///
717 /// Returns the REST error if the request failed.
718 fn create_dm<B: Backend>(
719 &self,
720 ctx: &Context<B>,
721 ) -> impl Future<Output = Result<Arc<Channel>, Error>> + Send {
722 ctx.users().create_dm(self.user_id())
723 }
724}
725
726impl UserExt for User {}
727impl UserExt for CachedUser {}
728
729/// Actions on a guild member: [`CachedMember`], or the payload of
730/// [`Events::GuildMemberAdd`](crate::Events::GuildMemberAdd) or
731/// [`Events::GuildMemberUpdate`](crate::Events::GuildMemberUpdate).
732///
733/// This trait is sealed.
734///
735/// discord.js counterpart: the methods of `GuildMember`.
736///
737/// # Examples
738///
739/// ```no_run
740/// # use djs_rs::prelude::*;
741/// # use djs_rs::model::id::RoleId;
742/// # let client = Client::builder("token").build();
743/// const NEWCOMER: RoleId = RoleId::new(1_300_000_000_000_000_000);
744/// client.on(Events::GuildMemberAdd, |ctx, member| async move {
745/// member.add_role(&ctx, NEWCOMER, Some("new member")).await?;
746/// Ok(())
747/// });
748/// ```
749pub trait MemberExt: sealed::Member {
750 /// Edits this member ([`MemberManager::edit`]).
751 ///
752 /// discord.js counterpart: `GuildMember#edit`.
753 ///
754 /// # Errors
755 ///
756 /// Returns the REST error if the request failed.
757 fn edit<B: Backend>(
758 &self,
759 ctx: &Context<B>,
760 body: &ModifyGuildMember,
761 reason: Option<&str>,
762 ) -> impl Future<Output = Result<Arc<CachedMember>, Error>> + Send {
763 let (guild_id, user_id) = self.ids();
764 ctx.members(guild_id).edit(user_id, body, reason)
765 }
766
767 /// Times this member out until `until`, or ends the timeout with `None`
768 /// ([`MemberManager::timeout`]).
769 ///
770 /// discord.js counterpart: `GuildMember#timeout`.
771 ///
772 /// # Errors
773 ///
774 /// Returns the REST error if the request failed.
775 fn timeout<B: Backend>(
776 &self,
777 ctx: &Context<B>,
778 until: Option<Timestamp>,
779 reason: Option<&str>,
780 ) -> impl Future<Output = Result<Arc<CachedMember>, Error>> + Send {
781 let (guild_id, user_id) = self.ids();
782 ctx.members(guild_id).timeout(user_id, until, reason)
783 }
784
785 /// Sets this member's nickname, or removes it with `None`
786 /// ([`MemberManager::set_nickname`]).
787 ///
788 /// discord.js counterpart: `GuildMember#setNickname`.
789 ///
790 /// # Errors
791 ///
792 /// Returns the REST error if the request failed.
793 fn set_nickname<B: Backend>(
794 &self,
795 ctx: &Context<B>,
796 nickname: Option<&str>,
797 reason: Option<&str>,
798 ) -> impl Future<Output = Result<Arc<CachedMember>, Error>> + Send {
799 let (guild_id, user_id) = self.ids();
800 ctx.members(guild_id)
801 .set_nickname(user_id, nickname, reason)
802 }
803
804 /// Gives this member a role ([`MemberManager::add_role`]).
805 ///
806 /// discord.js counterpart: `GuildMemberRoleManager#add`.
807 ///
808 /// # Errors
809 ///
810 /// Returns the REST error if the request failed.
811 fn add_role<B: Backend>(
812 &self,
813 ctx: &Context<B>,
814 role_id: RoleId,
815 reason: Option<&str>,
816 ) -> impl Future<Output = Result<(), Error>> + Send {
817 let (guild_id, user_id) = self.ids();
818 ctx.members(guild_id).add_role(user_id, role_id, reason)
819 }
820
821 /// Takes a role from this member ([`MemberManager::remove_role`]).
822 ///
823 /// discord.js counterpart: `GuildMemberRoleManager#remove`.
824 ///
825 /// # Errors
826 ///
827 /// Returns the REST error if the request failed.
828 fn remove_role<B: Backend>(
829 &self,
830 ctx: &Context<B>,
831 role_id: RoleId,
832 reason: Option<&str>,
833 ) -> impl Future<Output = Result<(), Error>> + Send {
834 let (guild_id, user_id) = self.ids();
835 ctx.members(guild_id).remove_role(user_id, role_id, reason)
836 }
837
838 /// Kicks this member ([`MemberManager::kick`]).
839 ///
840 /// discord.js counterpart: `GuildMember#kick`.
841 ///
842 /// # Errors
843 ///
844 /// Returns the REST error if the request failed.
845 fn kick<B: Backend>(
846 &self,
847 ctx: &Context<B>,
848 reason: Option<&str>,
849 ) -> impl Future<Output = Result<(), Error>> + Send {
850 let (guild_id, user_id) = self.ids();
851 ctx.members(guild_id).kick(user_id, reason)
852 }
853
854 /// Bans this member ([`MemberManager::ban`]).
855 ///
856 /// discord.js counterpart: `GuildMember#ban`.
857 ///
858 /// # Errors
859 ///
860 /// Returns the REST error if the request failed.
861 fn ban<B: Backend>(
862 &self,
863 ctx: &Context<B>,
864 body: &CreateGuildBan,
865 reason: Option<&str>,
866 ) -> impl Future<Output = Result<(), Error>> + Send {
867 let (guild_id, user_id) = self.ids();
868 ctx.members(guild_id).ban(user_id, body, reason)
869 }
870
871 /// This member's permissions in its guild, computed from the cache as Discord applies
872 /// them now, a timeout included ([`Cache::member_permissions`](djs_cache::Cache::member_permissions),
873 /// D-292, D-294). The cache's current state of the member is used, not this value's.
874 ///
875 /// `None` without a cache, or when the cache lacks the guild, the member or one of its
876 /// roles (members are not cached by default: enable them in the
877 /// [`CacheConfig`](djs_cache::CacheConfig)). Interactions carry Discord's own
878 /// computation instead ([`Interaction::member`](djs_model::interaction::Interaction::member)'s
879 /// `permissions`).
880 ///
881 /// discord.js counterpart: `GuildMember#permissions`.
882 ///
883 /// # Examples
884 ///
885 /// ```no_run
886 /// use djs_rs::{model::permissions::Permissions, prelude::*};
887 ///
888 /// # fn register(client: &Client) {
889 /// // A prefix command for moderators only.
890 /// client.on(Events::MessageCreate, |ctx, msg| async move {
891 /// let Some(guild_id) = msg.guild_id else { return Ok(()) };
892 /// if msg.content.starts_with("!kick ") {
893 /// let author = ctx.members(guild_id).fetch(msg.author.id).await?;
894 /// let allowed = author
895 /// .permissions(&ctx)
896 /// .is_some_and(|permissions| permissions.contains(Permissions::KICK_MEMBERS));
897 /// if !allowed {
898 /// msg.reply(&ctx, "You may not kick members.").await?;
899 /// return Ok(());
900 /// }
901 /// // …
902 /// }
903 /// Ok(())
904 /// });
905 /// # }
906 /// ```
907 fn permissions<B: Backend>(&self, ctx: &Context<B>) -> Option<Permissions> {
908 let (guild_id, user_id) = self.ids();
909 ctx.ops().member_permissions(guild_id, user_id)
910 }
911
912 /// This member's permissions in the channel or thread `channel_id` of its guild, computed
913 /// from the cache as Discord applies them now: the channel's overwrites (a thread's
914 /// parent's), the implicit denials (no `VIEW_CHANNEL`: nothing; no `SEND_MESSAGES`: no
915 /// mentions of everyone, TTS, files or embeds, D-295) and a timeout (D-294)
916 /// ([`Cache::member_permissions_in`](djs_cache::Cache::member_permissions_in)).
917 ///
918 /// `None` without a cache, or when the cache lacks the channel (and for a thread, its
919 /// parent), the guild, the member or one of its roles; also for a channel of another
920 /// guild.
921 ///
922 /// discord.js counterpart: `GuildMember#permissionsIn(channel)`.
923 fn permissions_in<B: Backend>(
924 &self,
925 ctx: &Context<B>,
926 channel_id: ChannelId,
927 ) -> Option<Permissions> {
928 let (guild_id, user_id) = self.ids();
929 ctx.ops()
930 .member_permissions_in(guild_id, channel_id, user_id)
931 }
932}
933
934impl MemberExt for CachedMember {}
935impl MemberExt for GuildMemberAdd {}
936impl MemberExt for GuildMemberUpdate {}
937
938/// Actions on a guild: [`Guild`] or [`CachedGuild`].
939///
940/// This trait is sealed.
941///
942/// discord.js counterpart: the methods and managers of `Guild`.
943///
944/// # Examples
945///
946/// ```no_run
947/// # use djs_rs::prelude::*;
948/// # use djs_rs::model::id::UserId;
949/// # async fn run(ctx: Context, guild: std::sync::Arc<djs_rs::cache::CachedGuild>) -> Result<(), djs_rs::rest::Error> {
950/// let owner = guild.members(&ctx).fetch(guild.owner_id).await?;
951/// println!("{} owns {}", owner.user.username, guild.name);
952/// # Ok(())
953/// # }
954/// ```
955pub trait GuildExt: sealed::Guild {
956 /// The manager of this guild's members.
957 ///
958 /// discord.js counterpart: `Guild#members`.
959 fn members<'a, B: Backend>(&self, ctx: &'a Context<B>) -> MemberManager<'a, B> {
960 ctx.members(self.guild_id())
961 }
962
963 /// The manager of this guild's roles.
964 ///
965 /// discord.js counterpart: `Guild#roles`.
966 fn roles<'a, B: Backend>(&self, ctx: &'a Context<B>) -> RoleManager<'a, B> {
967 ctx.roles(self.guild_id())
968 }
969
970 /// The manager of this guild's bans.
971 ///
972 /// discord.js counterpart: `Guild#bans`.
973 fn bans<'a, B: Backend>(&self, ctx: &'a Context<B>) -> BanManager<'a, B> {
974 ctx.bans(self.guild_id())
975 }
976
977 /// The manager of this guild's channels as a whole: create, list, positions (D-234).
978 ///
979 /// discord.js counterpart: `Guild#channels`.
980 fn channels<'a, B: Backend>(&self, ctx: &'a Context<B>) -> GuildChannelManager<'a, B> {
981 ctx.guild_channels(self.guild_id())
982 }
983
984 /// Edits this guild's settings ([`GuildManager::edit`](crate::manager::GuildManager::edit)).
985 ///
986 /// discord.js counterpart: `Guild#edit`.
987 ///
988 /// # Errors
989 ///
990 /// Returns the REST error if the request failed.
991 fn edit<B: Backend>(
992 &self,
993 ctx: &Context<B>,
994 body: &ModifyGuild,
995 reason: Option<&str>,
996 ) -> impl Future<Output = Result<Arc<CachedGuild>, Error>> + Send {
997 ctx.guilds().edit(self.guild_id(), body, reason)
998 }
999
1000 /// Makes the bot leave this guild ([`GuildManager::leave`](crate::manager::GuildManager::leave)).
1001 ///
1002 /// discord.js counterpart: `Guild#leave`.
1003 ///
1004 /// # Errors
1005 ///
1006 /// Returns the REST error if the request failed (the owner cannot leave its guild).
1007 fn leave<B: Backend>(
1008 &self,
1009 ctx: &Context<B>,
1010 ) -> impl Future<Output = Result<(), Error>> + Send {
1011 ctx.guilds().leave(self.guild_id())
1012 }
1013
1014 /// The manager of this guild's custom emojis.
1015 ///
1016 /// discord.js counterpart: `Guild#emojis`.
1017 fn emojis<'a, B: Backend>(&self, ctx: &'a Context<B>) -> EmojiManager<'a, B> {
1018 ctx.emojis(self.guild_id())
1019 }
1020
1021 /// The manager of this guild's stickers.
1022 ///
1023 /// discord.js counterpart: `Guild#stickers`.
1024 fn stickers<'a, B: Backend>(&self, ctx: &'a Context<B>) -> StickerManager<'a, B> {
1025 ctx.stickers(self.guild_id())
1026 }
1027
1028 /// The webhooks of this guild ([`WebhookManager::list_guild`](crate::manager::WebhookManager::list_guild)).
1029 ///
1030 /// discord.js counterpart: `Guild#fetchWebhooks`.
1031 ///
1032 /// # Errors
1033 ///
1034 /// Returns the REST error if the request failed.
1035 fn webhooks<B: Backend>(
1036 &self,
1037 ctx: &Context<B>,
1038 ) -> impl Future<Output = Result<Collection<WebhookId, Webhook>, Error>> + Send {
1039 ctx.webhooks().list_guild(self.guild_id())
1040 }
1041
1042 /// The invites to this guild ([`InviteManager::list_guild`](crate::manager::InviteManager::list_guild)).
1043 ///
1044 /// discord.js counterpart: `GuildInviteManager#fetch()`.
1045 ///
1046 /// # Errors
1047 ///
1048 /// Returns the REST error if the request failed.
1049 fn invites<B: Backend>(
1050 &self,
1051 ctx: &Context<B>,
1052 ) -> impl Future<Output = Result<Collection<String, InviteWithMetadata>, Error>> + Send {
1053 ctx.invites().list_guild(self.guild_id())
1054 }
1055
1056 /// The manager of this guild's scheduled events.
1057 ///
1058 /// discord.js counterpart: `Guild#scheduledEvents`.
1059 fn scheduled_events<'a, B: Backend>(
1060 &self,
1061 ctx: &'a Context<B>,
1062 ) -> ScheduledEventManager<'a, B> {
1063 ctx.scheduled_events(self.guild_id())
1064 }
1065
1066 /// The manager of this guild's live stages.
1067 ///
1068 /// discord.js counterpart: `Guild#stageInstances`.
1069 fn stage_instances<'a, B: Backend>(&self, ctx: &'a Context<B>) -> StageInstanceManager<'a, B> {
1070 ctx.stage_instances(self.guild_id())
1071 }
1072
1073 /// The manager of this guild's soundboard sounds.
1074 ///
1075 /// discord.js counterpart: `Guild#soundboardSounds`.
1076 fn soundboard_sounds<'a, B: Backend>(
1077 &self,
1078 ctx: &'a Context<B>,
1079 ) -> SoundboardSoundManager<'a, B> {
1080 ctx.soundboard_sounds(self.guild_id())
1081 }
1082
1083 /// The manager of the bot's application commands in this guild (D-244).
1084 ///
1085 /// discord.js counterpart: `Guild#commands`.
1086 ///
1087 /// # Panics
1088 ///
1089 /// Panics before the first `READY` (D-247), like [`Context::commands`].
1090 #[track_caller]
1091 fn commands<'a, B: Backend>(&self, ctx: &'a Context<B>) -> GuildCommandManager<'a, B> {
1092 ctx.guild_commands(self.guild_id())
1093 }
1094
1095 /// The manager of this guild's auto moderation rules.
1096 ///
1097 /// discord.js counterpart: `Guild#autoModerationRules`.
1098 fn auto_moderation_rules<'a, B: Backend>(
1099 &self,
1100 ctx: &'a Context<B>,
1101 ) -> AutoModerationRuleManager<'a, B> {
1102 ctx.auto_moderation_rules(self.guild_id())
1103 }
1104
1105 /// A page of this guild's audit log ([`GuildManager::audit_log`](crate::manager::GuildManager::audit_log)).
1106 ///
1107 /// discord.js counterpart: `Guild#fetchAuditLogs`.
1108 ///
1109 /// # Errors
1110 ///
1111 /// Returns the REST error if the request failed.
1112 fn audit_log<B: Backend>(
1113 &self,
1114 ctx: &Context<B>,
1115 query: &GetGuildAuditLog,
1116 ) -> impl Future<Output = Result<AuditLog, Error>> + Send {
1117 ctx.guilds().audit_log(self.guild_id(), query)
1118 }
1119
1120 /// This guild's integrations ([`GuildManager::integrations`](crate::manager::GuildManager::integrations)).
1121 ///
1122 /// discord.js counterpart: `Guild#fetchIntegrations`.
1123 ///
1124 /// # Errors
1125 ///
1126 /// Returns the REST error if the request failed.
1127 fn integrations<B: Backend>(
1128 &self,
1129 ctx: &Context<B>,
1130 ) -> impl Future<Output = Result<Collection<IntegrationId, Integration>, Error>> + Send {
1131 ctx.guilds().integrations(self.guild_id())
1132 }
1133}
1134
1135impl GuildExt for Guild {}
1136impl GuildExt for CachedGuild {}
1137
1138/// Actions on a [`Webhook`] (D-237, D-240).
1139///
1140/// This trait is sealed.
1141///
1142/// discord.js counterpart: the methods of `Webhook`.
1143///
1144/// # Examples
1145///
1146/// ```no_run
1147/// # use djs_rs::prelude::*;
1148/// # use djs_rs::model::id::ChannelId;
1149/// # async fn run(ctx: Context, channel: ChannelId) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1150/// let webhooks = ctx.webhooks().list_channel(channel).await?;
1151/// if let Some(webhook) = webhooks.values().find(|webhook| webhook.token.is_some()) {
1152/// webhook.send(&ctx, "Hello from a webhook").await?;
1153/// }
1154/// # Ok(())
1155/// # }
1156/// ```
1157pub trait WebhookExt: sealed::Webhook {
1158 /// Sends a message through this webhook with its token
1159 /// ([`WebhookManager::send`](crate::manager::WebhookManager::send)).
1160 ///
1161 /// discord.js counterpart: `Webhook#send`.
1162 ///
1163 /// # Errors
1164 ///
1165 /// Returns [`WebhookError::MissingToken`] for a webhook without a token (channel-follower
1166 /// and application webhooks), or the REST error if the request failed.
1167 fn send<B: Backend>(
1168 &self,
1169 ctx: &Context<B>,
1170 body: impl Into<ExecuteWebhook>,
1171 ) -> impl Future<Output = Result<Arc<CachedMessage>, WebhookError>> + Send {
1172 let (webhook_id, token) = self.webhook_parts();
1173 let body = body.into();
1174 let webhooks = ctx.webhooks();
1175 async move {
1176 let token = token.ok_or(WebhookError::MissingToken)?;
1177 Ok(webhooks.send(webhook_id, token, body).await?)
1178 }
1179 }
1180
1181 /// Edits this webhook ([`WebhookManager::edit`](crate::manager::WebhookManager::edit)).
1182 ///
1183 /// discord.js counterpart: `Webhook#edit`.
1184 ///
1185 /// # Errors
1186 ///
1187 /// Returns the REST error if the request failed.
1188 fn edit<B: Backend>(
1189 &self,
1190 ctx: &Context<B>,
1191 body: &ModifyWebhook,
1192 reason: Option<&str>,
1193 ) -> impl Future<Output = Result<Webhook, Error>> + Send {
1194 ctx.webhooks().edit(self.webhook_parts().0, body, reason)
1195 }
1196
1197 /// Deletes this webhook ([`WebhookManager::delete`](crate::manager::WebhookManager::delete)).
1198 ///
1199 /// discord.js counterpart: `Webhook#delete`.
1200 ///
1201 /// # Errors
1202 ///
1203 /// Returns the REST error if the request failed.
1204 fn delete<B: Backend>(
1205 &self,
1206 ctx: &Context<B>,
1207 reason: Option<&str>,
1208 ) -> impl Future<Output = Result<(), Error>> + Send {
1209 ctx.webhooks().delete(self.webhook_parts().0, reason)
1210 }
1211}
1212
1213impl WebhookExt for Webhook {}
1214
1215/// Responses to an [`Interaction`] (D-248): one method per Discord callback, plus the original
1216/// response and follow-up messages. Works on the
1217/// [`InteractionCreate`](djs_model::gateway::payload::InteractionCreate) payload too, which
1218/// dereferences to the interaction.
1219///
1220/// This trait is sealed.
1221///
1222/// discord.js counterpart: the methods of `CommandInteraction`, `MessageComponentInteraction` and `ModalSubmitInteraction`.
1223///
1224/// # The order of responses
1225///
1226/// Nothing is tracked locally (D-248): the rules are Discord's, and Discord rejects a request
1227/// that breaks them.
1228///
1229/// 1. **Within 3 seconds**, exactly one *initial response*:
1230/// - [`reply`](Self::reply) — a message (commands, components, modals);
1231/// - [`defer_reply`](Self::defer_reply) — "thinking…", the message comes later with
1232/// [`edit_reply`](Self::edit_reply);
1233/// - [`update`](Self::update) / [`defer_update`](Self::defer_update) — edit the message the
1234/// component is on, now or later (components, modals opened from one);
1235/// - [`show_modal`](Self::show_modal) — open a modal (commands, components);
1236/// - [`respond`](Self::respond) — autocomplete suggestions (autocomplete only);
1237/// - [`launch_activity`](Self::launch_activity) — start the app's Activity.
1238///
1239/// A second initial response fails with error `40060` ("Interaction has already been
1240/// acknowledged"); a late one with `10062` ("Unknown interaction").
1241/// 2. **For 15 minutes** after it, the interaction token allows
1242/// [`fetch_reply`](Self::fetch_reply), [`edit_reply`](Self::edit_reply),
1243/// [`delete_reply`](Self::delete_reply) and the follow-up messages
1244/// ([`follow_up`](Self::follow_up) and the `*_follow_up` methods).
1245///
1246/// These requests are authorized by the interaction token, not the bot token, and do not
1247/// count against the global rate limit. Messages they return are cached (D-233).
1248///
1249/// # Examples
1250///
1251/// ```no_run
1252/// # use djs_rs::prelude::*;
1253/// # let client = Client::builder("token").build();
1254/// client.on(Events::InteractionCreate, |ctx, interaction| async move {
1255/// let Some(command) = interaction.command() else {
1256/// return Ok(());
1257/// };
1258/// match command.name.as_str() {
1259/// "ping" => interaction.reply(&ctx, "Pong!").await?,
1260/// "slow" => {
1261/// interaction.defer_reply(&ctx, Default::default()).await?;
1262/// // … up to 15 minutes of work …
1263/// interaction.edit_reply(&ctx, "Done").await?;
1264/// }
1265/// _ => {}
1266/// }
1267/// Ok(())
1268/// });
1269/// ```
1270pub trait InteractionExt: sealed::Interaction {
1271 /// Responds with a message ([`ChannelMessageWithSource`](InteractionResponse::ChannelMessageWithSource));
1272 /// accepts anything that converts into [`MessageCallbackData`], such as `&str`. Set
1273 /// [`MessageFlags::EPHEMERAL`] in its `flags` for a message only the user sees.
1274 ///
1275 /// An initial response (see [the order of responses](InteractionExt#the-order-of-responses)).
1276 ///
1277 /// discord.js counterpart: `reply`.
1278 ///
1279 /// # Errors
1280 ///
1281 /// Returns the REST error if the request failed.
1282 fn reply<B: Backend>(
1283 &self,
1284 ctx: &Context<B>,
1285 body: impl Into<MessageCallbackData>,
1286 ) -> impl Future<Output = Result<(), Error>> + Send {
1287 let response = InteractionResponse::ChannelMessageWithSource(Box::new(body.into()));
1288 callback(ctx, self.interaction_parts(), response)
1289 }
1290
1291 /// Acknowledges the interaction and shows "thinking…"
1292 /// ([`DeferredChannelMessageWithSource`](InteractionResponse::DeferredChannelMessageWithSource));
1293 /// the message follows with [`edit_reply`](Self::edit_reply). `flags` can only be
1294 /// [`MessageFlags::EPHEMERAL`] (for an ephemeral message) or empty.
1295 ///
1296 /// An initial response (see [the order of responses](InteractionExt#the-order-of-responses)).
1297 ///
1298 /// discord.js counterpart: `deferReply`.
1299 ///
1300 /// # Errors
1301 ///
1302 /// Returns the REST error if the request failed.
1303 fn defer_reply<B: Backend>(
1304 &self,
1305 ctx: &Context<B>,
1306 flags: MessageFlags,
1307 ) -> impl Future<Output = Result<(), Error>> + Send {
1308 let response =
1309 InteractionResponse::DeferredChannelMessageWithSource(DeferredCallbackData::new(flags));
1310 callback(ctx, self.interaction_parts(), response)
1311 }
1312
1313 /// Edits the message the component is on
1314 /// ([`UpdateMessage`](InteractionResponse::UpdateMessage)): fields left `None` keep their
1315 /// value. Component interactions and modals opened from a component.
1316 ///
1317 /// An initial response (see [the order of responses](InteractionExt#the-order-of-responses)).
1318 ///
1319 /// discord.js counterpart: `update`.
1320 ///
1321 /// # Errors
1322 ///
1323 /// Returns the REST error if the request failed.
1324 fn update<B: Backend>(
1325 &self,
1326 ctx: &Context<B>,
1327 body: impl Into<MessageCallbackData>,
1328 ) -> impl Future<Output = Result<(), Error>> + Send {
1329 let response = InteractionResponse::UpdateMessage(Box::new(body.into()));
1330 callback(ctx, self.interaction_parts(), response)
1331 }
1332
1333 /// Acknowledges a component interaction without a loading state
1334 /// ([`DeferredUpdateMessage`](InteractionResponse::DeferredUpdateMessage)); the message
1335 /// can be edited later with [`edit_reply`](Self::edit_reply).
1336 ///
1337 /// An initial response (see [the order of responses](InteractionExt#the-order-of-responses)).
1338 ///
1339 /// discord.js counterpart: `deferUpdate`.
1340 ///
1341 /// # Errors
1342 ///
1343 /// Returns the REST error if the request failed.
1344 fn defer_update<B: Backend>(
1345 &self,
1346 ctx: &Context<B>,
1347 ) -> impl Future<Output = Result<(), Error>> + Send {
1348 callback(
1349 ctx,
1350 self.interaction_parts(),
1351 InteractionResponse::DeferredUpdateMessage,
1352 )
1353 }
1354
1355 /// Opens a modal ([`Modal`](InteractionResponse::Modal)), for example one built with
1356 /// `djs_builders::ModalBuilder`. Its submission arrives as a new interaction. Not for
1357 /// modal-submit and autocomplete interactions.
1358 ///
1359 /// An initial response (see [the order of responses](InteractionExt#the-order-of-responses)).
1360 ///
1361 /// discord.js counterpart: `showModal`.
1362 ///
1363 /// # Errors
1364 ///
1365 /// Returns the REST error if the request failed.
1366 fn show_modal<B: Backend>(
1367 &self,
1368 ctx: &Context<B>,
1369 modal: ModalCallbackData,
1370 ) -> impl Future<Output = Result<(), Error>> + Send {
1371 let response = InteractionResponse::Modal(Box::new(modal));
1372 callback(ctx, self.interaction_parts(), response)
1373 }
1374
1375 /// Suggests choices for the option being typed in an autocomplete interaction
1376 /// ([`AutocompleteResult`](InteractionResponse::AutocompleteResult)); up to 25, typed like
1377 /// the option. An empty list shows "no suggestions".
1378 ///
1379 /// An initial response (see [the order of responses](InteractionExt#the-order-of-responses)).
1380 ///
1381 /// discord.js counterpart: `AutocompleteInteraction#respond`.
1382 ///
1383 /// # Errors
1384 ///
1385 /// Returns the REST error if the request failed.
1386 fn respond<B: Backend>(
1387 &self,
1388 ctx: &Context<B>,
1389 choices: AutocompleteChoices,
1390 ) -> impl Future<Output = Result<(), Error>> + Send {
1391 let response =
1392 InteractionResponse::AutocompleteResult(AutocompleteCallbackData::new(choices));
1393 callback(ctx, self.interaction_parts(), response)
1394 }
1395
1396 /// Launches the app's Activity ([`LaunchActivity`](InteractionResponse::LaunchActivity);
1397 /// apps with Activities enabled).
1398 ///
1399 /// An initial response (see [the order of responses](InteractionExt#the-order-of-responses)).
1400 ///
1401 /// discord.js counterpart: `launchActivity`.
1402 ///
1403 /// # Errors
1404 ///
1405 /// Returns the REST error if the request failed.
1406 fn launch_activity<B: Backend>(
1407 &self,
1408 ctx: &Context<B>,
1409 ) -> impl Future<Output = Result<(), Error>> + Send {
1410 callback(
1411 ctx,
1412 self.interaction_parts(),
1413 InteractionResponse::LaunchActivity,
1414 )
1415 }
1416
1417 /// The message of the initial response
1418 /// ([Get Original Interaction Response](djs_rest::Rest::get_original_interaction_response)).
1419 ///
1420 /// discord.js counterpart: `fetchReply`.
1421 ///
1422 /// # Errors
1423 ///
1424 /// Returns the REST error if the request failed (for example before an initial response).
1425 fn fetch_reply<B: Backend>(
1426 &self,
1427 ctx: &Context<B>,
1428 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
1429 let (_, application_id, token) = self.interaction_parts();
1430 async move {
1431 let message = ctx
1432 .rest()
1433 .get_original_interaction_response(application_id, token)
1434 .await?;
1435 Ok(ctx.store_message(&message))
1436 }
1437 }
1438
1439 /// Edits the message of the initial response — also how the message of a
1440 /// [`defer_reply`](Self::defer_reply) is sent, and how a
1441 /// [`defer_update`](Self::defer_update)d message is edited
1442 /// ([Edit Original Interaction Response](djs_rest::Rest::edit_original_interaction_response)).
1443 /// Accepts anything that converts into an [`EditWebhookMessage`], such as `&str`.
1444 ///
1445 /// discord.js counterpart: `editReply`.
1446 ///
1447 /// # Errors
1448 ///
1449 /// Returns the REST error if the request failed.
1450 fn edit_reply<B: Backend>(
1451 &self,
1452 ctx: &Context<B>,
1453 body: impl Into<EditWebhookMessage>,
1454 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
1455 let (_, application_id, token) = self.interaction_parts();
1456 let body = body.into();
1457 async move {
1458 let message = ctx
1459 .rest()
1460 .edit_original_interaction_response(application_id, token, &body)
1461 .await?;
1462 Ok(ctx.store_message(&message))
1463 }
1464 }
1465
1466 /// Deletes the message of the initial response
1467 /// ([Delete Original Interaction Response](djs_rest::Rest::delete_original_interaction_response)).
1468 ///
1469 /// discord.js counterpart: `deleteReply`.
1470 ///
1471 /// # Errors
1472 ///
1473 /// Returns the REST error if the request failed.
1474 fn delete_reply<B: Backend>(
1475 &self,
1476 ctx: &Context<B>,
1477 ) -> impl Future<Output = Result<(), Error>> + Send {
1478 let (_, application_id, token) = self.interaction_parts();
1479 async move {
1480 ctx.rest()
1481 .delete_original_interaction_response(application_id, token)
1482 .await
1483 }
1484 }
1485
1486 /// Sends another message for the interaction
1487 /// ([Create Followup Message](djs_rest::Rest::create_followup_message)); accepts anything
1488 /// that converts into a [`CreateFollowupMessage`], such as `&str`. After a
1489 /// [`defer_reply`](Self::defer_reply), the first follow-up replaces "thinking…".
1490 ///
1491 /// discord.js counterpart: `followUp`.
1492 ///
1493 /// # Errors
1494 ///
1495 /// Returns the REST error if the request failed (`40094` after the 5 follow-ups an app
1496 /// installed only for the user may send).
1497 fn follow_up<B: Backend>(
1498 &self,
1499 ctx: &Context<B>,
1500 body: impl Into<CreateFollowupMessage>,
1501 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
1502 let (_, application_id, token) = self.interaction_parts();
1503 let body = body.into();
1504 async move {
1505 let message = ctx
1506 .rest()
1507 .create_followup_message(application_id, token, &body)
1508 .await?;
1509 Ok(ctx.store_message(&message))
1510 }
1511 }
1512
1513 /// A follow-up message ([Get Followup Message](djs_rest::Rest::get_followup_message)).
1514 ///
1515 /// discord.js counterpart: `fetchReply` with a message ID.
1516 ///
1517 /// # Errors
1518 ///
1519 /// Returns the REST error if the request failed.
1520 fn fetch_follow_up<B: Backend>(
1521 &self,
1522 ctx: &Context<B>,
1523 message_id: MessageId,
1524 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
1525 let (_, application_id, token) = self.interaction_parts();
1526 async move {
1527 let message = ctx
1528 .rest()
1529 .get_followup_message(application_id, token, message_id)
1530 .await?;
1531 Ok(ctx.store_message(&message))
1532 }
1533 }
1534
1535 /// Edits a follow-up message ([Edit Followup Message](djs_rest::Rest::edit_followup_message));
1536 /// accepts anything that converts into an [`EditWebhookMessage`], such as `&str`.
1537 ///
1538 /// discord.js counterpart: `editReply` with a message ID.
1539 ///
1540 /// # Errors
1541 ///
1542 /// Returns the REST error if the request failed.
1543 fn edit_follow_up<B: Backend>(
1544 &self,
1545 ctx: &Context<B>,
1546 message_id: MessageId,
1547 body: impl Into<EditWebhookMessage>,
1548 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send {
1549 let (_, application_id, token) = self.interaction_parts();
1550 let body = body.into();
1551 async move {
1552 let message = ctx
1553 .rest()
1554 .edit_followup_message(application_id, token, message_id, &body)
1555 .await?;
1556 Ok(ctx.store_message(&message))
1557 }
1558 }
1559
1560 /// Deletes a follow-up message
1561 /// ([Delete Followup Message](djs_rest::Rest::delete_followup_message)).
1562 ///
1563 /// discord.js counterpart: `deleteReply` with a message ID.
1564 ///
1565 /// # Errors
1566 ///
1567 /// Returns the REST error if the request failed.
1568 fn delete_follow_up<B: Backend>(
1569 &self,
1570 ctx: &Context<B>,
1571 message_id: MessageId,
1572 ) -> impl Future<Output = Result<(), Error>> + Send {
1573 let (_, application_id, token) = self.interaction_parts();
1574 async move {
1575 ctx.rest()
1576 .delete_followup_message(application_id, token, message_id)
1577 .await
1578 }
1579 }
1580
1581 /// A collector of the component interactions on this interaction's reply (and its
1582 /// follow-ups), matched by the interaction they belong to: no need to fetch the reply.
1583 /// For a component interaction (whose response edits its message), the components of
1584 /// that message.
1585 ///
1586 /// It ends at its limits, or when the reply, its channel, thread or guild is deleted.
1587 ///
1588 /// discord.js counterpart: `InteractionResponse#createMessageComponentCollector`.
1589 ///
1590 /// # Examples
1591 ///
1592 /// ```no_run
1593 /// # use std::time::Duration;
1594 /// # use djs_rs::prelude::*;
1595 /// # let client = Client::builder("token").build();
1596 /// client.command("counter", |ctx, cmd| async move {
1597 /// cmd.reply(&ctx, "Count: 0").await?; // with a "+1" button
1598 /// let mut clicks = cmd.component_collector(&ctx).time(Duration::from_secs(300)).build();
1599 /// let mut count = 0;
1600 /// while let Some(click) = clicks.next().await {
1601 /// count += 1;
1602 /// click.update(&ctx, format!("Count: {count}")).await?;
1603 /// }
1604 /// Ok(())
1605 /// });
1606 /// ```
1607 fn component_collector<B: Backend>(
1608 &self,
1609 ctx: &Context<B>,
1610 ) -> CollectorBuilder<ComponentInteraction> {
1611 let interaction = self.interaction();
1612 CollectorBuilder::new(
1613 ctx,
1614 reply_key(interaction),
1615 interaction.guild_id,
1616 interaction.channel_id,
1617 )
1618 }
1619
1620 /// Waits for one component interaction on this interaction's reply (D-268); set a
1621 /// [`time`](CollectorBuilder::time).
1622 ///
1623 /// discord.js counterpart: `InteractionResponse#awaitMessageComponent`.
1624 ///
1625 /// # Errors
1626 ///
1627 /// [`CollectorError`](crate::collector::CollectorError) with the reason if the collector
1628 /// ended first.
1629 fn await_component<B: Backend>(
1630 &self,
1631 ctx: &Context<B>,
1632 ) -> CollectorBuilder<ComponentInteraction, mode::First> {
1633 let interaction = self.interaction();
1634 CollectorBuilder::new(
1635 ctx,
1636 reply_key(interaction),
1637 interaction.guild_id,
1638 interaction.channel_id,
1639 )
1640 }
1641
1642 /// Waits up to `time` for the user of this interaction to submit a modal (D-268), usually
1643 /// the one shown with [`show_modal`](Self::show_modal). Add a
1644 /// [`filter`](CollectorBuilder::filter) on the modal's `custom_id` when several can be
1645 /// open. `time` is required, as in discord.js: a closed modal sends nothing.
1646 ///
1647 /// discord.js counterpart: `awaitModalSubmit`.
1648 ///
1649 /// # Errors
1650 ///
1651 /// [`CollectorError`](crate::collector::CollectorError) with
1652 /// [`EndReason::Time`](crate::collector::EndReason::Time) if nothing was submitted in time.
1653 ///
1654 /// # Examples
1655 ///
1656 /// ```no_run
1657 /// # use std::time::Duration;
1658 /// # use djs_rs::prelude::*;
1659 /// # let client = Client::builder("token").build();
1660 /// client.command("feedback", |ctx, cmd| async move {
1661 /// // cmd.show_modal(&ctx, …) with a text input "text" in the modal "feedback"
1662 /// let submitted = cmd
1663 /// .await_modal_submit(&ctx, Duration::from_secs(300))
1664 /// .filter(|modal| modal.custom_id == "feedback")
1665 /// .await?;
1666 /// let text = submitted.text_value("text").unwrap_or_default();
1667 /// submitted.reply(&ctx, format!("Thanks for: {text}")).await?;
1668 /// Ok(())
1669 /// });
1670 /// ```
1671 fn await_modal_submit<B: Backend>(
1672 &self,
1673 ctx: &Context<B>,
1674 time: Duration,
1675 ) -> CollectorBuilder<ModalInteraction, mode::First> {
1676 let interaction = self.interaction();
1677 // Every interaction a bot receives has a user; the fallback matches no one.
1678 let user = interaction
1679 .author()
1680 .map_or(UserId::new(u64::MAX), |user| user.id);
1681 CollectorBuilder::new(ctx, Key::User(user), interaction.guild_id, None).time(time)
1682 }
1683}
1684
1685impl InteractionExt for Interaction {}
1686impl InteractionExt for crate::router::CommandInteraction {}
1687impl InteractionExt for crate::router::AutocompleteInteraction {}
1688impl InteractionExt for crate::router::ComponentInteraction {}
1689impl InteractionExt for crate::router::ModalInteraction {}
1690
1691/// What identifies the components of an interaction's reply: the interaction itself, or for a
1692/// component interaction its message (discord.js does the same in `update`).
1693fn reply_key(interaction: &Interaction) -> Key {
1694 match &interaction.message {
1695 Some(message) => Key::Message(message.id),
1696 None => Key::Interaction(interaction.id),
1697 }
1698}
1699
1700/// Sends the initial response `response` (Create Interaction Response).
1701async fn callback<B: Backend>(
1702 ctx: &Context<B>,
1703 (interaction_id, _, token): (InteractionId, ApplicationId, &str),
1704 response: InteractionResponse,
1705) -> Result<(), Error> {
1706 // An HTTP interaction's first response goes in the HTTP body (D-399).
1707 #[cfg(feature = "http-interactions")]
1708 if let Some(initial) = ctx.core().take_inline(interaction_id) {
1709 return crate::http_interactions::respond(
1710 ctx.rest(),
1711 initial,
1712 interaction_id,
1713 token,
1714 &response,
1715 )
1716 .await;
1717 }
1718 ctx.rest()
1719 .create_interaction_response(interaction_id, token, &response)
1720 .await
1721}
1722
1723/// The IDs the extension traits need; sealed so the traits stay implementable only here.
1724mod sealed {
1725 use super::{ApplicationId, ChannelId, GuildId, InteractionId, MessageId, UserId, WebhookId};
1726
1727 pub trait Interaction {
1728 /// The interaction's ID, its application and its token.
1729 fn interaction_parts(&self) -> (InteractionId, ApplicationId, &str);
1730
1731 /// The whole interaction.
1732 fn interaction(&self) -> &djs_model::interaction::Interaction;
1733 }
1734
1735 impl Interaction for djs_model::interaction::Interaction {
1736 fn interaction_parts(&self) -> (InteractionId, ApplicationId, &str) {
1737 (self.id, self.application_id, &self.token)
1738 }
1739
1740 fn interaction(&self) -> &Self {
1741 self
1742 }
1743 }
1744
1745 /// The router's wrappers (D-252) answer for their interaction.
1746 macro_rules! wrapped {
1747 ($($wrapper:ident),*) => {$(
1748 impl Interaction for crate::router::$wrapper {
1749 fn interaction_parts(&self) -> (InteractionId, ApplicationId, &str) {
1750 crate::router::$wrapper::interaction(self).interaction_parts()
1751 }
1752
1753 fn interaction(&self) -> &djs_model::interaction::Interaction {
1754 crate::router::$wrapper::interaction(self)
1755 }
1756 }
1757 )*};
1758 }
1759
1760 wrapped!(
1761 CommandInteraction,
1762 AutocompleteInteraction,
1763 ComponentInteraction,
1764 ModalInteraction
1765 );
1766
1767 pub trait Message {
1768 /// The channel and the message.
1769 fn ids(&self) -> (ChannelId, MessageId);
1770
1771 /// The guild, if the message is in one and its data says so.
1772 fn guild(&self) -> Option<GuildId>;
1773 }
1774
1775 impl Message for djs_model::message::Message {
1776 fn ids(&self) -> (ChannelId, MessageId) {
1777 (self.channel_id, self.id)
1778 }
1779
1780 fn guild(&self) -> Option<GuildId> {
1781 self.guild_id
1782 }
1783 }
1784
1785 impl Message for djs_cache::CachedMessage {
1786 fn ids(&self) -> (ChannelId, MessageId) {
1787 (self.channel_id, self.id)
1788 }
1789
1790 fn guild(&self) -> Option<GuildId> {
1791 self.guild_id
1792 }
1793 }
1794
1795 pub trait Channel {
1796 fn channel_id(&self) -> ChannelId;
1797 }
1798
1799 impl Channel for djs_model::channel::Channel {
1800 fn channel_id(&self) -> ChannelId {
1801 self.id()
1802 }
1803 }
1804
1805 pub trait User {
1806 fn user_id(&self) -> UserId;
1807 }
1808
1809 impl User for djs_model::user::User {
1810 fn user_id(&self) -> UserId {
1811 self.id
1812 }
1813 }
1814
1815 impl User for djs_cache::CachedUser {
1816 fn user_id(&self) -> UserId {
1817 self.id
1818 }
1819 }
1820
1821 pub trait Member {
1822 /// The guild and the user.
1823 fn ids(&self) -> (GuildId, UserId);
1824 }
1825
1826 impl Member for djs_cache::CachedMember {
1827 fn ids(&self) -> (GuildId, UserId) {
1828 (self.guild_id, self.user.id)
1829 }
1830 }
1831
1832 impl Member for djs_model::gateway::payload::GuildMemberAdd {
1833 fn ids(&self) -> (GuildId, UserId) {
1834 (self.guild_id, self.member.user.id)
1835 }
1836 }
1837
1838 impl Member for djs_model::gateway::payload::GuildMemberUpdate {
1839 fn ids(&self) -> (GuildId, UserId) {
1840 (self.guild_id, self.user.id)
1841 }
1842 }
1843
1844 pub trait Guild {
1845 fn guild_id(&self) -> GuildId;
1846 }
1847
1848 pub trait Webhook {
1849 /// The ID and the token, if the webhook has one.
1850 fn webhook_parts(&self) -> (WebhookId, Option<&str>);
1851 }
1852
1853 impl Webhook for djs_model::webhook::Webhook {
1854 fn webhook_parts(&self) -> (WebhookId, Option<&str>) {
1855 (self.id, self.token.as_deref())
1856 }
1857 }
1858
1859 impl Guild for djs_model::guild::Guild {
1860 fn guild_id(&self) -> GuildId {
1861 self.id
1862 }
1863 }
1864
1865 impl Guild for djs_cache::CachedGuild {
1866 fn guild_id(&self) -> GuildId {
1867 self.id
1868 }
1869 }
1870}