djs_model/interaction/getters.rs
1//! Typed getters over interaction data (D-250): command options by name and type, the
2//! selections of select menus and modals with their [`Resolved`] objects.
3//!
4//! Every getter returns `None` when the option or component is missing or of another type,
5//! so a handler can use `?` or `let … else`; nothing panics.
6//!
7//! discord.js counterpart: `CommandInteractionOptionResolver`, `ModalSubmitFields` and the
8//! `users` / `members` / `roles` / `channels` of the select menu interactions.
9
10use compact_str::CompactString;
11
12use super::{
13 CommandData, CommandDataOption, CommandOptionValue, ComponentData, InteractionChannel,
14 InteractionMember, ModalSubmitData, Resolved, SubmittedComponent,
15};
16use crate::{
17 guild::Role,
18 id::{
19 AttachmentId, GenericId, Id, MessageId, RoleId, UserId,
20 marker::{ChannelMarker, RoleMarker, UserMarker},
21 },
22 message::{Attachment, Message},
23 user::User,
24};
25
26/// A user or a role chosen in a mentionable option or select menu, with its resolved data.
27///
28/// discord.js counterpart: the `User`, `GuildMember` or `Role` returned by
29/// `CommandInteractionOptionResolver#getMentionable`.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Mentionable<'a> {
33 /// A user.
34 User {
35 /// The user.
36 user: &'a User,
37 /// Their member data, when chosen in a guild.
38 member: Option<&'a InteractionMember>,
39 },
40 /// A role.
41 Role(&'a Role),
42}
43
44impl Mentionable<'_> {
45 /// Returns the ID of the user or role.
46 ///
47 /// discord.js counterpart: the ID `CommandInteractionOptionResolver#getMentionable` returns.
48 #[must_use]
49 pub const fn id(&self) -> GenericId {
50 match self {
51 Self::User { user, .. } => user.id.cast(),
52 Self::Role(role) => role.id.cast(),
53 }
54 }
55}
56
57/// The resolved objects by ID, unboxed (D-256).
58impl Resolved {
59 fn user(&self, id: UserId) -> Option<&User> {
60 self.users.get(&id).map(|user| &**user)
61 }
62
63 fn member(&self, id: UserId) -> Option<&InteractionMember> {
64 self.members.get(&id).map(|member| &**member)
65 }
66
67 fn role(&self, id: RoleId) -> Option<&Role> {
68 self.roles.get(&id).map(|role| &**role)
69 }
70
71 fn channel(&self, id: Id<ChannelMarker>) -> Option<&InteractionChannel> {
72 self.channels.get(&id).map(|channel| &**channel)
73 }
74
75 fn message(&self, id: MessageId) -> Option<&Message> {
76 self.messages.get(&id).map(|message| &**message)
77 }
78
79 fn attachment(&self, id: AttachmentId) -> Option<&Attachment> {
80 self.attachments.get(&id).map(|attachment| &**attachment)
81 }
82}
83
84/// The resolved user `id` and their member data, if both are present.
85fn user_and_member(resolved: Option<&Resolved>, id: UserId) -> Option<(&User, &InteractionMember)> {
86 let resolved = resolved?;
87 Some((resolved.user(id)?, resolved.member(id)?))
88}
89
90/// The resolved user or role `id`.
91fn mentionable(resolved: Option<&Resolved>, id: GenericId) -> Option<Mentionable<'_>> {
92 let resolved = resolved?;
93 if let Some(user) = resolved.user(id.cast()) {
94 return Some(Mentionable::User {
95 user,
96 member: resolved.member(id.cast()),
97 });
98 }
99 resolved.role(id.cast()).map(Mentionable::Role)
100}
101
102/// The subcommand option among `options` (a subcommand is always the only option).
103fn subcommand_option(options: &[CommandDataOption]) -> Option<&CommandDataOption> {
104 match options {
105 [
106 option @ CommandDataOption {
107 value: CommandOptionValue::SubCommand(_),
108 ..
109 },
110 ] => Some(option),
111 _ => None,
112 }
113}
114
115/// Reads command options by name and type (D-250).
116///
117/// The getters look at the options of the subcommand that was run ([`leaf_options`]), so
118/// `get_string("reason")` works the same for `/ban reason:…` and `/mod ban reason:…`. User,
119/// member, role, channel and attachment getters return the [`resolved`](Self::resolved)
120/// object behind the option's ID.
121///
122/// # Examples
123///
124/// ```
125/// use djs_model::interaction::Interaction;
126///
127/// # let json = r#"{"id":"1","application_id":"2","type":2,"token":"t","version":1,
128/// # "data":{"id":"3","name":"mod","type":1,"options":[{"name":"warn","type":1,"options":[
129/// # {"name":"reason","type":3,"value":"spam"},{"name":"days","type":4,"value":7}]}]}}"#;
130/// // `/mod warn reason:spam days:7`
131/// let interaction: Interaction = serde_json::from_str(json).unwrap();
132/// let data = interaction.command().unwrap();
133/// assert_eq!(data.subcommand(), Some("warn"));
134/// assert_eq!(data.get_string("reason"), Some("spam"));
135/// assert_eq!(data.get_integer("days"), Some(7));
136/// assert_eq!(data.get_boolean("silent"), None); // not filled in
137/// assert_eq!(data.get_string("days"), None); // another type
138/// ```
139///
140/// [`leaf_options`]: Self::leaf_options
141impl CommandData {
142 /// Returns the options of the subcommand that was run, or the command's own options if it
143 /// has no subcommands: the options every getter searches.
144 ///
145 /// discord.js counterpart: the hoisted options of `CommandInteractionOptionResolver`.
146 #[must_use]
147 pub fn leaf_options(&self) -> &[CommandDataOption] {
148 let mut options = self.options.as_slice();
149 while let [
150 CommandDataOption {
151 value:
152 CommandOptionValue::SubCommandGroup(inner) | CommandOptionValue::SubCommand(inner),
153 ..
154 },
155 ] = options
156 {
157 options = inner;
158 }
159 options
160 }
161
162 /// Returns the name of the subcommand that was run (also inside a group).
163 ///
164 /// discord.js counterpart: `CommandInteractionOptionResolver#getSubcommand`.
165 #[must_use]
166 pub fn subcommand(&self) -> Option<&str> {
167 let option =
168 subcommand_option(&self.options).or_else(|| match self.options.as_slice() {
169 [
170 CommandDataOption {
171 value: CommandOptionValue::SubCommandGroup(inner),
172 ..
173 },
174 ] => subcommand_option(inner),
175 _ => None,
176 })?;
177 Some(&option.name)
178 }
179
180 /// Returns the name of the subcommand group of the subcommand that was run.
181 ///
182 /// discord.js counterpart: `CommandInteractionOptionResolver#getSubcommandGroup`.
183 #[must_use]
184 pub fn subcommand_group(&self) -> Option<&str> {
185 match self.options.as_slice() {
186 [
187 CommandDataOption {
188 name,
189 value: CommandOptionValue::SubCommandGroup(_),
190 },
191 ] => Some(name),
192 _ => None,
193 }
194 }
195
196 /// Returns the value of the option `name` (among the [`leaf_options`](Self::leaf_options)),
197 /// whatever its type.
198 ///
199 /// discord.js counterpart: `CommandInteractionOptionResolver#get`.
200 #[must_use]
201 pub fn get(&self, name: &str) -> Option<&CommandOptionValue> {
202 self.leaf_options()
203 .iter()
204 .find(|option| option.name == name)
205 .map(|option| &option.value)
206 }
207
208 /// Returns the value of the string option `name`.
209 ///
210 /// discord.js counterpart: `CommandInteractionOptionResolver#getString`.
211 #[must_use]
212 pub fn get_string(&self, name: &str) -> Option<&str> {
213 match self.get(name)? {
214 CommandOptionValue::String(value) => Some(value),
215 _ => None,
216 }
217 }
218
219 /// Returns the value of the integer option `name`.
220 ///
221 /// discord.js counterpart: `CommandInteractionOptionResolver#getInteger`.
222 #[must_use]
223 pub fn get_integer(&self, name: &str) -> Option<i64> {
224 match self.get(name)? {
225 CommandOptionValue::Integer(value) => Some(*value),
226 _ => None,
227 }
228 }
229
230 /// Returns the value of the number (floating-point) option `name`.
231 ///
232 /// discord.js counterpart: `CommandInteractionOptionResolver#getNumber`.
233 #[must_use]
234 pub fn get_number(&self, name: &str) -> Option<f64> {
235 match self.get(name)? {
236 CommandOptionValue::Number(value) => Some(*value),
237 _ => None,
238 }
239 }
240
241 /// Returns the value of the boolean option `name`.
242 ///
243 /// discord.js counterpart: `CommandInteractionOptionResolver#getBoolean`.
244 #[must_use]
245 pub fn get_boolean(&self, name: &str) -> Option<bool> {
246 match self.get(name)? {
247 CommandOptionValue::Boolean(value) => Some(*value),
248 _ => None,
249 }
250 }
251
252 /// The user ID of the user or mentionable option `name`.
253 fn user_id(&self, name: &str) -> Option<UserId> {
254 match self.get(name)? {
255 CommandOptionValue::User(id) => Some(*id),
256 CommandOptionValue::Mentionable(id) => Some(id.cast()),
257 _ => None,
258 }
259 }
260
261 /// Returns the user chosen in the user (or mentionable) option `name`.
262 ///
263 /// discord.js counterpart: `CommandInteractionOptionResolver#getUser`.
264 #[must_use]
265 pub fn get_user(&self, name: &str) -> Option<&User> {
266 self.resolved.as_deref()?.user(self.user_id(name)?)
267 }
268
269 /// Returns the user chosen in the user (or mentionable) option `name` with their member
270 /// data; `None` outside guilds or if the user is not a member.
271 ///
272 /// discord.js counterpart: `CommandInteractionOptionResolver#getMember`.
273 #[must_use]
274 pub fn get_member(&self, name: &str) -> Option<(&User, &InteractionMember)> {
275 user_and_member(self.resolved.as_deref(), self.user_id(name)?)
276 }
277
278 /// Returns the role chosen in the role (or mentionable) option `name`.
279 ///
280 /// discord.js counterpart: `CommandInteractionOptionResolver#getRole`.
281 #[must_use]
282 pub fn get_role(&self, name: &str) -> Option<&Role> {
283 let id: RoleId = match self.get(name)? {
284 CommandOptionValue::Role(id) => *id,
285 CommandOptionValue::Mentionable(id) => id.cast(),
286 _ => return None,
287 };
288 self.resolved.as_deref()?.role(id)
289 }
290
291 /// Returns the channel chosen in the channel option `name` (a partial channel with the
292 /// invoking member's permissions in it).
293 ///
294 /// discord.js counterpart: `CommandInteractionOptionResolver#getChannel`.
295 #[must_use]
296 pub fn get_channel(&self, name: &str) -> Option<&InteractionChannel> {
297 let CommandOptionValue::Channel(id) = self.get(name)? else {
298 return None;
299 };
300 self.resolved.as_deref()?.channel(*id)
301 }
302
303 /// Returns the file uploaded in the attachment option `name`.
304 ///
305 /// discord.js counterpart: `CommandInteractionOptionResolver#getAttachment`.
306 #[must_use]
307 pub fn get_attachment(&self, name: &str) -> Option<&Attachment> {
308 let CommandOptionValue::Attachment(id) = self.get(name)? else {
309 return None;
310 };
311 self.resolved.as_deref()?.attachment(*id)
312 }
313
314 /// Returns the user or role chosen in the mentionable option `name`.
315 ///
316 /// discord.js counterpart: `CommandInteractionOptionResolver#getMentionable`.
317 #[must_use]
318 pub fn get_mentionable(&self, name: &str) -> Option<Mentionable<'_>> {
319 let CommandOptionValue::Mentionable(id) = self.get(name)? else {
320 return None;
321 };
322 mentionable(self.resolved.as_deref(), *id)
323 }
324
325 /// Returns what the user has typed so far in the [`focused`](Self::focused) option of an
326 /// autocomplete interaction.
327 ///
328 /// discord.js counterpart: `CommandInteractionOptionResolver#getFocused`.
329 #[must_use]
330 pub fn focused_value(&self) -> Option<&str> {
331 match &self.focused()?.value {
332 CommandOptionValue::Focused { value, .. } => Some(value),
333 _ => None,
334 }
335 }
336
337 /// Returns the user a user command was used on.
338 ///
339 /// discord.js counterpart: `UserContextMenuCommandInteraction#targetUser`.
340 #[must_use]
341 pub fn target_user(&self) -> Option<&User> {
342 self.resolved.as_deref()?.user(self.target_id?.cast())
343 }
344
345 /// Returns the user a user command was used on with their member data (in guilds).
346 ///
347 /// discord.js counterpart: `UserContextMenuCommandInteraction#targetMember`.
348 #[must_use]
349 pub fn target_member(&self) -> Option<(&User, &InteractionMember)> {
350 user_and_member(self.resolved.as_deref(), self.target_id?.cast())
351 }
352
353 /// Returns the message a message command was used on.
354 ///
355 /// discord.js counterpart: `MessageContextMenuCommandInteraction#targetMessage`.
356 #[must_use]
357 pub fn target_message(&self) -> Option<&Message> {
358 self.resolved.as_deref()?.message(self.target_id?.cast())
359 }
360}
361
362/// The selections of entity select menus with their resolved objects (D-250), in the order
363/// of [`values`](Self::values).
364///
365/// In a mentionable select menu, [`users`](Self::users) and [`roles`](Self::roles) each
366/// return their part of the selection.
367impl ComponentData {
368 /// Returns the users chosen in a user or mentionable select menu.
369 ///
370 /// discord.js counterpart: `UserSelectMenuInteraction#users`.
371 pub fn users(&self) -> impl Iterator<Item = &User> + '_ {
372 let resolved = self.resolved.as_deref();
373 self.ids::<UserMarker>()
374 .filter_map(move |id| resolved?.user(id))
375 }
376
377 /// Returns the users chosen in a user or mentionable select menu in a guild, with their
378 /// member data.
379 ///
380 /// discord.js counterpart: `UserSelectMenuInteraction#members`.
381 pub fn members(&self) -> impl Iterator<Item = (&User, &InteractionMember)> + '_ {
382 let resolved = self.resolved.as_deref();
383 self.ids::<UserMarker>()
384 .filter_map(move |id| user_and_member(resolved, id))
385 }
386
387 /// Returns the roles chosen in a role or mentionable select menu.
388 ///
389 /// discord.js counterpart: `RoleSelectMenuInteraction#roles`.
390 pub fn roles(&self) -> impl Iterator<Item = &Role> + '_ {
391 let resolved = self.resolved.as_deref();
392 self.ids::<RoleMarker>()
393 .filter_map(move |id| resolved?.role(id))
394 }
395
396 /// Returns the channels chosen in a channel select menu.
397 ///
398 /// discord.js counterpart: `ChannelSelectMenuInteraction#channels`.
399 pub fn channels(&self) -> impl Iterator<Item = &InteractionChannel> + '_ {
400 let resolved = self.resolved.as_deref();
401 self.ids::<ChannelMarker>()
402 .filter_map(move |id| resolved?.channel(id))
403 }
404
405 /// Returns the users and roles chosen in a mentionable select menu.
406 ///
407 /// discord.js counterpart: `MentionableSelectMenuInteraction` (`users`, `members`,
408 /// `roles`).
409 pub fn mentionables(&self) -> impl Iterator<Item = Mentionable<'_>> + '_ {
410 let resolved = self.resolved.as_deref();
411 self.ids().filter_map(move |id| mentionable(resolved, id))
412 }
413}
414
415/// Reads submitted modal fields by custom ID and component type (D-250); see also
416/// [`get`](Self::get) and [`text_value`](Self::text_value).
417///
418/// Each getter returns `None` when no component has the custom ID or it is of another type;
419/// the `selected_*` getters return the [`resolved`](Self::resolved) objects in the order they
420/// were selected.
421///
422/// discord.js counterpart: `ModalSubmitFields`.
423impl ModalSubmitData {
424 /// Returns the values chosen in the string select menu `custom_id`.
425 ///
426 /// discord.js counterpart: `ModalSubmitFields#getStringSelectValues`.
427 #[must_use]
428 pub fn string_select_values(&self, custom_id: &str) -> Option<&[CompactString]> {
429 match self.get(custom_id)? {
430 SubmittedComponent::StringSelect(select) => Some(&select.values),
431 _ => None,
432 }
433 }
434
435 /// Returns the values of the checked boxes of the checkbox group `custom_id`.
436 ///
437 /// discord.js counterpart: `ModalSubmitFields#getCheckboxGroup`.
438 #[must_use]
439 pub fn checkbox_group_values(&self, custom_id: &str) -> Option<&[CompactString]> {
440 match self.get(custom_id)? {
441 SubmittedComponent::CheckboxGroup(group) => Some(&group.values),
442 _ => None,
443 }
444 }
445
446 /// Returns the value chosen in the radio group `custom_id` (`None` also when nothing was
447 /// chosen).
448 ///
449 /// discord.js counterpart: `ModalSubmitFields#getRadioGroup`.
450 #[must_use]
451 pub fn radio_group_value(&self, custom_id: &str) -> Option<&str> {
452 match self.get(custom_id)? {
453 SubmittedComponent::RadioGroup(group) => group.value.as_deref(),
454 _ => None,
455 }
456 }
457
458 /// Returns whether the checkbox `custom_id` was checked.
459 ///
460 /// discord.js counterpart: `ModalSubmitFields#getCheckbox`.
461 #[must_use]
462 pub fn checkbox_value(&self, custom_id: &str) -> Option<bool> {
463 match self.get(custom_id)? {
464 SubmittedComponent::Checkbox(checkbox) => Some(checkbox.value),
465 _ => None,
466 }
467 }
468
469 /// The user IDs selected in the user or mentionable select menu `custom_id`.
470 fn user_ids<'a>(&'a self, custom_id: &str) -> Option<impl Iterator<Item = UserId> + use<'a>> {
471 let (users, mentionables): (&[UserId], &[GenericId]) = match self.get(custom_id)? {
472 SubmittedComponent::UserSelect(select) => (&select.values, &[]),
473 SubmittedComponent::MentionableSelect(select) => (&[], &select.values),
474 _ => return None,
475 };
476 Some(
477 users
478 .iter()
479 .copied()
480 .chain(mentionables.iter().map(|id| id.cast())),
481 )
482 }
483
484 /// Returns the users chosen in the user or mentionable select menu `custom_id`.
485 ///
486 /// discord.js counterpart: `ModalSubmitFields#getSelectedUsers`.
487 #[must_use]
488 pub fn selected_users<'a>(
489 &'a self,
490 custom_id: &str,
491 ) -> Option<impl Iterator<Item = &'a User> + use<'a>> {
492 let resolved = self.resolved.as_deref();
493 Some(
494 self.user_ids(custom_id)?
495 .filter_map(move |id| resolved?.user(id)),
496 )
497 }
498
499 /// Returns the users chosen in the user or mentionable select menu `custom_id`, with their
500 /// member data (in guilds).
501 ///
502 /// discord.js counterpart: `ModalSubmitFields#getSelectedMembers`.
503 #[must_use]
504 pub fn selected_members<'a>(
505 &'a self,
506 custom_id: &str,
507 ) -> Option<impl Iterator<Item = (&'a User, &'a InteractionMember)> + use<'a>> {
508 let resolved = self.resolved.as_deref();
509 Some(
510 self.user_ids(custom_id)?
511 .filter_map(move |id| user_and_member(resolved, id)),
512 )
513 }
514
515 /// Returns the roles chosen in the role or mentionable select menu `custom_id`.
516 ///
517 /// discord.js counterpart: `ModalSubmitFields#getSelectedRoles`.
518 #[must_use]
519 pub fn selected_roles<'a>(
520 &'a self,
521 custom_id: &str,
522 ) -> Option<impl Iterator<Item = &'a Role> + use<'a>> {
523 let (roles, mentionables): (&[RoleId], &[GenericId]) = match self.get(custom_id)? {
524 SubmittedComponent::RoleSelect(select) => (&select.values, &[]),
525 SubmittedComponent::MentionableSelect(select) => (&[], &select.values),
526 _ => return None,
527 };
528 let resolved = self.resolved.as_deref();
529 Some(
530 roles
531 .iter()
532 .copied()
533 .chain(mentionables.iter().map(|id| id.cast()))
534 .filter_map(move |id| resolved?.role(id)),
535 )
536 }
537
538 /// Returns the channels chosen in the channel select menu `custom_id`.
539 ///
540 /// discord.js counterpart: `ModalSubmitFields#getSelectedChannels`.
541 #[must_use]
542 pub fn selected_channels<'a>(
543 &'a self,
544 custom_id: &str,
545 ) -> Option<impl Iterator<Item = &'a InteractionChannel> + use<'a>> {
546 let SubmittedComponent::ChannelSelect(select) = self.get(custom_id)? else {
547 return None;
548 };
549 let resolved = self.resolved.as_deref();
550 Some(
551 select
552 .values
553 .iter()
554 .filter_map(move |id: &Id<ChannelMarker>| resolved?.channel(*id)),
555 )
556 }
557
558 /// Returns the users and roles chosen in the mentionable select menu `custom_id`.
559 ///
560 /// discord.js counterpart: `ModalSubmitFields#getSelectedMentionables`.
561 #[must_use]
562 pub fn selected_mentionables<'a>(
563 &'a self,
564 custom_id: &str,
565 ) -> Option<impl Iterator<Item = Mentionable<'a>> + use<'a>> {
566 let SubmittedComponent::MentionableSelect(select) = self.get(custom_id)? else {
567 return None;
568 };
569 let resolved = self.resolved.as_deref();
570 Some(
571 select
572 .values
573 .iter()
574 .filter_map(move |id| mentionable(resolved, *id)),
575 )
576 }
577
578 /// Returns the files uploaded in the file upload `custom_id`.
579 ///
580 /// discord.js counterpart: `ModalSubmitFields#getUploadedFiles`.
581 #[must_use]
582 pub fn uploaded_files<'a>(
583 &'a self,
584 custom_id: &str,
585 ) -> Option<impl Iterator<Item = &'a Attachment> + use<'a>> {
586 let SubmittedComponent::FileUpload(upload) = self.get(custom_id)? else {
587 return None;
588 };
589 let resolved = self.resolved.as_deref();
590 Some(
591 upload
592 .values
593 .iter()
594 .filter_map(move |id| resolved?.attachment(*id)),
595 )
596 }
597}