Skip to main content

djs_model/interaction/
data.rs

1//! The type-specific [`data`](super::Interaction::data) of interactions (D-067).
2
3use std::collections::BTreeMap;
4
5use compact_str::{CompactString, ToCompactString};
6use serde::{
7    Deserialize, Deserializer, Serialize, Serializer,
8    de::{Error as DeError, Unexpected, Visitor},
9};
10
11use super::{InteractionChannel, InteractionMember, InteractionType};
12use crate::{
13    application_command::{CommandOptionType, CommandType},
14    component::ComponentType,
15    guild::Role,
16    id::{
17        AttachmentId, ChannelId, CommandId, GenericId, GuildId, Id, MessageId, RoleId, UserId,
18        marker::{ChannelMarker, GenericMarker, RoleMarker, UserMarker},
19    },
20    message::{Attachment, Message},
21    user::User,
22};
23
24/// The [data](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-data)
25/// of an [`Interaction`](super::Interaction), by interaction type (D-067).
26///
27/// The variant decides the interaction's [`type`](super::Interaction::kind): it is decoded
28/// from `type` and `data` together and written back as both.
29///
30/// discord.js counterpart: the `data` of `APIInteraction` (discord-api-types).
31#[derive(Clone, Debug, PartialEq)]
32#[non_exhaustive]
33pub enum InteractionData {
34    /// Discord checks the app's HTTP interactions endpoint; answer with
35    /// [`InteractionResponse::Pong`](super::InteractionResponse::Pong).
36    Ping,
37    /// A user ran one of the app's commands.
38    ///
39    /// discord.js counterpart: `ChatInputCommandInteraction`, `UserContextMenuCommandInteraction`,
40    /// `MessageContextMenuCommandInteraction`, `PrimaryEntryPointCommandInteraction`.
41    ApplicationCommand(Box<CommandData>),
42    /// A user clicked a button or chose in a select menu on one of the app's messages.
43    ///
44    /// discord.js counterpart: `ButtonInteraction`, `StringSelectMenuInteraction` and the other
45    /// select menu interactions.
46    MessageComponent(Box<ComponentData>),
47    /// A user is typing an option with autocomplete; one option is
48    /// [`Focused`](CommandOptionValue::Focused).
49    ///
50    /// discord.js counterpart: `AutocompleteInteraction`.
51    Autocomplete(Box<CommandData>),
52    /// A user submitted one of the app's modals.
53    ///
54    /// discord.js counterpart: `ModalSubmitInteraction`.
55    ModalSubmit(Box<ModalSubmitData>),
56    /// An interaction type this version does not know; its data is not kept.
57    Unknown(InteractionType),
58}
59
60impl InteractionData {
61    /// Returns the interaction type this data belongs to.
62    ///
63    /// discord.js counterpart: `BaseInteraction#type`.
64    #[must_use]
65    pub const fn kind(&self) -> InteractionType {
66        match self {
67            Self::Ping => InteractionType::Ping,
68            Self::ApplicationCommand(_) => InteractionType::ApplicationCommand,
69            Self::MessageComponent(_) => InteractionType::MessageComponent,
70            Self::Autocomplete(_) => InteractionType::ApplicationCommandAutocomplete,
71            Self::ModalSubmit(_) => InteractionType::ModalSubmit,
72            Self::Unknown(kind) => *kind,
73        }
74    }
75
76    /// Returns the command data of command and autocomplete interactions (see
77    /// [`Interaction::command`](super::Interaction::command) and
78    /// [`Interaction::autocomplete`](super::Interaction::autocomplete) for one kind).
79    ///
80    /// discord.js counterpart: the command fields of `CommandInteraction`.
81    #[must_use]
82    pub fn command(&self) -> Option<&CommandData> {
83        match self {
84            Self::ApplicationCommand(data) | Self::Autocomplete(data) => Some(data),
85            _ => None,
86        }
87    }
88
89    /// Returns the custom ID of the component or modal (component and modal-submit
90    /// interactions).
91    ///
92    /// discord.js counterpart: `MessageComponentInteraction#customId` and `ModalSubmitInteraction#customId`.
93    #[must_use]
94    pub fn custom_id(&self) -> Option<&str> {
95        match self {
96            Self::MessageComponent(data) => Some(&data.custom_id),
97            Self::ModalSubmit(data) => Some(&data.custom_id),
98            _ => None,
99        }
100    }
101
102    /// Returns the resolved users, members, roles, channels, messages and attachments, if any.
103    ///
104    /// discord.js counterpart: `CommandInteractionOptionResolver#resolved`.
105    #[must_use]
106    pub fn resolved(&self) -> Option<&Resolved> {
107        match self {
108            Self::ApplicationCommand(data) | Self::Autocomplete(data) => data.resolved.as_deref(),
109            Self::MessageComponent(data) => data.resolved.as_deref(),
110            Self::ModalSubmit(data) => data.resolved.as_deref(),
111            Self::Ping | Self::Unknown(_) => None,
112        }
113    }
114
115    /// Borrows the data for serialization (`None` for pings and unknown types).
116    pub(super) fn as_ref(&self) -> Option<DataRef<'_>> {
117        match self {
118            Self::ApplicationCommand(data) | Self::Autocomplete(data) => {
119                Some(DataRef::Command(data))
120            }
121            Self::MessageComponent(data) => Some(DataRef::Component(data)),
122            Self::ModalSubmit(data) => Some(DataRef::ModalSubmit(data)),
123            Self::Ping | Self::Unknown(_) => None,
124        }
125    }
126}
127
128/// Borrowed data, written as the interaction's `data` object.
129#[derive(Serialize)]
130#[serde(untagged)]
131pub(super) enum DataRef<'a> {
132    Command(&'a CommandData),
133    Component(&'a ComponentData),
134    ModalSubmit(&'a ModalSubmitData),
135}
136
137/// The [data of a command interaction](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-application-command-data-structure)
138/// (and of an autocomplete interaction).
139///
140/// discord.js counterpart: the command fields of `CommandInteraction` (`commandId`,
141/// `commandName`, `commandType`, `options`).
142#[derive(Clone, Debug, PartialEq, Serialize)]
143#[non_exhaustive]
144pub struct CommandData {
145    /// The command's ID.
146    pub id: CommandId,
147    /// The command's name.
148    pub name: CompactString,
149    /// The command's type.
150    #[serde(rename = "type")]
151    pub kind: CommandType,
152    /// The users, members, roles, channels, messages and attachments the options refer to
153    /// (and the target of context menu commands).
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub resolved: Option<Box<Resolved>>,
156    /// The options the user filled in (in autocomplete interactions: possibly partial).
157    #[serde(skip_serializing_if = "Vec::is_empty")]
158    pub options: Vec<CommandDataOption>,
159    /// The guild the command is registered in (guild commands).
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub guild_id: Option<GuildId>,
162    /// The user or message a context menu command was used on (in [`resolved`](Self::resolved)).
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub target_id: Option<GenericId>,
165}
166
167impl CommandData {
168    /// Returns the option that is being typed in an autocomplete interaction, searching
169    /// subcommands and groups.
170    ///
171    /// discord.js counterpart: `CommandInteractionOptionResolver#getFocused`.
172    #[must_use]
173    pub fn focused(&self) -> Option<&CommandDataOption> {
174        fn find(options: &[CommandDataOption]) -> Option<&CommandDataOption> {
175            options.iter().find_map(|option| match &option.value {
176                CommandOptionValue::Focused { .. } => Some(option),
177                CommandOptionValue::SubCommand(options)
178                | CommandOptionValue::SubCommandGroup(options) => find(options),
179                _ => None,
180            })
181        }
182
183        find(&self.options)
184    }
185}
186
187/// An [option filled in by the user](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-application-command-interaction-data-option-structure):
188/// its name and its value (by option type).
189///
190/// discord.js counterpart: `CommandInteractionOption`.
191#[derive(Clone, Debug, PartialEq)]
192#[non_exhaustive]
193pub struct CommandDataOption {
194    /// The option's name.
195    pub name: CompactString,
196    /// The value, or the options of a subcommand or group.
197    pub value: CommandOptionValue,
198}
199
200impl CommandDataOption {
201    /// Creates an option (for tests and mock servers).
202    ///
203    /// discord.js counterpart: `CommandInteractionOption`.
204    #[must_use]
205    pub fn new(name: impl Into<CompactString>, value: CommandOptionValue) -> Self {
206        Self {
207            name: name.into(),
208            value,
209        }
210    }
211}
212
213/// The value of a [`CommandDataOption`], by [option type](CommandOptionType).
214///
215/// Snowflake values (users, channels, roles, mentionables, attachments) are IDs; the objects
216/// they refer to are in the command's [`Resolved`] data.
217///
218/// discord.js counterpart: the `value` of an `APIApplicationCommandInteractionDataOption` (discord-api-types).
219#[derive(Clone, Debug, PartialEq)]
220#[non_exhaustive]
221pub enum CommandOptionValue {
222    /// A subcommand and its options.
223    SubCommand(Vec<CommandDataOption>),
224    /// A subcommand group and its (single) subcommand.
225    SubCommandGroup(Vec<CommandDataOption>),
226    /// A string.
227    String(CompactString),
228    /// An integer.
229    Integer(i64),
230    /// A boolean.
231    Boolean(bool),
232    /// A user (also in [`Resolved::users`] and, in guilds, [`Resolved::members`]).
233    User(UserId),
234    /// A channel (in [`Resolved::channels`]).
235    Channel(ChannelId),
236    /// A role (in [`Resolved::roles`]).
237    Role(RoleId),
238    /// A user or a role (in the matching [`Resolved`] map).
239    Mentionable(GenericId),
240    /// A floating-point number.
241    Number(f64),
242    /// An attachment (in [`Resolved::attachments`]).
243    Attachment(AttachmentId),
244    /// The option being typed in an autocomplete interaction: what the user has typed so far,
245    /// which need not be valid for the option's type yet.
246    Focused {
247        /// The option's type.
248        kind: CommandOptionType,
249        /// The text typed so far.
250        value: CompactString,
251    },
252    /// An option type this version does not know; its value is not kept.
253    Unknown(CommandOptionType),
254}
255
256impl CommandOptionValue {
257    /// Returns the option type.
258    ///
259    /// discord.js counterpart: `CommandInteractionOption#type`.
260    #[must_use]
261    pub const fn kind(&self) -> CommandOptionType {
262        match self {
263            Self::SubCommand(_) => CommandOptionType::SubCommand,
264            Self::SubCommandGroup(_) => CommandOptionType::SubCommandGroup,
265            Self::String(_) => CommandOptionType::String,
266            Self::Integer(_) => CommandOptionType::Integer,
267            Self::Boolean(_) => CommandOptionType::Boolean,
268            Self::User(_) => CommandOptionType::User,
269            Self::Channel(_) => CommandOptionType::Channel,
270            Self::Role(_) => CommandOptionType::Role,
271            Self::Mentionable(_) => CommandOptionType::Mentionable,
272            Self::Number(_) => CommandOptionType::Number,
273            Self::Attachment(_) => CommandOptionType::Attachment,
274            Self::Focused { kind, .. } | Self::Unknown(kind) => *kind,
275        }
276    }
277}
278
279/// A JSON value of an option, before the option type says what it must be.
280enum RawOptionValue {
281    String(CompactString),
282    Integer(i64),
283    Float(f64),
284    Boolean(bool),
285}
286
287impl<'de> Deserialize<'de> for RawOptionValue {
288    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
289        struct RawOptionValueVisitor;
290
291        impl Visitor<'_> for RawOptionValueVisitor {
292            type Value = RawOptionValue;
293
294            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
295                f.write_str("a string, a number or a boolean")
296            }
297
298            fn visit_bool<E: DeError>(self, value: bool) -> Result<RawOptionValue, E> {
299                Ok(RawOptionValue::Boolean(value))
300            }
301
302            fn visit_i64<E: DeError>(self, value: i64) -> Result<RawOptionValue, E> {
303                Ok(RawOptionValue::Integer(value))
304            }
305
306            fn visit_u64<E: DeError>(self, value: u64) -> Result<RawOptionValue, E> {
307                i64::try_from(value)
308                    .map(RawOptionValue::Integer)
309                    .map_err(|_| E::invalid_value(Unexpected::Unsigned(value), &self))
310            }
311
312            fn visit_f64<E: DeError>(self, value: f64) -> Result<RawOptionValue, E> {
313                Ok(RawOptionValue::Float(value))
314            }
315
316            fn visit_str<E: DeError>(self, value: &str) -> Result<RawOptionValue, E> {
317                Ok(RawOptionValue::String(value.into()))
318            }
319        }
320
321        deserializer.deserialize_any(RawOptionValueVisitor)
322    }
323}
324
325impl RawOptionValue {
326    fn unexpected(&self) -> Unexpected<'_> {
327        match self {
328            Self::String(value) => Unexpected::Str(value),
329            Self::Integer(value) => Unexpected::Signed(*value),
330            Self::Float(value) => Unexpected::Float(*value),
331            Self::Boolean(value) => Unexpected::Bool(*value),
332        }
333    }
334
335    /// The text of a focused option (Discord sends it as a string; numbers are accepted too).
336    fn into_text(self) -> CompactString {
337        match self {
338            Self::String(value) => value,
339            Self::Integer(value) => value.to_compact_string(),
340            Self::Float(value) => value.to_compact_string(),
341            Self::Boolean(value) => value.to_compact_string(),
342        }
343    }
344
345    fn into_string<E: DeError>(self) -> Result<CompactString, E> {
346        match self {
347            Self::String(value) => Ok(value),
348            other => Err(E::invalid_type(other.unexpected(), &"a string")),
349        }
350    }
351
352    fn into_integer<E: DeError>(self) -> Result<i64, E> {
353        match self {
354            Self::Integer(value) => Ok(value),
355            Self::String(ref text) => text
356                .parse()
357                .map_err(|_| E::invalid_type(self.unexpected(), &"an integer")),
358            other => Err(E::invalid_type(other.unexpected(), &"an integer")),
359        }
360    }
361
362    fn into_number<E: DeError>(self) -> Result<f64, E> {
363        match self {
364            Self::Float(value) => Ok(value),
365            #[expect(
366                clippy::cast_precision_loss,
367                reason = "number options are doubles; Discord limits them to ±2^53"
368            )]
369            Self::Integer(value) => Ok(value as f64),
370            Self::String(ref text) => text
371                .parse()
372                .map_err(|_| E::invalid_type(self.unexpected(), &"a number")),
373            Self::Boolean(_) => Err(E::invalid_type(self.unexpected(), &"a number")),
374        }
375    }
376
377    fn into_boolean<E: DeError>(self) -> Result<bool, E> {
378        match self {
379            Self::Boolean(value) => Ok(value),
380            other => Err(E::invalid_type(other.unexpected(), &"a boolean")),
381        }
382    }
383
384    fn into_id<T, E: DeError>(self) -> Result<Id<T>, E> {
385        match self {
386            Self::String(ref text) => text
387                .parse()
388                .map_err(|_| E::invalid_value(self.unexpected(), &"a snowflake ID")),
389            Self::Integer(value) => u64::try_from(value)
390                .ok()
391                .and_then(Id::new_checked)
392                .ok_or_else(|| E::invalid_value(self.unexpected(), &"a snowflake ID")),
393            other => Err(E::invalid_type(other.unexpected(), &"a snowflake ID")),
394        }
395    }
396}
397
398/// Every field of an option, decoded in one pass.
399#[derive(Deserialize)]
400struct RawDataOption {
401    name: CompactString,
402    #[serde(rename = "type")]
403    kind: CommandOptionType,
404    #[serde(default)]
405    value: Option<RawOptionValue>,
406    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
407    options: Vec<CommandDataOption>,
408    #[serde(default)]
409    focused: bool,
410}
411
412impl<'de> Deserialize<'de> for CommandDataOption {
413    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
414        let raw = RawDataOption::deserialize(deserializer)?;
415        let kind = raw.kind;
416        let value = match kind {
417            CommandOptionType::SubCommand => CommandOptionValue::SubCommand(raw.options),
418            CommandOptionType::SubCommandGroup => CommandOptionValue::SubCommandGroup(raw.options),
419            CommandOptionType::Unknown(_) => CommandOptionValue::Unknown(kind),
420            _ => {
421                let value = raw.value.ok_or_else(|| D::Error::missing_field("value"))?;
422                if raw.focused {
423                    CommandOptionValue::Focused {
424                        kind,
425                        value: value.into_text(),
426                    }
427                } else {
428                    match kind {
429                        CommandOptionType::String => {
430                            CommandOptionValue::String(value.into_string()?)
431                        }
432                        CommandOptionType::Integer => {
433                            CommandOptionValue::Integer(value.into_integer()?)
434                        }
435                        CommandOptionType::Boolean => {
436                            CommandOptionValue::Boolean(value.into_boolean()?)
437                        }
438                        CommandOptionType::User => CommandOptionValue::User(value.into_id()?),
439                        CommandOptionType::Channel => CommandOptionValue::Channel(value.into_id()?),
440                        CommandOptionType::Role => CommandOptionValue::Role(value.into_id()?),
441                        CommandOptionType::Mentionable => {
442                            CommandOptionValue::Mentionable(value.into_id()?)
443                        }
444                        CommandOptionType::Number => {
445                            CommandOptionValue::Number(value.into_number()?)
446                        }
447                        _ => CommandOptionValue::Attachment(value.into_id()?),
448                    }
449                }
450            }
451        };
452        Ok(Self {
453            name: raw.name,
454            value,
455        })
456    }
457}
458
459impl Serialize for CommandDataOption {
460    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
461        #[derive(Serialize)]
462        #[serde(untagged)]
463        enum Value<'a> {
464            String(&'a str),
465            Integer(i64),
466            Number(f64),
467            Boolean(bool),
468            Id(GenericId),
469        }
470
471        #[derive(Serialize)]
472        struct Flat<'a> {
473            name: &'a str,
474            #[serde(rename = "type")]
475            kind: CommandOptionType,
476            #[serde(skip_serializing_if = "Option::is_none")]
477            value: Option<Value<'a>>,
478            #[serde(skip_serializing_if = "Option::is_none")]
479            options: Option<&'a [CommandDataOption]>,
480            #[serde(skip_serializing_if = "core::ops::Not::not")]
481            focused: bool,
482        }
483
484        let mut flat = Flat {
485            name: &self.name,
486            kind: self.value.kind(),
487            value: None,
488            options: None,
489            focused: false,
490        };
491        match &self.value {
492            CommandOptionValue::SubCommand(options)
493            | CommandOptionValue::SubCommandGroup(options) => flat.options = Some(options),
494            CommandOptionValue::String(value) => flat.value = Some(Value::String(value)),
495            CommandOptionValue::Integer(value) => flat.value = Some(Value::Integer(*value)),
496            CommandOptionValue::Boolean(value) => flat.value = Some(Value::Boolean(*value)),
497            CommandOptionValue::User(id) => flat.value = Some(Value::Id(id.cast())),
498            CommandOptionValue::Channel(id) => flat.value = Some(Value::Id(id.cast())),
499            CommandOptionValue::Role(id) => flat.value = Some(Value::Id(id.cast())),
500            CommandOptionValue::Mentionable(id) => flat.value = Some(Value::Id(*id)),
501            CommandOptionValue::Number(value) => flat.value = Some(Value::Number(*value)),
502            CommandOptionValue::Attachment(id) => flat.value = Some(Value::Id(id.cast())),
503            CommandOptionValue::Focused { value, .. } => {
504                flat.value = Some(Value::String(value));
505                flat.focused = true;
506            }
507            CommandOptionValue::Unknown(_) => {}
508        }
509        flat.serialize(serializer)
510    }
511}
512
513/// The [data of a component interaction](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-message-component-data-structure):
514/// which button or select menu was used, and what was selected.
515///
516/// discord.js counterpart: `MessageComponentInteraction` (`customId`, `componentType`) and the
517/// select menu interactions (`values`).
518#[derive(Clone, Debug, PartialEq, Serialize)]
519#[non_exhaustive]
520pub struct ComponentData {
521    /// The component's custom ID.
522    pub custom_id: CompactString,
523    /// The component's type.
524    pub component_type: ComponentType,
525    /// The selected values (select menus): option values of string selects, IDs (as strings)
526    /// of the other selects (see [`ids`](Self::ids)).
527    #[serde(skip_serializing_if = "Vec::is_empty")]
528    pub values: Vec<CompactString>,
529    /// The selected users, members, roles and channels (entity select menus).
530    #[serde(skip_serializing_if = "Option::is_none")]
531    pub resolved: Option<Box<Resolved>>,
532}
533
534impl ComponentData {
535    /// Parses the selected [`values`](Self::values) of a user, role, mentionable or channel
536    /// select menu as IDs, skipping values that are not snowflakes.
537    ///
538    /// discord.js counterpart: `UserSelectMenuInteraction#values` and its siblings.
539    pub fn ids<T>(&self) -> impl Iterator<Item = Id<T>> + '_ {
540        self.values.iter().filter_map(|value| value.parse().ok())
541    }
542}
543
544/// The [data of a modal-submit interaction](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-modal-submit-data-structure):
545/// the values the user entered in the modal's components.
546///
547/// discord.js counterpart: `ModalSubmitInteraction` (`customId`, `fields`).
548#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
549#[non_exhaustive]
550pub struct ModalSubmitData {
551    /// The modal's custom ID.
552    pub custom_id: CompactString,
553    /// The submitted components, in the modal's layout.
554    pub components: Vec<SubmittedComponent>,
555    /// The selected users, members, roles, channels and uploaded attachments.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub resolved: Option<Box<Resolved>>,
558}
559
560impl ModalSubmitData {
561    /// Finds the submitted input with the given custom ID, inside labels and action rows.
562    ///
563    /// discord.js counterpart: `ModalSubmitFields#getField`.
564    #[must_use]
565    pub fn get(&self, custom_id: &str) -> Option<&SubmittedComponent> {
566        fn find<'a>(
567            components: &'a [SubmittedComponent],
568            custom_id: &str,
569        ) -> Option<&'a SubmittedComponent> {
570            components.iter().find_map(|component| match component {
571                SubmittedComponent::ActionRow(row) => find(&row.components, custom_id),
572                SubmittedComponent::Label(label) => {
573                    find(core::slice::from_ref(&*label.component), custom_id)
574                }
575                other => (other.custom_id() == Some(custom_id)).then_some(other),
576            })
577        }
578
579        find(&self.components, custom_id)
580    }
581
582    /// Returns the text entered in the text input with the given custom ID.
583    ///
584    /// discord.js counterpart: `ModalSubmitFields#getTextInputValue`.
585    #[must_use]
586    pub fn text_value(&self, custom_id: &str) -> Option<&str> {
587        match self.get(custom_id)? {
588            SubmittedComponent::TextInput(input) => Some(&input.value),
589            _ => None,
590        }
591    }
592}
593
594/// A [submitted modal component](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-component-interaction-response-structures):
595/// what the user entered, by component type.
596///
597/// discord.js counterpart: the entries of `ModalSubmitFields`.
598#[derive(Clone, Debug, PartialEq, Eq)]
599#[non_exhaustive]
600#[doc(alias = "ModalSubmitComponent")]
601pub enum SubmittedComponent {
602    /// An action row (legacy modals with text inputs in rows).
603    ActionRow(SubmittedActionRow),
604    /// A text input.
605    TextInput(SubmittedTextInput),
606    /// A string select menu.
607    StringSelect(SubmittedSelect),
608    /// A user select menu.
609    UserSelect(SubmittedEntitySelect<UserMarker>),
610    /// A role select menu.
611    RoleSelect(SubmittedEntitySelect<RoleMarker>),
612    /// A mentionable (user or role) select menu.
613    MentionableSelect(SubmittedEntitySelect<GenericMarker>),
614    /// A channel select menu.
615    ChannelSelect(SubmittedEntitySelect<ChannelMarker>),
616    /// A text display (no value).
617    TextDisplay(SubmittedTextDisplay),
618    /// A label and its component.
619    Label(SubmittedLabel),
620    /// A file upload.
621    FileUpload(SubmittedFileUpload),
622    /// A radio group.
623    RadioGroup(SubmittedRadioGroup),
624    /// A checkbox group.
625    CheckboxGroup(SubmittedSelect),
626    /// A checkbox.
627    Checkbox(SubmittedCheckbox),
628    /// A component type this version does not know; only its type and ID are kept.
629    Unknown(UnknownSubmittedComponent),
630}
631
632impl SubmittedComponent {
633    /// Returns the component type.
634    ///
635    /// discord.js counterpart: the `type` of `ModalData`.
636    #[must_use]
637    pub const fn kind(&self) -> ComponentType {
638        match self {
639            Self::ActionRow(_) => ComponentType::ActionRow,
640            Self::TextInput(_) => ComponentType::TextInput,
641            Self::StringSelect(_) => ComponentType::StringSelect,
642            Self::UserSelect(_) => ComponentType::UserSelect,
643            Self::RoleSelect(_) => ComponentType::RoleSelect,
644            Self::MentionableSelect(_) => ComponentType::MentionableSelect,
645            Self::ChannelSelect(_) => ComponentType::ChannelSelect,
646            Self::TextDisplay(_) => ComponentType::TextDisplay,
647            Self::Label(_) => ComponentType::Label,
648            Self::FileUpload(_) => ComponentType::FileUpload,
649            Self::RadioGroup(_) => ComponentType::RadioGroup,
650            Self::CheckboxGroup(_) => ComponentType::CheckboxGroup,
651            Self::Checkbox(_) => ComponentType::Checkbox,
652            Self::Unknown(component) => component.kind,
653        }
654    }
655
656    /// Returns the component's numeric ID.
657    ///
658    /// discord.js counterpart: the `id` of `ModalData`.
659    #[must_use]
660    pub const fn id(&self) -> Option<u32> {
661        match self {
662            Self::ActionRow(component) => component.id,
663            Self::TextInput(component) => component.id,
664            Self::StringSelect(component) | Self::CheckboxGroup(component) => component.id,
665            Self::UserSelect(component) => component.id,
666            Self::RoleSelect(component) => component.id,
667            Self::MentionableSelect(component) => component.id,
668            Self::ChannelSelect(component) => component.id,
669            Self::TextDisplay(component) => component.id,
670            Self::Label(component) => component.id,
671            Self::FileUpload(component) => component.id,
672            Self::RadioGroup(component) => component.id,
673            Self::Checkbox(component) => component.id,
674            Self::Unknown(component) => component.id,
675        }
676    }
677
678    /// Returns the custom ID of an input (not of action rows, labels and text displays).
679    ///
680    /// discord.js counterpart: the `customId` of `ModalData`.
681    #[must_use]
682    pub fn custom_id(&self) -> Option<&str> {
683        match self {
684            Self::TextInput(component) => Some(&component.custom_id),
685            Self::StringSelect(component) | Self::CheckboxGroup(component) => {
686                Some(&component.custom_id)
687            }
688            Self::UserSelect(component) => Some(&component.custom_id),
689            Self::RoleSelect(component) => Some(&component.custom_id),
690            Self::MentionableSelect(component) => Some(&component.custom_id),
691            Self::ChannelSelect(component) => Some(&component.custom_id),
692            Self::FileUpload(component) => Some(&component.custom_id),
693            Self::RadioGroup(component) => Some(&component.custom_id),
694            Self::Checkbox(component) => Some(&component.custom_id),
695            Self::ActionRow(_) | Self::TextDisplay(_) | Self::Label(_) | Self::Unknown(_) => None,
696        }
697    }
698}
699
700/// A submitted [action row](SubmittedComponent::ActionRow).
701///
702/// discord.js counterpart: `ModalSubmitActionRowComponent` (discord-api-types).
703#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
704#[non_exhaustive]
705pub struct SubmittedActionRow {
706    /// The component's numeric ID.
707    #[serde(skip_serializing_if = "Option::is_none")]
708    pub id: Option<u32>,
709    /// The submitted components in the row.
710    pub components: Vec<SubmittedComponent>,
711}
712
713/// A submitted [text input](SubmittedComponent::TextInput).
714///
715/// discord.js counterpart: `APIModalSubmitTextInputComponent` (discord-api-types).
716#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
717#[non_exhaustive]
718pub struct SubmittedTextInput {
719    /// The component's numeric ID.
720    #[serde(skip_serializing_if = "Option::is_none")]
721    pub id: Option<u32>,
722    /// The input's custom ID.
723    pub custom_id: CompactString,
724    /// The text the user entered.
725    pub value: CompactString,
726}
727
728/// A submitted [string select](SubmittedComponent::StringSelect) or
729/// [checkbox group](SubmittedComponent::CheckboxGroup).
730///
731/// discord.js counterpart: `APIModalSubmitStringSelectComponent` (discord-api-types).
732#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
733#[non_exhaustive]
734pub struct SubmittedSelect {
735    /// The component's numeric ID.
736    #[serde(skip_serializing_if = "Option::is_none")]
737    pub id: Option<u32>,
738    /// The component's custom ID.
739    pub custom_id: CompactString,
740    /// The values of the selected options (empty if none).
741    pub values: Vec<CompactString>,
742}
743
744/// A submitted user, role, mentionable or channel select menu: the IDs of the selected
745/// entities, whose objects are in [`ModalSubmitData::resolved`].
746///
747/// discord.js counterpart: `APIModalSubmitUserSelectComponent` and the other select components (discord-api-types).
748#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
749#[serde(bound = "")]
750#[non_exhaustive]
751pub struct SubmittedEntitySelect<T> {
752    /// The component's numeric ID.
753    #[serde(skip_serializing_if = "Option::is_none")]
754    pub id: Option<u32>,
755    /// The select menu's custom ID.
756    pub custom_id: CompactString,
757    /// The IDs of the selected entities.
758    pub values: Vec<Id<T>>,
759}
760
761/// A submitted [text display](SubmittedComponent::TextDisplay).
762///
763/// discord.js counterpart: `ModalSubmitTextDisplayComponent` (discord-api-types).
764#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
765#[non_exhaustive]
766pub struct SubmittedTextDisplay {
767    /// The component's numeric ID.
768    #[serde(skip_serializing_if = "Option::is_none")]
769    pub id: Option<u32>,
770}
771
772/// A submitted [label](SubmittedComponent::Label) and the input inside it.
773///
774/// discord.js counterpart: `ModalSubmitLabelComponent` (discord-api-types).
775#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
776#[non_exhaustive]
777pub struct SubmittedLabel {
778    /// The component's numeric ID.
779    #[serde(skip_serializing_if = "Option::is_none")]
780    pub id: Option<u32>,
781    /// The submitted input inside the label.
782    pub component: Box<SubmittedComponent>,
783}
784
785/// A submitted [file upload](SubmittedComponent::FileUpload): the IDs of the uploaded files,
786/// whose objects are in [`Resolved::attachments`].
787///
788/// discord.js counterpart: `APIModalSubmitFileUploadComponent` (discord-api-types).
789#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
790#[non_exhaustive]
791pub struct SubmittedFileUpload {
792    /// The component's numeric ID.
793    #[serde(skip_serializing_if = "Option::is_none")]
794    pub id: Option<u32>,
795    /// The component's custom ID.
796    pub custom_id: CompactString,
797    /// The IDs of the uploaded files.
798    pub values: Vec<AttachmentId>,
799}
800
801/// A submitted [radio group](SubmittedComponent::RadioGroup).
802///
803/// discord.js counterpart: `APIModalSubmitRadioGroupComponent` (discord-api-types).
804#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
805#[non_exhaustive]
806pub struct SubmittedRadioGroup {
807    /// The component's numeric ID.
808    #[serde(skip_serializing_if = "Option::is_none")]
809    pub id: Option<u32>,
810    /// The component's custom ID.
811    pub custom_id: CompactString,
812    /// The value of the selected option (`None` if nothing is selected).
813    pub value: Option<CompactString>,
814}
815
816/// A submitted [checkbox](SubmittedComponent::Checkbox).
817///
818/// discord.js counterpart: `APIModalSubmitCheckboxComponent` (discord-api-types).
819#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
820#[non_exhaustive]
821pub struct SubmittedCheckbox {
822    /// The component's numeric ID.
823    #[serde(skip_serializing_if = "Option::is_none")]
824    pub id: Option<u32>,
825    /// The component's custom ID.
826    pub custom_id: CompactString,
827    /// Whether the checkbox is checked.
828    pub value: bool,
829}
830
831/// A submitted component of a type this version does not know.
832///
833/// discord.js counterpart: none (a component type unknown to this version, kept as received).
834#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
835#[non_exhaustive]
836pub struct UnknownSubmittedComponent {
837    /// The component's type.
838    #[serde(skip)]
839    pub kind: ComponentType,
840    /// The component's numeric ID.
841    #[serde(skip_serializing_if = "Option::is_none")]
842    pub id: Option<u32>,
843}
844
845/// The `value` of a submitted component: text (text inputs, radio groups) or a boolean
846/// (checkboxes).
847enum RawSubmittedValue {
848    Text(CompactString),
849    Boolean(bool),
850}
851
852impl<'de> Deserialize<'de> for RawSubmittedValue {
853    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
854        struct RawSubmittedValueVisitor;
855
856        impl Visitor<'_> for RawSubmittedValueVisitor {
857            type Value = RawSubmittedValue;
858
859            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
860                f.write_str("a string or a boolean")
861            }
862
863            fn visit_bool<E: DeError>(self, value: bool) -> Result<RawSubmittedValue, E> {
864                Ok(RawSubmittedValue::Boolean(value))
865            }
866
867            fn visit_str<E: DeError>(self, value: &str) -> Result<RawSubmittedValue, E> {
868                Ok(RawSubmittedValue::Text(value.into()))
869            }
870        }
871
872        deserializer.deserialize_any(RawSubmittedValueVisitor)
873    }
874}
875
876/// Every field of a submitted component, decoded in one pass.
877#[derive(Deserialize)]
878struct RawSubmittedComponent {
879    #[serde(rename = "type")]
880    kind: ComponentType,
881    #[serde(default)]
882    id: Option<u32>,
883    #[serde(default)]
884    custom_id: Option<CompactString>,
885    #[serde(default)]
886    value: Option<RawSubmittedValue>,
887    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
888    values: Vec<CompactString>,
889    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
890    components: Vec<SubmittedComponent>,
891    #[serde(default)]
892    component: Option<Box<SubmittedComponent>>,
893}
894
895impl RawSubmittedComponent {
896    fn custom_id<E: DeError>(&mut self) -> Result<CompactString, E> {
897        self.custom_id
898            .take()
899            .ok_or_else(|| E::missing_field("custom_id"))
900    }
901
902    fn entity_select<T, E: DeError>(mut self) -> Result<SubmittedEntitySelect<T>, E> {
903        Ok(SubmittedEntitySelect {
904            id: self.id,
905            custom_id: self.custom_id()?,
906            values: parse_ids(&self.values)?,
907        })
908    }
909}
910
911fn parse_ids<T, E: DeError>(values: &[CompactString]) -> Result<Vec<Id<T>>, E> {
912    values
913        .iter()
914        .map(|value| {
915            value
916                .parse()
917                .map_err(|_| E::invalid_value(Unexpected::Str(value), &"a snowflake ID"))
918        })
919        .collect()
920}
921
922impl<'de> Deserialize<'de> for SubmittedComponent {
923    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
924        let mut raw = RawSubmittedComponent::deserialize(deserializer)?;
925        let id = raw.id;
926        Ok(match raw.kind {
927            ComponentType::ActionRow => Self::ActionRow(SubmittedActionRow {
928                id,
929                components: raw.components,
930            }),
931            ComponentType::TextInput => Self::TextInput(SubmittedTextInput {
932                id,
933                custom_id: raw.custom_id()?,
934                value: match raw.value {
935                    Some(RawSubmittedValue::Text(value)) => value,
936                    Some(RawSubmittedValue::Boolean(value)) => {
937                        return Err(D::Error::invalid_type(Unexpected::Bool(value), &"a string"));
938                    }
939                    None => return Err(D::Error::missing_field("value")),
940                },
941            }),
942            kind @ (ComponentType::StringSelect | ComponentType::CheckboxGroup) => {
943                let select = SubmittedSelect {
944                    id,
945                    custom_id: raw.custom_id()?,
946                    values: raw.values,
947                };
948                if kind == ComponentType::StringSelect {
949                    Self::StringSelect(select)
950                } else {
951                    Self::CheckboxGroup(select)
952                }
953            }
954            ComponentType::UserSelect => Self::UserSelect(raw.entity_select()?),
955            ComponentType::RoleSelect => Self::RoleSelect(raw.entity_select()?),
956            ComponentType::MentionableSelect => Self::MentionableSelect(raw.entity_select()?),
957            ComponentType::ChannelSelect => Self::ChannelSelect(raw.entity_select()?),
958            ComponentType::TextDisplay => Self::TextDisplay(SubmittedTextDisplay { id }),
959            ComponentType::Label => Self::Label(SubmittedLabel {
960                id,
961                component: raw
962                    .component
963                    .ok_or_else(|| D::Error::missing_field("component"))?,
964            }),
965            ComponentType::FileUpload => Self::FileUpload(SubmittedFileUpload {
966                id,
967                custom_id: raw.custom_id()?,
968                values: parse_ids(&raw.values)?,
969            }),
970            ComponentType::RadioGroup => Self::RadioGroup(SubmittedRadioGroup {
971                id,
972                custom_id: raw.custom_id()?,
973                value: match raw.value {
974                    Some(RawSubmittedValue::Text(value)) => Some(value),
975                    Some(RawSubmittedValue::Boolean(value)) => {
976                        return Err(D::Error::invalid_type(Unexpected::Bool(value), &"a string"));
977                    }
978                    None => None,
979                },
980            }),
981            ComponentType::Checkbox => Self::Checkbox(SubmittedCheckbox {
982                id,
983                custom_id: raw.custom_id()?,
984                value: match raw.value {
985                    Some(RawSubmittedValue::Boolean(value)) => value,
986                    Some(RawSubmittedValue::Text(value)) => {
987                        return Err(D::Error::invalid_type(
988                            Unexpected::Str(&value),
989                            &"a boolean",
990                        ));
991                    }
992                    None => false,
993                },
994            }),
995            kind => Self::Unknown(UnknownSubmittedComponent { kind, id }),
996        })
997    }
998}
999
1000/// Serializes a variant's struct together with its `type`.
1001#[derive(Serialize)]
1002struct Tagged<'a, T> {
1003    #[serde(rename = "type")]
1004    kind: ComponentType,
1005    #[serde(flatten)]
1006    component: &'a T,
1007}
1008
1009impl Serialize for SubmittedComponent {
1010    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1011        let kind = self.kind();
1012        match self {
1013            Self::ActionRow(component) => Tagged { kind, component }.serialize(serializer),
1014            Self::TextInput(component) => Tagged { kind, component }.serialize(serializer),
1015            Self::StringSelect(component) | Self::CheckboxGroup(component) => {
1016                Tagged { kind, component }.serialize(serializer)
1017            }
1018            Self::UserSelect(component) => Tagged { kind, component }.serialize(serializer),
1019            Self::RoleSelect(component) => Tagged { kind, component }.serialize(serializer),
1020            Self::MentionableSelect(component) => Tagged { kind, component }.serialize(serializer),
1021            Self::ChannelSelect(component) => Tagged { kind, component }.serialize(serializer),
1022            Self::TextDisplay(component) => Tagged { kind, component }.serialize(serializer),
1023            Self::Label(component) => Tagged { kind, component }.serialize(serializer),
1024            Self::FileUpload(component) => Tagged { kind, component }.serialize(serializer),
1025            Self::RadioGroup(component) => Tagged { kind, component }.serialize(serializer),
1026            Self::Checkbox(component) => Tagged { kind, component }.serialize(serializer),
1027            Self::Unknown(component) => Tagged { kind, component }.serialize(serializer),
1028        }
1029    }
1030}
1031
1032/// The [resolved data](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-resolved-data-structure)
1033/// of an interaction: the objects behind the IDs in options, select menus and file uploads,
1034/// keyed by ID (D-058).
1035///
1036/// A member's user is in [`users`](Self::users) under the same ID. The values are boxed
1037/// (D-256): a B-tree leaf reserves room for 11 entries, so a one-entry map of plain values
1038/// would hold kilobytes of empty space; boxed, an interaction takes a third of the memory.
1039/// Fields and methods work through the box as usual (`resolved.users[&id].username`), and
1040/// the getters of [`CommandData`] and the other data types return plain references.
1041///
1042/// discord.js counterpart: the resolved structures of `CommandInteractionOptionResolver` and
1043/// the select menu interactions (`users`, `members`, `roles`, `channels`).
1044#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1045#[non_exhaustive]
1046pub struct Resolved {
1047    /// Users.
1048    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1049    pub users: BTreeMap<UserId, Box<User>>,
1050    /// Members (without user; with their permissions in the channel).
1051    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1052    pub members: BTreeMap<UserId, Box<InteractionMember>>,
1053    /// Roles.
1054    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1055    pub roles: BTreeMap<RoleId, Box<Role>>,
1056    /// Partial channels (with the invoking member's permissions in them).
1057    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1058    pub channels: BTreeMap<ChannelId, Box<InteractionChannel>>,
1059    /// Messages (the target of message commands).
1060    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1061    pub messages: BTreeMap<MessageId, Box<Message>>,
1062    /// Attachments (attachment options, file uploads).
1063    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1064    pub attachments: BTreeMap<AttachmentId, Box<Attachment>>,
1065}
1066
1067/// Every field of every kind of interaction data, decoded in one pass; converted by the
1068/// interaction's `type` (D-067).
1069#[derive(Deserialize)]
1070pub(super) struct RawData {
1071    #[serde(default)]
1072    id: Option<CommandId>,
1073    #[serde(default)]
1074    name: Option<CompactString>,
1075    #[serde(default, rename = "type")]
1076    kind: Option<CommandType>,
1077    #[serde(default)]
1078    resolved: Option<Box<Resolved>>,
1079    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
1080    options: Vec<CommandDataOption>,
1081    #[serde(default)]
1082    guild_id: Option<GuildId>,
1083    #[serde(default)]
1084    target_id: Option<GenericId>,
1085    #[serde(default)]
1086    custom_id: Option<CompactString>,
1087    #[serde(default)]
1088    component_type: Option<ComponentType>,
1089    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
1090    values: Vec<CompactString>,
1091    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
1092    components: Vec<SubmittedComponent>,
1093}
1094
1095impl RawData {
1096    /// Converts the data of an interaction of type `kind`.
1097    pub(super) fn into_data<E: DeError>(
1098        data: Option<Self>,
1099        kind: InteractionType,
1100    ) -> Result<InteractionData, E> {
1101        let missing = || E::missing_field("data");
1102        Ok(match kind {
1103            InteractionType::Ping => InteractionData::Ping,
1104            InteractionType::ApplicationCommand => {
1105                InteractionData::ApplicationCommand(Box::new(data.ok_or_else(missing)?.command()?))
1106            }
1107            InteractionType::ApplicationCommandAutocomplete => {
1108                InteractionData::Autocomplete(Box::new(data.ok_or_else(missing)?.command()?))
1109            }
1110            InteractionType::MessageComponent => {
1111                let data = data.ok_or_else(missing)?;
1112                InteractionData::MessageComponent(Box::new(ComponentData {
1113                    custom_id: data
1114                        .custom_id
1115                        .ok_or_else(|| E::missing_field("custom_id"))?,
1116                    component_type: data
1117                        .component_type
1118                        .ok_or_else(|| E::missing_field("component_type"))?,
1119                    values: data.values,
1120                    resolved: data.resolved,
1121                }))
1122            }
1123            InteractionType::ModalSubmit => {
1124                let data = data.ok_or_else(missing)?;
1125                InteractionData::ModalSubmit(Box::new(ModalSubmitData {
1126                    custom_id: data
1127                        .custom_id
1128                        .ok_or_else(|| E::missing_field("custom_id"))?,
1129                    components: data.components,
1130                    resolved: data.resolved,
1131                }))
1132            }
1133            InteractionType::Unknown(_) => InteractionData::Unknown(kind),
1134        })
1135    }
1136
1137    fn command<E: DeError>(self) -> Result<CommandData, E> {
1138        Ok(CommandData {
1139            id: self.id.ok_or_else(|| E::missing_field("id"))?,
1140            name: self.name.ok_or_else(|| E::missing_field("name"))?,
1141            kind: self.kind.unwrap_or_default(),
1142            resolved: self.resolved,
1143            options: self.options,
1144            guild_id: self.guild_id,
1145            target_id: self.target_id,
1146        })
1147    }
1148}