1use 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#[derive(Clone, Debug, PartialEq)]
32#[non_exhaustive]
33pub enum InteractionData {
34 Ping,
37 ApplicationCommand(Box<CommandData>),
42 MessageComponent(Box<ComponentData>),
47 Autocomplete(Box<CommandData>),
52 ModalSubmit(Box<ModalSubmitData>),
56 Unknown(InteractionType),
58}
59
60impl InteractionData {
61 #[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 #[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 #[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 #[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 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#[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#[derive(Clone, Debug, PartialEq, Serialize)]
143#[non_exhaustive]
144pub struct CommandData {
145 pub id: CommandId,
147 pub name: CompactString,
149 #[serde(rename = "type")]
151 pub kind: CommandType,
152 #[serde(skip_serializing_if = "Option::is_none")]
155 pub resolved: Option<Box<Resolved>>,
156 #[serde(skip_serializing_if = "Vec::is_empty")]
158 pub options: Vec<CommandDataOption>,
159 #[serde(skip_serializing_if = "Option::is_none")]
161 pub guild_id: Option<GuildId>,
162 #[serde(skip_serializing_if = "Option::is_none")]
164 pub target_id: Option<GenericId>,
165}
166
167impl CommandData {
168 #[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#[derive(Clone, Debug, PartialEq)]
192#[non_exhaustive]
193pub struct CommandDataOption {
194 pub name: CompactString,
196 pub value: CommandOptionValue,
198}
199
200impl CommandDataOption {
201 #[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#[derive(Clone, Debug, PartialEq)]
220#[non_exhaustive]
221pub enum CommandOptionValue {
222 SubCommand(Vec<CommandDataOption>),
224 SubCommandGroup(Vec<CommandDataOption>),
226 String(CompactString),
228 Integer(i64),
230 Boolean(bool),
232 User(UserId),
234 Channel(ChannelId),
236 Role(RoleId),
238 Mentionable(GenericId),
240 Number(f64),
242 Attachment(AttachmentId),
244 Focused {
247 kind: CommandOptionType,
249 value: CompactString,
251 },
252 Unknown(CommandOptionType),
254}
255
256impl CommandOptionValue {
257 #[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
279enum 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 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#[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#[derive(Clone, Debug, PartialEq, Serialize)]
519#[non_exhaustive]
520pub struct ComponentData {
521 pub custom_id: CompactString,
523 pub component_type: ComponentType,
525 #[serde(skip_serializing_if = "Vec::is_empty")]
528 pub values: Vec<CompactString>,
529 #[serde(skip_serializing_if = "Option::is_none")]
531 pub resolved: Option<Box<Resolved>>,
532}
533
534impl ComponentData {
535 pub fn ids<T>(&self) -> impl Iterator<Item = Id<T>> + '_ {
540 self.values.iter().filter_map(|value| value.parse().ok())
541 }
542}
543
544#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
549#[non_exhaustive]
550pub struct ModalSubmitData {
551 pub custom_id: CompactString,
553 pub components: Vec<SubmittedComponent>,
555 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub resolved: Option<Box<Resolved>>,
558}
559
560impl ModalSubmitData {
561 #[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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
599#[non_exhaustive]
600#[doc(alias = "ModalSubmitComponent")]
601pub enum SubmittedComponent {
602 ActionRow(SubmittedActionRow),
604 TextInput(SubmittedTextInput),
606 StringSelect(SubmittedSelect),
608 UserSelect(SubmittedEntitySelect<UserMarker>),
610 RoleSelect(SubmittedEntitySelect<RoleMarker>),
612 MentionableSelect(SubmittedEntitySelect<GenericMarker>),
614 ChannelSelect(SubmittedEntitySelect<ChannelMarker>),
616 TextDisplay(SubmittedTextDisplay),
618 Label(SubmittedLabel),
620 FileUpload(SubmittedFileUpload),
622 RadioGroup(SubmittedRadioGroup),
624 CheckboxGroup(SubmittedSelect),
626 Checkbox(SubmittedCheckbox),
628 Unknown(UnknownSubmittedComponent),
630}
631
632impl SubmittedComponent {
633 #[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 #[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 #[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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
704#[non_exhaustive]
705pub struct SubmittedActionRow {
706 #[serde(skip_serializing_if = "Option::is_none")]
708 pub id: Option<u32>,
709 pub components: Vec<SubmittedComponent>,
711}
712
713#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
717#[non_exhaustive]
718pub struct SubmittedTextInput {
719 #[serde(skip_serializing_if = "Option::is_none")]
721 pub id: Option<u32>,
722 pub custom_id: CompactString,
724 pub value: CompactString,
726}
727
728#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
733#[non_exhaustive]
734pub struct SubmittedSelect {
735 #[serde(skip_serializing_if = "Option::is_none")]
737 pub id: Option<u32>,
738 pub custom_id: CompactString,
740 pub values: Vec<CompactString>,
742}
743
744#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
749#[serde(bound = "")]
750#[non_exhaustive]
751pub struct SubmittedEntitySelect<T> {
752 #[serde(skip_serializing_if = "Option::is_none")]
754 pub id: Option<u32>,
755 pub custom_id: CompactString,
757 pub values: Vec<Id<T>>,
759}
760
761#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
765#[non_exhaustive]
766pub struct SubmittedTextDisplay {
767 #[serde(skip_serializing_if = "Option::is_none")]
769 pub id: Option<u32>,
770}
771
772#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
776#[non_exhaustive]
777pub struct SubmittedLabel {
778 #[serde(skip_serializing_if = "Option::is_none")]
780 pub id: Option<u32>,
781 pub component: Box<SubmittedComponent>,
783}
784
785#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
790#[non_exhaustive]
791pub struct SubmittedFileUpload {
792 #[serde(skip_serializing_if = "Option::is_none")]
794 pub id: Option<u32>,
795 pub custom_id: CompactString,
797 pub values: Vec<AttachmentId>,
799}
800
801#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
805#[non_exhaustive]
806pub struct SubmittedRadioGroup {
807 #[serde(skip_serializing_if = "Option::is_none")]
809 pub id: Option<u32>,
810 pub custom_id: CompactString,
812 pub value: Option<CompactString>,
814}
815
816#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
820#[non_exhaustive]
821pub struct SubmittedCheckbox {
822 #[serde(skip_serializing_if = "Option::is_none")]
824 pub id: Option<u32>,
825 pub custom_id: CompactString,
827 pub value: bool,
829}
830
831#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
835#[non_exhaustive]
836pub struct UnknownSubmittedComponent {
837 #[serde(skip)]
839 pub kind: ComponentType,
840 #[serde(skip_serializing_if = "Option::is_none")]
842 pub id: Option<u32>,
843}
844
845enum 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#[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#[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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1045#[non_exhaustive]
1046pub struct Resolved {
1047 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1049 pub users: BTreeMap<UserId, Box<User>>,
1050 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1052 pub members: BTreeMap<UserId, Box<InteractionMember>>,
1053 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1055 pub roles: BTreeMap<RoleId, Box<Role>>,
1056 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1058 pub channels: BTreeMap<ChannelId, Box<InteractionChannel>>,
1059 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1061 pub messages: BTreeMap<MessageId, Box<Message>>,
1062 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1064 pub attachments: BTreeMap<AttachmentId, Box<Attachment>>,
1065}
1066
1067#[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 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}