Skip to main content

djs_model/interaction/
mod.rs

1//! [Interactions](https://docs.discord.com/developers/interactions/receiving-and-responding):
2//! what a user does with an app (commands, components, modals), and the app's responses.
3//!
4//! An [`Interaction`] holds the fields every interaction has, and its [`data`](Interaction::data)
5//! is an enum keyed by the interaction type (D-067). [`InteractionResponse`] is what the app
6//! sends back (D-068).
7
8mod data;
9mod getters;
10mod response;
11
12use core::{fmt, ops::Deref};
13
14use compact_str::CompactString;
15use serde::{
16    Deserialize, Deserializer, Serialize, Serializer,
17    de::{Error as DeError, Unexpected, Visitor},
18};
19
20pub use self::{
21    data::{
22        CommandData, CommandDataOption, CommandOptionValue, ComponentData, InteractionData,
23        ModalSubmitData, Resolved, SubmittedActionRow, SubmittedCheckbox, SubmittedComponent,
24        SubmittedEntitySelect, SubmittedFileUpload, SubmittedLabel, SubmittedRadioGroup,
25        SubmittedSelect, SubmittedTextDisplay, SubmittedTextInput, UnknownSubmittedComponent,
26    },
27    getters::Mentionable,
28    response::{
29        ActivityInstanceResource, AutocompleteCallbackData, AutocompleteChoices, CallbackResource,
30        DeferredCallbackData, InteractionCallback, InteractionCallbackResponse,
31        InteractionCallbackType, InteractionResponse, MessageCallbackData, ModalCallbackData,
32    },
33};
34use crate::{
35    channel::{ChannelFlags, ChannelType, ThreadMetadata},
36    entitlement::Entitlement,
37    guild::{Feature, MemberFlags, PartialMember},
38    id::{ApplicationId, ChannelId, GuildId, InteractionId, MessageId, RoleId, UserId},
39    macros::int_enum,
40    message::Message,
41    permissions::Permissions,
42    user::{AvatarDecorationData, Collectibles, User},
43    util::{ImageHash, Locale, Timestamp},
44};
45
46/// An [interaction](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object):
47/// a user used one of the app's commands, components or modals (or Discord checks the app's
48/// HTTP endpoint).
49///
50/// The [`data`](Self::data) enum tells which kind it is (D-067). The interaction is answered
51/// with an [`InteractionResponse`] within 3 seconds; its [`token`](Self::token) then stays
52/// valid for follow-up messages for 15 minutes. `Debug` does not print the token.
53///
54/// Contains floats (number options), so it is `PartialEq` but not `Eq` (D-064).
55///
56/// discord.js counterpart: `BaseInteraction` and its subclasses.
57#[derive(Clone, PartialEq)]
58#[non_exhaustive]
59pub struct Interaction {
60    /// The interaction's ID.
61    pub id: InteractionId,
62    /// The application the interaction is for.
63    pub application_id: ApplicationId,
64    /// The kind of interaction and its kind-specific data (D-067).
65    pub data: InteractionData,
66    /// The guild it was triggered in (a partial object).
67    pub guild: Option<InteractionGuild>,
68    /// The guild it was triggered in.
69    pub guild_id: Option<GuildId>,
70    /// The channel it was triggered in (a partial object).
71    pub channel: Option<Box<InteractionChannel>>,
72    /// The channel it was triggered in.
73    pub channel_id: Option<ChannelId>,
74    /// The invoking member, with their permissions in the channel (guild interactions).
75    pub member: Option<Box<InteractionMember>>,
76    /// The invoking user (DM interactions; in guilds use [`member`](Self::member), or
77    /// [`author`](Self::author) for both).
78    pub user: Option<Box<User>>,
79    /// The token to respond with; secret, valid for 15 minutes.
80    pub token: CompactString,
81    /// Always `1`.
82    pub version: u8,
83    /// The message the component was on (component interactions and modals opened by one).
84    pub message: Option<Box<Message>>,
85    /// The app's permissions in the channel (with the extra permissions apps get in DMs).
86    pub app_permissions: Permissions,
87    /// The invoking user's language (every interaction except pings).
88    pub locale: Option<Locale>,
89    /// The guild's preferred locale.
90    pub guild_locale: Option<Locale>,
91    /// The user's and guild's entitlements to the app's SKUs (monetized apps).
92    pub entitlements: Vec<Entitlement>,
93    /// The installations that authorized the interaction.
94    pub authorizing_integration_owners: AuthorizingIntegrationOwners,
95    /// Where the interaction was triggered.
96    pub context: Option<InteractionContextType>,
97    /// The maximum size of attachments in a response, in bytes.
98    pub attachment_size_limit: Option<u64>,
99}
100
101impl Interaction {
102    /// Returns the interaction type.
103    ///
104    /// discord.js counterpart: `BaseInteraction#type`.
105    #[must_use]
106    pub const fn kind(&self) -> InteractionType {
107        self.data.kind()
108    }
109
110    /// Returns the invoking user, from [`member`](Self::member) in guilds or
111    /// [`user`](Self::user) in DMs.
112    ///
113    /// discord.js counterpart: `BaseInteraction#user`.
114    #[must_use]
115    pub fn author(&self) -> Option<&User> {
116        self.member
117            .as_ref()
118            .and_then(|member| member.user.as_ref())
119            .or(self.user.as_deref())
120    }
121
122    /// Returns the command data if a user ran one of the app's commands (not for
123    /// autocomplete, unlike [`InteractionData::command`]; D-249).
124    ///
125    /// discord.js counterpart: `BaseInteraction#isCommand`.
126    #[must_use]
127    pub fn command(&self) -> Option<&CommandData> {
128        match &self.data {
129            InteractionData::ApplicationCommand(data) => Some(data),
130            _ => None,
131        }
132    }
133
134    /// Returns the command data if a user is typing an option with autocomplete (D-249); the
135    /// typed option is [`CommandData::focused`].
136    ///
137    /// discord.js counterpart: `BaseInteraction#isAutocomplete`.
138    #[must_use]
139    pub fn autocomplete(&self) -> Option<&CommandData> {
140        match &self.data {
141            InteractionData::Autocomplete(data) => Some(data),
142            _ => None,
143        }
144    }
145
146    /// Returns the component data if a user clicked a button or chose in a select menu
147    /// (D-249).
148    ///
149    /// discord.js counterpart: `BaseInteraction#isMessageComponent`.
150    #[must_use]
151    pub fn component(&self) -> Option<&ComponentData> {
152        match &self.data {
153            InteractionData::MessageComponent(data) => Some(data),
154            _ => None,
155        }
156    }
157
158    /// Returns the submitted fields if a user submitted one of the app's modals (D-249).
159    ///
160    /// discord.js counterpart: `BaseInteraction#isModalSubmit`.
161    #[must_use]
162    pub fn modal(&self) -> Option<&ModalSubmitData> {
163        match &self.data {
164            InteractionData::ModalSubmit(data) => Some(data),
165            _ => None,
166        }
167    }
168}
169
170impl fmt::Debug for Interaction {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        f.debug_struct("Interaction")
173            .field("id", &self.id)
174            .field("application_id", &self.application_id)
175            .field("data", &self.data)
176            .field("guild", &self.guild)
177            .field("guild_id", &self.guild_id)
178            .field("channel", &self.channel)
179            .field("channel_id", &self.channel_id)
180            .field("member", &self.member)
181            .field("user", &self.user)
182            .field("token", &"<redacted>")
183            .field("version", &self.version)
184            .field("message", &self.message)
185            .field("app_permissions", &self.app_permissions)
186            .field("locale", &self.locale)
187            .field("guild_locale", &self.guild_locale)
188            .field("entitlements", &self.entitlements)
189            .field(
190                "authorizing_integration_owners",
191                &self.authorizing_integration_owners,
192            )
193            .field("context", &self.context)
194            .field("attachment_size_limit", &self.attachment_size_limit)
195            .finish()
196    }
197}
198
199/// Every interaction field, decoded in one pass; `data` is converted by `type` afterwards
200/// (D-067).
201#[derive(Deserialize)]
202struct RawInteraction {
203    id: InteractionId,
204    application_id: ApplicationId,
205    #[serde(rename = "type")]
206    kind: InteractionType,
207    #[serde(default)]
208    data: Option<data::RawData>,
209    #[serde(default)]
210    guild: Option<InteractionGuild>,
211    #[serde(default)]
212    guild_id: Option<GuildId>,
213    #[serde(default)]
214    channel: Option<Box<InteractionChannel>>,
215    #[serde(default)]
216    channel_id: Option<ChannelId>,
217    #[serde(default)]
218    member: Option<Box<InteractionMember>>,
219    #[serde(default)]
220    user: Option<Box<User>>,
221    token: CompactString,
222    #[serde(default = "default_version")]
223    version: u8,
224    #[serde(default)]
225    message: Option<Box<Message>>,
226    #[serde(default)]
227    app_permissions: Permissions,
228    #[serde(default)]
229    locale: Option<Locale>,
230    #[serde(default)]
231    guild_locale: Option<Locale>,
232    #[serde(default)]
233    entitlements: Vec<Entitlement>,
234    #[serde(default)]
235    authorizing_integration_owners: AuthorizingIntegrationOwners,
236    #[serde(default)]
237    context: Option<InteractionContextType>,
238    #[serde(default)]
239    attachment_size_limit: Option<u64>,
240}
241
242const fn default_version() -> u8 {
243    1
244}
245
246impl<'de> Deserialize<'de> for Interaction {
247    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
248        let raw = RawInteraction::deserialize(deserializer)?;
249        Ok(Self {
250            id: raw.id,
251            application_id: raw.application_id,
252            data: data::RawData::into_data(raw.data, raw.kind)?,
253            guild: raw.guild,
254            guild_id: raw.guild_id,
255            channel: raw.channel,
256            channel_id: raw.channel_id,
257            member: raw.member,
258            user: raw.user,
259            token: raw.token,
260            version: raw.version,
261            message: raw.message,
262            app_permissions: raw.app_permissions,
263            locale: raw.locale,
264            guild_locale: raw.guild_locale,
265            entitlements: raw.entitlements,
266            authorizing_integration_owners: raw.authorizing_integration_owners,
267            context: raw.context,
268            attachment_size_limit: raw.attachment_size_limit,
269        })
270    }
271}
272
273impl Serialize for Interaction {
274    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
275        #[derive(Serialize)]
276        struct Flat<'a> {
277            id: InteractionId,
278            application_id: ApplicationId,
279            #[serde(rename = "type")]
280            kind: InteractionType,
281            #[serde(skip_serializing_if = "Option::is_none")]
282            data: Option<data::DataRef<'a>>,
283            #[serde(skip_serializing_if = "Option::is_none")]
284            guild: Option<&'a InteractionGuild>,
285            #[serde(skip_serializing_if = "Option::is_none")]
286            guild_id: Option<GuildId>,
287            #[serde(skip_serializing_if = "Option::is_none")]
288            channel: Option<&'a InteractionChannel>,
289            #[serde(skip_serializing_if = "Option::is_none")]
290            channel_id: Option<ChannelId>,
291            #[serde(skip_serializing_if = "Option::is_none")]
292            member: Option<&'a InteractionMember>,
293            #[serde(skip_serializing_if = "Option::is_none")]
294            user: Option<&'a User>,
295            token: &'a str,
296            version: u8,
297            #[serde(skip_serializing_if = "Option::is_none")]
298            message: Option<&'a Message>,
299            app_permissions: Permissions,
300            #[serde(skip_serializing_if = "Option::is_none")]
301            locale: Option<&'a Locale>,
302            #[serde(skip_serializing_if = "Option::is_none")]
303            guild_locale: Option<&'a Locale>,
304            entitlements: &'a [Entitlement],
305            authorizing_integration_owners: &'a AuthorizingIntegrationOwners,
306            #[serde(skip_serializing_if = "Option::is_none")]
307            context: Option<InteractionContextType>,
308            #[serde(skip_serializing_if = "Option::is_none")]
309            attachment_size_limit: Option<u64>,
310        }
311
312        Flat {
313            id: self.id,
314            application_id: self.application_id,
315            kind: self.kind(),
316            data: self.data.as_ref(),
317            guild: self.guild.as_ref(),
318            guild_id: self.guild_id,
319            channel: self.channel.as_deref(),
320            channel_id: self.channel_id,
321            member: self.member.as_deref(),
322            user: self.user.as_deref(),
323            token: &self.token,
324            version: self.version,
325            message: self.message.as_deref(),
326            app_permissions: self.app_permissions,
327            locale: self.locale.as_ref(),
328            guild_locale: self.guild_locale.as_ref(),
329            entitlements: &self.entitlements,
330            authorizing_integration_owners: &self.authorizing_integration_owners,
331            context: self.context,
332            attachment_size_limit: self.attachment_size_limit,
333        }
334        .serialize(serializer)
335    }
336}
337
338/// The [partial guild](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-structure)
339/// an interaction was triggered in (D-051).
340///
341/// discord.js counterpart: `APIPartialInteractionGuild` (discord-api-types).
342#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
343#[non_exhaustive]
344pub struct InteractionGuild {
345    /// The guild's ID.
346    pub id: GuildId,
347    /// The guild's preferred locale.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub locale: Option<Locale>,
350    /// The guild's features.
351    #[serde(default)]
352    pub features: Vec<Feature>,
353}
354
355/// The partial channel an interaction was triggered in, or a channel in [`Resolved`] data
356/// (D-051): the fields Discord sends there, plus the invoking member's permissions in it.
357///
358/// discord.js counterpart: the channel of an interaction (`Interaction#channel`) and the
359/// resolved channels of command options.
360#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
361#[non_exhaustive]
362pub struct InteractionChannel {
363    /// The channel's ID.
364    pub id: ChannelId,
365    /// The channel's type.
366    #[serde(rename = "type")]
367    pub kind: ChannelType,
368    /// The channel's name (absent for DMs).
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub name: Option<CompactString>,
371    /// The guild, for guild channels.
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub guild_id: Option<GuildId>,
374    /// The invoking member's permissions in the channel (resolved channels).
375    #[serde(default, skip_serializing_if = "Option::is_none")]
376    pub permissions: Option<Permissions>,
377    /// The app's permissions in the channel (resolved channels).
378    #[serde(default, skip_serializing_if = "Option::is_none")]
379    pub app_permissions: Option<Permissions>,
380    /// The parent category, or the parent channel of a thread.
381    #[serde(default, skip_serializing_if = "Option::is_none")]
382    pub parent_id: Option<ChannelId>,
383    /// The sorting position.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub position: Option<i32>,
386    /// The channel's topic.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub topic: Option<CompactString>,
389    /// Whether the channel is age-restricted.
390    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
391    pub nsfw: bool,
392    /// The last message sent in the channel (may not exist any more).
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub last_message_id: Option<MessageId>,
395    /// When the last message was pinned.
396    #[serde(default, skip_serializing_if = "Option::is_none")]
397    pub last_pin_timestamp: Option<Timestamp>,
398    /// The slowmode in seconds.
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub rate_limit_per_user: Option<u16>,
401    /// The channel's flags.
402    #[serde(default)]
403    pub flags: ChannelFlags,
404    /// The thread's metadata, for threads.
405    #[serde(default, skip_serializing_if = "Option::is_none")]
406    pub thread_metadata: Option<ThreadMetadata>,
407    /// The recipients of a DM or group DM.
408    #[serde(default, skip_serializing_if = "Vec::is_empty")]
409    pub recipients: Vec<User>,
410}
411
412/// A member in an interaction: the invoking [`member`](Interaction::member) (with its
413/// [`user`](Self::user)) or a member in [`Resolved`] data (without user), together with their
414/// [`permissions`](Self::permissions) in the channel.
415///
416/// Dereferences to the [`PartialMember`], so `member.nick` works. Decoded in one pass, like
417/// [`Mention`](crate::message::Mention) (D-060).
418///
419/// discord.js counterpart: `GuildMember` (`Interaction#member`).
420#[derive(Clone, Debug, PartialEq, Eq)]
421#[non_exhaustive]
422pub struct InteractionMember {
423    /// The member's guild-specific data.
424    pub member: PartialMember,
425    /// The member's user (the invoking member; absent in resolved data, where the user is in
426    /// [`Resolved::users`]).
427    pub user: Option<User>,
428    /// The member's permissions in the channel, including overwrites.
429    pub permissions: Permissions,
430}
431
432impl Deref for InteractionMember {
433    type Target = PartialMember;
434
435    fn deref(&self) -> &PartialMember {
436        &self.member
437    }
438}
439
440/// The fields of a [`PartialMember`] plus `user` and `permissions`, decoded in one pass. Must
441/// list the same fields with the same serde attributes as [`PartialMember`].
442#[derive(Deserialize)]
443struct RawInteractionMember {
444    #[serde(default)]
445    nick: Option<CompactString>,
446    #[serde(default)]
447    avatar: Option<ImageHash>,
448    #[serde(default)]
449    banner: Option<ImageHash>,
450    roles: Vec<RoleId>,
451    joined_at: Option<Timestamp>,
452    #[serde(default)]
453    premium_since: Option<Timestamp>,
454    #[serde(default)]
455    deaf: bool,
456    #[serde(default)]
457    mute: bool,
458    #[serde(default)]
459    flags: MemberFlags,
460    #[serde(default)]
461    pending: bool,
462    #[serde(default)]
463    communication_disabled_until: Option<Timestamp>,
464    #[serde(default)]
465    avatar_decoration_data: Option<Box<AvatarDecorationData>>,
466    #[serde(default)]
467    collectibles: Option<Box<Collectibles>>,
468    #[serde(default)]
469    user: Option<User>,
470    #[serde(default)]
471    permissions: Permissions,
472}
473
474impl<'de> Deserialize<'de> for InteractionMember {
475    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
476        let raw = RawInteractionMember::deserialize(deserializer)?;
477        Ok(Self {
478            member: PartialMember {
479                nick: raw.nick,
480                avatar: raw.avatar,
481                banner: raw.banner,
482                roles: raw.roles,
483                joined_at: raw.joined_at,
484                premium_since: raw.premium_since,
485                deaf: raw.deaf,
486                mute: raw.mute,
487                flags: raw.flags,
488                pending: raw.pending,
489                communication_disabled_until: raw.communication_disabled_until,
490                avatar_decoration_data: raw.avatar_decoration_data,
491                collectibles: raw.collectibles,
492            },
493            user: raw.user,
494            permissions: raw.permissions,
495        })
496    }
497}
498
499impl Serialize for InteractionMember {
500    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
501        #[derive(Serialize)]
502        struct Flat<'a> {
503            #[serde(flatten)]
504            member: &'a PartialMember,
505            #[serde(skip_serializing_if = "Option::is_none")]
506            user: Option<&'a User>,
507            permissions: Permissions,
508        }
509
510        Flat {
511            member: &self.member,
512            user: self.user.as_ref(),
513            permissions: self.permissions,
514        }
515        .serialize(serializer)
516    }
517}
518
519int_enum! {
520    /// The [type of an interaction](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-type).
521    ///
522    /// discord.js counterpart: `InteractionType`.
523    pub enum InteractionType: u8 {
524        /// Discord checks that an HTTP interactions endpoint works.
525        Ping = 1,
526        /// A slash command or a context menu command.
527        ApplicationCommand = 2,
528        /// A button, select menu or other message component.
529        MessageComponent = 3,
530        /// Autocomplete suggestions for a command option.
531        ApplicationCommandAutocomplete = 4,
532        /// A submitted modal.
533        ModalSubmit = 5,
534    }
535}
536
537int_enum! {
538    /// [Where an interaction can be used](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-context-types),
539    /// or was triggered from.
540    ///
541    /// discord.js counterpart: `InteractionContextType`.
542    pub enum InteractionContextType: u8 {
543        /// In guilds.
544        Guild = 0,
545        /// In DMs with the app's bot user.
546        BotDm = 1,
547        /// In group DMs and DMs other than with the app's bot user.
548        PrivateChannel = 2,
549    }
550}
551
552/// The [interaction a message responds to](https://docs.discord.com/developers/interactions/receiving-and-responding#message-interaction-object)
553/// (`Message::interaction`).
554///
555/// **Deprecated** by Discord in favor of
556/// [`Message::interaction_metadata`](crate::message::Message::interaction_metadata).
557///
558/// discord.js counterpart: `MessageInteraction` (`Message#interaction`).
559#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
560#[non_exhaustive]
561pub struct MessageInteraction {
562    /// The interaction's ID.
563    pub id: InteractionId,
564    /// The kind of interaction.
565    #[serde(rename = "type")]
566    pub kind: InteractionType,
567    /// The name of the command, including subcommands and subcommand groups.
568    pub name: CompactString,
569    /// The user who invoked the interaction.
570    pub user: User,
571    /// The member who invoked the interaction, in guilds.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub member: Option<Box<PartialMember>>,
574}
575
576/// The [installations that authorized an interaction](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-authorizing-integration-owners-object),
577/// keyed by [`IntegrationType`](crate::application::IntegrationType).
578///
579/// A key is only present when the app is installed in that context, the interaction's context
580/// supports it and, for commands, the command supports that installation context.
581///
582/// discord.js counterpart: `authorizingIntegrationOwners`.
583#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
584#[non_exhaustive]
585pub struct AuthorizingIntegrationOwners {
586    /// The guild install (key `"0"`).
587    #[serde(rename = "0", default, skip_serializing_if = "Option::is_none")]
588    pub guild_install: Option<GuildInstallOwner>,
589    /// The ID of the user who installed the app (key `"1"`).
590    #[serde(rename = "1", default, skip_serializing_if = "Option::is_none")]
591    pub user_install: Option<UserId>,
592}
593
594/// The owner of a guild install in [`AuthorizingIntegrationOwners`].
595///
596/// discord.js counterpart: the guild install entry of `APIAuthorizingIntegrationOwnersMap` (discord-api-types).
597#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
598#[non_exhaustive]
599pub enum GuildInstallOwner {
600    /// The interaction happened in this guild.
601    Guild(GuildId),
602    /// The interaction happened in a DM with the app's bot user (Discord sends `"0"`).
603    BotDm,
604}
605
606impl GuildInstallOwner {
607    /// Returns the guild ID, unless the interaction happened in a DM with the bot.
608    ///
609    /// discord.js counterpart: `BaseInteraction#authorizingIntegrationOwners`'s guild entry.
610    #[must_use]
611    pub const fn guild_id(self) -> Option<GuildId> {
612        match self {
613            Self::Guild(id) => Some(id),
614            Self::BotDm => None,
615        }
616    }
617}
618
619impl Serialize for GuildInstallOwner {
620    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
621        match self {
622            Self::Guild(id) => id.serialize(serializer),
623            Self::BotDm => serializer.serialize_str("0"),
624        }
625    }
626}
627
628impl<'de> Deserialize<'de> for GuildInstallOwner {
629    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
630        struct OwnerVisitor;
631
632        impl Visitor<'_> for OwnerVisitor {
633            type Value = GuildInstallOwner;
634
635            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636                f.write_str("a guild ID or \"0\"")
637            }
638
639            fn visit_str<E: DeError>(self, value: &str) -> Result<GuildInstallOwner, E> {
640                if value == "0" {
641                    return Ok(GuildInstallOwner::BotDm);
642                }
643                value
644                    .parse()
645                    .map(GuildInstallOwner::Guild)
646                    .map_err(|_| E::invalid_value(Unexpected::Str(value), &self))
647            }
648        }
649
650        deserializer.deserialize_str(OwnerVisitor)
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use core::mem::size_of;
657
658    use super::*;
659
660    /// Size guards (D-054): interactions are decoded on every `INTERACTION_CREATE`.
661    #[test]
662    fn sizes() {
663        assert!(
664            size_of::<Interaction>() <= 288,
665            "{}",
666            size_of::<Interaction>()
667        );
668        assert_eq!(size_of::<InteractionData>(), 16);
669        assert!(
670            size_of::<CommandDataOption>() <= 56,
671            "{}",
672            size_of::<CommandDataOption>()
673        );
674        assert!(
675            size_of::<SubmittedComponent>() <= 64,
676            "{}",
677            size_of::<SubmittedComponent>()
678        );
679        assert!(
680            size_of::<InteractionResponse>() <= 32,
681            "{}",
682            size_of::<InteractionResponse>()
683        );
684    }
685
686    #[test]
687    fn debug_redacts_the_token() {
688        let interaction: Interaction = serde_json::from_str(
689            r#"{"id":"1","application_id":"2","type":1,"token":"secret-token","version":1}"#,
690        )
691        .unwrap();
692        let debug = format!("{interaction:?}");
693        assert!(!debug.contains("secret-token"), "{debug}");
694        assert!(debug.contains("<redacted>"), "{debug}");
695    }
696}