1mod 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#[derive(Clone, PartialEq)]
58#[non_exhaustive]
59pub struct Interaction {
60 pub id: InteractionId,
62 pub application_id: ApplicationId,
64 pub data: InteractionData,
66 pub guild: Option<InteractionGuild>,
68 pub guild_id: Option<GuildId>,
70 pub channel: Option<Box<InteractionChannel>>,
72 pub channel_id: Option<ChannelId>,
74 pub member: Option<Box<InteractionMember>>,
76 pub user: Option<Box<User>>,
79 pub token: CompactString,
81 pub version: u8,
83 pub message: Option<Box<Message>>,
85 pub app_permissions: Permissions,
87 pub locale: Option<Locale>,
89 pub guild_locale: Option<Locale>,
91 pub entitlements: Vec<Entitlement>,
93 pub authorizing_integration_owners: AuthorizingIntegrationOwners,
95 pub context: Option<InteractionContextType>,
97 pub attachment_size_limit: Option<u64>,
99}
100
101impl Interaction {
102 #[must_use]
106 pub const fn kind(&self) -> InteractionType {
107 self.data.kind()
108 }
109
110 #[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 #[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 #[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 #[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 #[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#[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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
343#[non_exhaustive]
344pub struct InteractionGuild {
345 pub id: GuildId,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub locale: Option<Locale>,
350 #[serde(default)]
352 pub features: Vec<Feature>,
353}
354
355#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
361#[non_exhaustive]
362pub struct InteractionChannel {
363 pub id: ChannelId,
365 #[serde(rename = "type")]
367 pub kind: ChannelType,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
370 pub name: Option<CompactString>,
371 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub guild_id: Option<GuildId>,
374 #[serde(default, skip_serializing_if = "Option::is_none")]
376 pub permissions: Option<Permissions>,
377 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub app_permissions: Option<Permissions>,
380 #[serde(default, skip_serializing_if = "Option::is_none")]
382 pub parent_id: Option<ChannelId>,
383 #[serde(default, skip_serializing_if = "Option::is_none")]
385 pub position: Option<i32>,
386 #[serde(default, skip_serializing_if = "Option::is_none")]
388 pub topic: Option<CompactString>,
389 #[serde(default, skip_serializing_if = "core::ops::Not::not")]
391 pub nsfw: bool,
392 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub last_message_id: Option<MessageId>,
395 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub last_pin_timestamp: Option<Timestamp>,
398 #[serde(default, skip_serializing_if = "Option::is_none")]
400 pub rate_limit_per_user: Option<u16>,
401 #[serde(default)]
403 pub flags: ChannelFlags,
404 #[serde(default, skip_serializing_if = "Option::is_none")]
406 pub thread_metadata: Option<ThreadMetadata>,
407 #[serde(default, skip_serializing_if = "Vec::is_empty")]
409 pub recipients: Vec<User>,
410}
411
412#[derive(Clone, Debug, PartialEq, Eq)]
421#[non_exhaustive]
422pub struct InteractionMember {
423 pub member: PartialMember,
425 pub user: Option<User>,
428 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#[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 pub enum InteractionType: u8 {
524 Ping = 1,
526 ApplicationCommand = 2,
528 MessageComponent = 3,
530 ApplicationCommandAutocomplete = 4,
532 ModalSubmit = 5,
534 }
535}
536
537int_enum! {
538 pub enum InteractionContextType: u8 {
543 Guild = 0,
545 BotDm = 1,
547 PrivateChannel = 2,
549 }
550}
551
552#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
560#[non_exhaustive]
561pub struct MessageInteraction {
562 pub id: InteractionId,
564 #[serde(rename = "type")]
566 pub kind: InteractionType,
567 pub name: CompactString,
569 pub user: User,
571 #[serde(default, skip_serializing_if = "Option::is_none")]
573 pub member: Option<Box<PartialMember>>,
574}
575
576#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
584#[non_exhaustive]
585pub struct AuthorizingIntegrationOwners {
586 #[serde(rename = "0", default, skip_serializing_if = "Option::is_none")]
588 pub guild_install: Option<GuildInstallOwner>,
589 #[serde(rename = "1", default, skip_serializing_if = "Option::is_none")]
591 pub user_install: Option<UserId>,
592}
593
594#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
598#[non_exhaustive]
599pub enum GuildInstallOwner {
600 Guild(GuildId),
602 BotDm,
604}
605
606impl GuildInstallOwner {
607 #[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 #[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}