djs_model/interaction/response.rs
1//! [Interaction responses](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object)
2//! and the [callback response](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-callback)
3//! Discord returns for them (D-068).
4
5use compact_str::CompactString;
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};
7
8use super::InteractionType;
9use crate::{
10 application_command::{Choice, RawValue, convert_choices},
11 component::Component,
12 id::{InteractionId, MessageId},
13 macros::int_enum,
14 message::{AllowedMentions, AttachmentRequest, Embed, Message, MessageFlags},
15 poll::CreatePoll,
16 rest::{Attachments, FileUpload, setters},
17};
18
19int_enum! {
20 /// The [type of an interaction response](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type).
21 ///
22 /// discord.js counterpart: `InteractionResponseType`.
23 #[doc(alias = "InteractionResponseType")]
24 pub enum InteractionCallbackType: u8 {
25 /// [`InteractionResponse::Pong`].
26 Pong = 1,
27 /// [`InteractionResponse::ChannelMessageWithSource`].
28 ChannelMessageWithSource = 4,
29 /// [`InteractionResponse::DeferredChannelMessageWithSource`].
30 DeferredChannelMessageWithSource = 5,
31 /// [`InteractionResponse::DeferredUpdateMessage`].
32 DeferredUpdateMessage = 6,
33 /// [`InteractionResponse::UpdateMessage`].
34 UpdateMessage = 7,
35 /// [`InteractionResponse::AutocompleteResult`].
36 ApplicationCommandAutocompleteResult = 8,
37 /// [`InteractionResponse::Modal`].
38 Modal = 9,
39 /// [`InteractionResponse::PremiumRequired`] (deprecated).
40 PremiumRequired = 10,
41 /// [`InteractionResponse::LaunchActivity`].
42 LaunchActivity = 12,
43 }
44}
45
46/// An [interaction response](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object):
47/// how the app answers an [`Interaction`](super::Interaction), within 3 seconds, by
48/// `POST /interactions/{id}/{token}/callback` or as the body of the HTTP endpoint's reply.
49///
50/// Written as `{"type": …, "data": …}`; the variant decides the type.
51///
52/// discord.js counterpart: what `reply`, `deferReply`, `update`, `deferUpdate`, `respond`,
53/// `showModal` and `launchActivity` send.
54///
55/// # Examples
56///
57/// ```
58/// use djs_model::interaction::{InteractionResponse, MessageCallbackData};
59///
60/// let reply = MessageCallbackData::from("Only you can see this.").ephemeral();
61/// let response = InteractionResponse::ChannelMessageWithSource(Box::new(reply));
62/// assert_eq!(
63/// serde_json::to_string(&response).unwrap(),
64/// r#"{"type":4,"data":{"content":"Only you can see this.","flags":64}}"#
65/// );
66/// ```
67#[derive(Clone, Debug, PartialEq)]
68#[non_exhaustive]
69pub enum InteractionResponse {
70 /// Acknowledges a [`Ping`](super::InteractionData::Ping).
71 Pong,
72 /// Responds with a message.
73 ///
74 /// discord.js counterpart: `reply`.
75 ChannelMessageWithSource(Box<MessageCallbackData>),
76 /// Acknowledges the interaction and shows "thinking…"; the response message is sent later
77 /// by editing the original response.
78 ///
79 /// discord.js counterpart: `deferReply`.
80 DeferredChannelMessageWithSource(DeferredCallbackData),
81 /// Acknowledges a component or modal-submit interaction without a loading state; the
82 /// message is edited later.
83 ///
84 /// discord.js counterpart: `deferUpdate`.
85 DeferredUpdateMessage,
86 /// Edits the message the component is on (component and modal-submit interactions).
87 ///
88 /// discord.js counterpart: `update`.
89 UpdateMessage(Box<MessageCallbackData>),
90 /// Suggests choices to an [`Autocomplete`](super::InteractionData::Autocomplete)
91 /// interaction.
92 ///
93 /// discord.js counterpart: `AutocompleteInteraction#respond`.
94 AutocompleteResult(AutocompleteCallbackData),
95 /// Opens a modal (not available for modal-submit and ping interactions).
96 ///
97 /// discord.js counterpart: `showModal`.
98 Modal(Box<ModalCallbackData>),
99 /// **Deprecated**: responds with an upgrade button (monetized apps); use a premium
100 /// [`Button`](crate::component::Button::Premium) instead.
101 PremiumRequired,
102 /// Launches the app's Activity (apps with Activities).
103 ///
104 /// discord.js counterpart: `launchActivity`.
105 LaunchActivity,
106 /// A response type this version does not know (only produced when decoding); its data is
107 /// not kept.
108 Unknown(InteractionCallbackType),
109}
110
111impl InteractionResponse {
112 /// Returns the files to upload with the response (those of its message data); empty for
113 /// responses without a message.
114 ///
115 /// discord.js counterpart: the `files` of `InteractionReplyOptions`.
116 #[must_use]
117 pub fn files(&self) -> &[FileUpload] {
118 match self {
119 Self::ChannelMessageWithSource(data) | Self::UpdateMessage(data) => &data.files,
120 _ => &[],
121 }
122 }
123
124 /// Returns the response type.
125 ///
126 /// discord.js counterpart: `InteractionResponseType` (discord-api-types).
127 #[must_use]
128 pub const fn kind(&self) -> InteractionCallbackType {
129 match self {
130 Self::Pong => InteractionCallbackType::Pong,
131 Self::ChannelMessageWithSource(_) => InteractionCallbackType::ChannelMessageWithSource,
132 Self::DeferredChannelMessageWithSource(_) => {
133 InteractionCallbackType::DeferredChannelMessageWithSource
134 }
135 Self::DeferredUpdateMessage => InteractionCallbackType::DeferredUpdateMessage,
136 Self::UpdateMessage(_) => InteractionCallbackType::UpdateMessage,
137 Self::AutocompleteResult(_) => {
138 InteractionCallbackType::ApplicationCommandAutocompleteResult
139 }
140 Self::Modal(_) => InteractionCallbackType::Modal,
141 Self::PremiumRequired => InteractionCallbackType::PremiumRequired,
142 Self::LaunchActivity => InteractionCallbackType::LaunchActivity,
143 Self::Unknown(kind) => *kind,
144 }
145 }
146}
147
148impl Serialize for InteractionResponse {
149 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
150 #[derive(Serialize)]
151 #[serde(untagged)]
152 enum Data<'a> {
153 Message(&'a MessageCallbackData),
154 Deferred(&'a DeferredCallbackData),
155 Autocomplete(&'a AutocompleteCallbackData),
156 Modal(&'a ModalCallbackData),
157 }
158
159 #[derive(Serialize)]
160 struct Flat<'a> {
161 #[serde(rename = "type")]
162 kind: InteractionCallbackType,
163 #[serde(skip_serializing_if = "Option::is_none")]
164 data: Option<Data<'a>>,
165 }
166
167 let data = match self {
168 Self::ChannelMessageWithSource(data) | Self::UpdateMessage(data) => {
169 Some(Data::Message(data))
170 }
171 Self::DeferredChannelMessageWithSource(data) if !data.flags.is_empty() => {
172 Some(Data::Deferred(data))
173 }
174 Self::AutocompleteResult(data) => Some(Data::Autocomplete(data)),
175 Self::Modal(data) => Some(Data::Modal(data)),
176 _ => None,
177 };
178 Flat {
179 kind: self.kind(),
180 data,
181 }
182 .serialize(serializer)
183 }
184}
185
186/// Every field of every kind of callback data, decoded in one pass.
187#[derive(Deserialize)]
188struct RawCallbackData {
189 #[serde(default)]
190 tts: bool,
191 #[serde(default)]
192 content: Option<CompactString>,
193 #[serde(default)]
194 embeds: Option<Vec<Embed>>,
195 #[serde(default)]
196 allowed_mentions: Option<AllowedMentions>,
197 #[serde(default)]
198 flags: Option<MessageFlags>,
199 #[serde(default)]
200 components: Option<Vec<Component>>,
201 #[serde(default)]
202 attachments: Option<Vec<AttachmentRequest>>,
203 #[serde(default)]
204 poll: Option<CreatePoll>,
205 #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
206 choices: Vec<Choice<RawValue>>,
207 #[serde(default)]
208 custom_id: Option<CompactString>,
209 #[serde(default)]
210 title: Option<CompactString>,
211}
212
213impl RawCallbackData {
214 fn into_message(self) -> MessageCallbackData {
215 MessageCallbackData {
216 tts: self.tts,
217 content: self.content,
218 embeds: self.embeds,
219 allowed_mentions: self.allowed_mentions,
220 flags: self.flags,
221 components: self.components,
222 attachments: self.attachments,
223 poll: self.poll,
224 files: Vec::new(),
225 }
226 }
227}
228
229#[derive(Deserialize)]
230struct RawResponse {
231 #[serde(rename = "type")]
232 kind: InteractionCallbackType,
233 #[serde(default)]
234 data: Option<RawCallbackData>,
235}
236
237impl<'de> Deserialize<'de> for InteractionResponse {
238 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
239 let raw = RawResponse::deserialize(deserializer)?;
240 let data = raw.data;
241 let missing = || D::Error::missing_field("data");
242 Ok(match raw.kind {
243 InteractionCallbackType::Pong => Self::Pong,
244 InteractionCallbackType::ChannelMessageWithSource => {
245 Self::ChannelMessageWithSource(Box::new(data.ok_or_else(missing)?.into_message()))
246 }
247 InteractionCallbackType::DeferredChannelMessageWithSource => {
248 Self::DeferredChannelMessageWithSource(DeferredCallbackData {
249 flags: data.and_then(|data| data.flags).unwrap_or_default(),
250 })
251 }
252 InteractionCallbackType::DeferredUpdateMessage => Self::DeferredUpdateMessage,
253 InteractionCallbackType::UpdateMessage => Self::UpdateMessage(Box::new(
254 data.map(RawCallbackData::into_message).unwrap_or_default(),
255 )),
256 InteractionCallbackType::ApplicationCommandAutocompleteResult => {
257 let data = data.ok_or_else(missing)?;
258 Self::AutocompleteResult(AutocompleteCallbackData {
259 choices: AutocompleteChoices::from_raw(data.choices)?,
260 })
261 }
262 InteractionCallbackType::Modal => {
263 let data = data.ok_or_else(missing)?;
264 Self::Modal(Box::new(ModalCallbackData {
265 custom_id: data
266 .custom_id
267 .ok_or_else(|| D::Error::missing_field("custom_id"))?,
268 title: data.title.ok_or_else(|| D::Error::missing_field("title"))?,
269 components: data.components.unwrap_or_default(),
270 }))
271 }
272 InteractionCallbackType::PremiumRequired => Self::PremiumRequired,
273 InteractionCallbackType::LaunchActivity => Self::LaunchActivity,
274 kind @ InteractionCallbackType::Unknown(_) => Self::Unknown(kind),
275 })
276 }
277}
278
279/// The [message data of a response](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-messages):
280/// a new message ([`ChannelMessageWithSource`](InteractionResponse::ChannelMessageWithSource))
281/// or the edit of the component's message ([`UpdateMessage`](InteractionResponse::UpdateMessage)).
282///
283/// Every field is optional. For updates, an absent field keeps the message's current value,
284/// while `Some(vec![])` removes all embeds, components or attachments.
285///
286/// discord.js counterpart: `InteractionReplyOptions` / `InteractionUpdateOptions`.
287#[derive(Clone, Debug, Default, PartialEq)]
288#[non_exhaustive]
289pub struct MessageCallbackData {
290 /// Whether the message is read aloud.
291 pub tts: bool,
292 /// The text (up to 2000 characters).
293 pub content: Option<CompactString>,
294 /// The embeds (up to 10).
295 pub embeds: Option<Vec<Embed>>,
296 /// Which mentions in the content notify.
297 pub allowed_mentions: Option<AllowedMentions>,
298 /// Only [`EPHEMERAL`](MessageFlags::EPHEMERAL), [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS),
299 /// [`SUPPRESS_NOTIFICATIONS`](MessageFlags::SUPPRESS_NOTIFICATIONS),
300 /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) and
301 /// [`IS_VOICE_MESSAGE`](MessageFlags::IS_VOICE_MESSAGE) can be set.
302 pub flags: Option<MessageFlags>,
303 /// The components.
304 pub components: Option<Vec<Component>>,
305 /// Explicit attachment entries: for updates, the existing attachments to keep. Every file
306 /// in [`files`](Self::files) gets an entry automatically, unless one with its `files[n]`
307 /// index is listed here (D-094).
308 pub attachments: Option<Vec<AttachmentRequest>>,
309 /// A poll to create with the message.
310 pub poll: Option<CreatePoll>,
311 /// Files to upload with the response (sent as `multipart/form-data`, D-087). Not part of
312 /// the JSON; empty when decoded.
313 pub files: Vec<FileUpload>,
314}
315
316impl Serialize for MessageCallbackData {
317 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
318 #[derive(Serialize)]
319 struct Wire<'a> {
320 #[serde(skip_serializing_if = "core::ops::Not::not")]
321 tts: bool,
322 #[serde(skip_serializing_if = "Option::is_none")]
323 content: Option<&'a CompactString>,
324 #[serde(skip_serializing_if = "Option::is_none")]
325 embeds: Option<&'a [Embed]>,
326 #[serde(skip_serializing_if = "Option::is_none")]
327 allowed_mentions: Option<&'a AllowedMentions>,
328 #[serde(skip_serializing_if = "Option::is_none")]
329 flags: Option<MessageFlags>,
330 #[serde(skip_serializing_if = "Option::is_none")]
331 components: Option<&'a [Component]>,
332 #[serde(skip_serializing_if = "Attachments::is_absent")]
333 attachments: Attachments<'a>,
334 #[serde(skip_serializing_if = "Option::is_none")]
335 poll: Option<&'a CreatePoll>,
336 }
337
338 // Destructured without `..`, so a new field cannot be forgotten here.
339 let Self {
340 tts,
341 content,
342 embeds,
343 allowed_mentions,
344 flags,
345 components,
346 attachments,
347 poll,
348 files,
349 } = self;
350 Wire {
351 tts: *tts,
352 content: content.as_ref(),
353 embeds: embeds.as_deref(),
354 allowed_mentions: allowed_mentions.as_ref(),
355 flags: *flags,
356 components: components.as_deref(),
357 attachments: Attachments::new(attachments.as_deref(), files),
358 poll: poll.as_ref(),
359 }
360 .serialize(serializer)
361 }
362}
363
364setters::message_body!(MessageCallbackData {
365 content,
366 embeds,
367 components,
368 allowed_mentions,
369 flags,
370 ephemeral,
371 suppress_notifications,
372 files,
373 attachments,
374 poll,
375 tts,
376});
377
378/// The data of a [deferred message response](InteractionResponse::DeferredChannelMessageWithSource):
379/// only the flags of the message that follows.
380///
381/// discord.js counterpart: the `data` of `APIInteractionResponseDeferredChannelMessageWithSource` (discord-api-types).
382#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
383#[non_exhaustive]
384pub struct DeferredCallbackData {
385 /// Only [`EPHEMERAL`](MessageFlags::EPHEMERAL) is valid here (the later message is then
386 /// ephemeral).
387 pub flags: MessageFlags,
388}
389
390impl DeferredCallbackData {
391 /// Creates the data with the given flags.
392 ///
393 /// discord.js counterpart: `InteractionDeferReplyOptions`.
394 #[must_use]
395 pub const fn new(flags: MessageFlags) -> Self {
396 Self { flags }
397 }
398}
399
400/// The [data of an autocomplete response](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-autocomplete):
401/// the suggested choices.
402///
403/// discord.js counterpart: `APICommandAutocompleteInteractionResponseCallbackData` (discord-api-types).
404///
405/// # Examples
406///
407/// ```
408/// use djs_model::{
409/// application_command::Choice,
410/// interaction::{AutocompleteCallbackData, AutocompleteChoices, InteractionResponse},
411/// };
412///
413/// let response = InteractionResponse::AutocompleteResult(AutocompleteCallbackData::new(
414/// AutocompleteChoices::Integer(vec![Choice::new("Ten", 10), Choice::new("Twenty", 20)]),
415/// ));
416/// assert_eq!(
417/// serde_json::to_string(&response).unwrap(),
418/// r#"{"type":8,"data":{"choices":[{"name":"Ten","value":10},{"name":"Twenty","value":20}]}}"#
419/// );
420/// ```
421#[derive(Clone, Debug, PartialEq, Serialize)]
422#[non_exhaustive]
423pub struct AutocompleteCallbackData {
424 /// The choices (up to 25; empty for "no suggestions").
425 pub choices: AutocompleteChoices,
426}
427
428impl AutocompleteCallbackData {
429 /// Creates the data.
430 ///
431 /// discord.js counterpart: `AutocompleteInteraction#respond`.
432 #[must_use]
433 pub const fn new(choices: AutocompleteChoices) -> Self {
434 Self { choices }
435 }
436}
437
438/// Autocomplete suggestions, typed like the option being completed.
439///
440/// discord.js counterpart: the `choices` of `APICommandAutocompleteInteractionResponseCallbackData` (discord-api-types).
441#[derive(Clone, Debug, PartialEq, Serialize)]
442#[serde(untagged)]
443#[non_exhaustive]
444pub enum AutocompleteChoices {
445 /// Choices of a string option.
446 String(Vec<Choice<CompactString>>),
447 /// Choices of an integer option.
448 Integer(Vec<Choice<i64>>),
449 /// Choices of a number option.
450 Number(Vec<Choice<f64>>),
451}
452
453impl AutocompleteChoices {
454 /// Types decoded choices: strings stay strings, integers stay integers, and a list with
455 /// any fractional number is a number list (an empty list is a string list).
456 fn from_raw<E: DeError>(choices: Vec<Choice<RawValue>>) -> Result<Self, E> {
457 Ok(match choices.first().map(|choice| &choice.value) {
458 None | Some(RawValue::String(_)) => {
459 Self::String(convert_choices(choices, RawValue::into_string)?)
460 }
461 Some(_)
462 if choices
463 .iter()
464 .any(|choice| matches!(choice.value, RawValue::Float(_))) =>
465 {
466 Self::Number(convert_choices(choices, RawValue::into_number)?)
467 }
468 Some(_) => Self::Integer(convert_choices(choices, RawValue::into_integer)?),
469 })
470 }
471}
472
473/// The [data of a modal response](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-modal):
474/// the popup's ID, title and components.
475///
476/// discord.js counterpart: `ModalBuilder` (what `showModal` sends).
477///
478/// # Examples
479///
480/// ```
481/// use djs_model::{
482/// component::{Label, TextInput, TextInputStyle},
483/// interaction::{InteractionResponse, ModalCallbackData},
484/// };
485///
486/// let input = TextInput::new("feedback", TextInputStyle::Paragraph);
487/// let modal = ModalCallbackData::new(
488/// "feedback_modal",
489/// "Feedback",
490/// vec![Label::new("Your feedback", input.into()).into()],
491/// );
492/// let json = serde_json::to_value(InteractionResponse::Modal(Box::new(modal))).unwrap();
493/// assert_eq!(json["type"], 9);
494/// assert_eq!(json["data"]["components"][0]["component"]["custom_id"], "feedback");
495/// ```
496#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
497#[non_exhaustive]
498pub struct ModalCallbackData {
499 /// The modal's custom ID (1-100 characters), sent back in
500 /// [`ModalSubmitData::custom_id`](super::ModalSubmitData::custom_id).
501 pub custom_id: CompactString,
502 /// The title (max 45 characters).
503 pub title: CompactString,
504 /// The components (1-5): labels, text displays and (deprecated) action rows with text
505 /// inputs.
506 pub components: Vec<Component>,
507}
508
509impl ModalCallbackData {
510 /// Creates the data.
511 ///
512 /// discord.js counterpart: `ModalBuilder` (`@discordjs/builders`).
513 #[must_use]
514 pub fn new(
515 custom_id: impl Into<CompactString>,
516 title: impl Into<CompactString>,
517 components: Vec<Component>,
518 ) -> Self {
519 Self {
520 custom_id: custom_id.into(),
521 title: title.into(),
522 components,
523 }
524 }
525}
526
527/// The [callback response](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-callback-interaction-callback-response-object)
528/// Discord returns for a response sent with `with_response=true`.
529///
530/// discord.js counterpart: `InteractionCallbackResponse`.
531#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
532#[non_exhaustive]
533pub struct InteractionCallbackResponse {
534 /// The interaction that was responded to.
535 pub interaction: InteractionCallback,
536 /// What the response created.
537 #[serde(default, skip_serializing_if = "Option::is_none")]
538 pub resource: Option<CallbackResource>,
539}
540
541/// The [interaction](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-callback-interaction-callback-object)
542/// a callback response belongs to.
543///
544/// discord.js counterpart: `InteractionCallback`.
545#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
546#[non_exhaustive]
547pub struct InteractionCallback {
548 /// The interaction's ID.
549 pub id: InteractionId,
550 /// The interaction's type.
551 #[serde(rename = "type")]
552 pub kind: InteractionType,
553 /// The Activity instance that was launched or joined.
554 #[serde(default, skip_serializing_if = "Option::is_none")]
555 pub activity_instance_id: Option<CompactString>,
556 /// The message the response created.
557 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub response_message_id: Option<MessageId>,
559 /// Whether the message is in a loading state (deferred responses).
560 #[serde(default, skip_serializing_if = "Option::is_none")]
561 pub response_message_loading: Option<bool>,
562 /// Whether the message is ephemeral.
563 #[serde(default, skip_serializing_if = "Option::is_none")]
564 pub response_message_ephemeral: Option<bool>,
565}
566
567/// The [resource](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-callback-interaction-callback-resource-object)
568/// a response created.
569///
570/// discord.js counterpart: `InteractionCallbackResource`.
571#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
572#[non_exhaustive]
573pub struct CallbackResource {
574 /// The response type.
575 #[serde(rename = "type")]
576 pub kind: InteractionCallbackType,
577 /// The launched Activity ([`LaunchActivity`](InteractionCallbackType::LaunchActivity)).
578 #[serde(default, skip_serializing_if = "Option::is_none")]
579 pub activity_instance: Option<ActivityInstanceResource>,
580 /// The created or updated message
581 /// ([`ChannelMessageWithSource`](InteractionCallbackType::ChannelMessageWithSource),
582 /// [`UpdateMessage`](InteractionCallbackType::UpdateMessage)).
583 #[serde(default, skip_serializing_if = "Option::is_none")]
584 pub message: Option<Box<Message>>,
585}
586
587/// The [Activity instance](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-callback-interaction-callback-activity-instance-resource)
588/// a [`LaunchActivity`](InteractionResponse::LaunchActivity) response launched.
589///
590/// discord.js counterpart: `RESTAPIInteractionCallbackActivityInstanceResource` (discord-api-types).
591#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
592#[non_exhaustive]
593pub struct ActivityInstanceResource {
594 /// The instance ID.
595 pub id: CompactString,
596}