1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use std::collections::HashMap;
use serde::{Serialize, ser::SerializeMap};
use crate::types::{
AllowedMentions, Component, Container, Embed, File, MessageFlags, PartialAttachment, PollCreate,
};
const TYPE_KEY: &str = "type";
const DATA_KEY: &str = "data";
/// [Interaction Response Structure](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-interaction-response-structure)
#[derive(Debug, Clone)]
pub enum InteractionResponse {
/// ACK to a `ping`
Pong,
/// Respond to an interaction with a message
ChannelMessageWithSource(MessageCallbackData),
/// ACK an interaction and edit a response later, the user sees a loading state. The flags
/// (only `EPHEMERAL`) decide whether the eventual response is ephemeral.
DeferredChannelMessageWithSource(Option<MessageFlags>),
/// for components, ACK an interaction and edit the original message later; the user does not see a loading state
DeferredUpdateMessage,
/// for components, edit the message the component was attached to
UpdateMessage(MessageCallbackData),
/// respond to an autocomplete interaction with suggested choices
ApplicationCommandAutocompleteResult(AutocompleteCallbackData),
/// respond to an interaction with a popup modal
Modal(ModalCallbackData),
}
impl InteractionResponse {
/// A message with `content`
pub fn respond_with_message(content: String) -> Self {
InteractionResponse::ChannelMessageWithSource(MessageCallbackData {
content: Some(content),
..Default::default()
})
}
/// Respond with a message only the invoking user can see
pub fn respond_with_ephemeral_message(content: String) -> Self {
InteractionResponse::ChannelMessageWithSource(MessageCallbackData {
content: Some(content),
flags: Some(MessageFlags::Ephemeral),
..Default::default()
})
}
/// A message with one embed
pub fn respond_with_embed(embed: Embed) -> Self {
InteractionResponse::ChannelMessageWithSource(MessageCallbackData {
embeds: Some(vec![embed]),
..Default::default()
})
}
/// Respond with a [Components V2](https://discord.com/developers/docs/components/reference)
/// message laid out by `components` (containers, text displays, action rows); it has no
/// content or embeds
pub fn respond_with_components(components: Vec<Component>) -> Self {
InteractionResponse::ChannelMessageWithSource(MessageCallbackData::components_v2(
components,
))
}
/// The message data of a message response (types 4 and 7)
pub fn message_data(&self) -> Option<&MessageCallbackData> {
match self {
InteractionResponse::ChannelMessageWithSource(data)
| InteractionResponse::UpdateMessage(data) => Some(data),
_ => None,
}
}
/// The message of a message response (new or update), to change it
pub fn message_data_mut(&mut self) -> Option<&mut MessageCallbackData> {
match self {
InteractionResponse::ChannelMessageWithSource(data)
| InteractionResponse::UpdateMessage(data) => Some(data),
_ => None,
}
}
/// The message of a message response (new or update)
pub fn into_message_data(self) -> Option<MessageCallbackData> {
match self {
InteractionResponse::ChannelMessageWithSource(data)
| InteractionResponse::UpdateMessage(data) => Some(data),
_ => None,
}
}
/// Files to upload with a message response; none for other types
pub fn files(&self) -> &[File] {
self.message_data().map_or(&[], |data| &data.files)
}
/// Attaches a file to a message response; no-op for other types
pub fn with_file(mut self, file: File) -> Self {
if let Some(data) = self.message_data_mut() {
data.files.push(file);
}
self
}
/// Autocomplete suggestions (max 25)
pub fn respond_with_autocomplete_choices(choices: Vec<ApplicationCommandOptionChoice>) -> Self {
InteractionResponse::ApplicationCommandAutocompleteResult(AutocompleteCallbackData {
choices,
})
}
}
impl Serialize for InteractionResponse {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_map(Some(2))?;
match self {
InteractionResponse::Pong => {
map.serialize_entry(TYPE_KEY, &1)?;
}
InteractionResponse::ChannelMessageWithSource(data) => {
map.serialize_entry(TYPE_KEY, &4)?;
map.serialize_entry(DATA_KEY, &data)?;
}
InteractionResponse::DeferredChannelMessageWithSource(flags) => {
map.serialize_entry(TYPE_KEY, &5)?;
if let Some(flags) = flags {
map.serialize_entry(DATA_KEY, &DeferredData { flags })?;
}
}
InteractionResponse::DeferredUpdateMessage => {
map.serialize_entry(TYPE_KEY, &6)?;
}
InteractionResponse::UpdateMessage(data) => {
map.serialize_entry(TYPE_KEY, &7)?;
map.serialize_entry(DATA_KEY, &data)?;
}
InteractionResponse::ApplicationCommandAutocompleteResult(data) => {
map.serialize_entry(TYPE_KEY, &8)?;
map.serialize_entry(DATA_KEY, &data)?;
}
InteractionResponse::Modal(data) => {
map.serialize_entry(TYPE_KEY, &9)?;
map.serialize_entry(DATA_KEY, &data)?;
}
};
map.end()
}
}
#[derive(Serialize)]
struct DeferredData<'a> {
flags: &'a MessageFlags,
}
/// [Message Callback Data Structure](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-messages)
#[derive(Debug, Clone, Default, Serialize)]
pub struct MessageCallbackData {
/// is the response TTS
#[serde(skip_serializing_if = "Option::is_none")]
pub tts: Option<bool>,
/// message content
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
/// supports up to 10 embeds
#[serde(skip_serializing_if = "Option::is_none")]
pub embeds: Option<Vec<Embed>>,
/// [allowed mentions](https://discord.com/developers/docs/resources/channel#allowed-mentions-object) object
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_mentions: Option<AllowedMentions>,
/// [message flags](https://discord.com/developers/docs/resources/channel#message-object-message-flags) combined as a [bitfield](https://en.wikipedia.org/wiki/Bit_field) (only SUPPRESS_EMBEDS, EPHEMERAL, SUPPRESS_NOTIFICATIONS and IS_COMPONENTS_V2 can be set)
#[serde(skip_serializing_if = "Option::is_none")]
pub flags: Option<MessageFlags>,
/// message components: action rows, or with
/// [`IS_COMPONENTS_V2`](MessageFlags::IsComponentsV2) the whole message (containers, text
/// displays, ...)
#[serde(skip_serializing_if = "Option::is_none")]
pub components: Option<Vec<Component>>,
/// attachment objects with filename and description
#[serde(skip_serializing_if = "Option::is_none")]
pub attachments: Option<Vec<PartialAttachment>>,
/// a poll sent with the message
#[serde(skip_serializing_if = "Option::is_none")]
pub poll: Option<PollCreate>,
/// files to upload; sent as multipart, so the Adapter answers through the callback endpoint
#[serde(skip)]
pub files: Vec<File>,
/// Leave the embeds as they are instead of filling in the App's
/// [`Theme`](crate::command::Theme); set by [`Unthemed`](crate::command::Unthemed)
#[serde(skip)]
pub unthemed: bool,
}
impl MessageCallbackData {
/// A [Components V2](https://discord.com/developers/docs/components/reference) message laid
/// out by `components`. Leave `content`, `embeds` and `poll` unset: Discord rejects them
/// alongside [`IS_COMPONENTS_V2`](MessageFlags::IsComponentsV2); use text displays instead.
/// Handler responses and deferred edits that set them fail with a [`HandlerError`](crate::command::HandlerError).
pub fn components_v2(components: Vec<Component>) -> Self {
MessageCallbackData {
components: Some(components),
flags: Some(MessageFlags::IsComponentsV2),
..Default::default()
}
}
/// Whether the message is laid out with Components V2
pub fn is_components_v2(&self) -> bool {
self.flags
.is_some_and(|flags| flags.contains(MessageFlags::IsComponentsV2))
}
/// The top-level [`Container`]s of the message
pub fn containers_mut(&mut self) -> impl Iterator<Item = &mut Container> {
self.components
.iter_mut()
.flatten()
.filter_map(|component| match component {
Component::Container(container) => Some(container),
_ => None,
})
}
}
/// Suggestions answering an autocomplete Interaction
#[derive(Debug, Clone, Serialize)]
pub struct AutocompleteCallbackData {
/// autocomplete choices (max of 25 choices)
pub choices: Vec<ApplicationCommandOptionChoice>,
}
/// [Application Command Option Choice Structure](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-choice-structure)
#[derive(Debug, Clone, Serialize)]
pub struct ApplicationCommandOptionChoice {
/// 1-100 character choice name
pub name: String,
/// Localization dictionary for the name field. Values follow the same restrictions as name
#[serde(skip_serializing_if = "Option::is_none")]
pub name_localizations: Option<HashMap<String, String>>,
/// Value for the choice, up to 100 characters if string
pub value: ApplicationCommandOptionChoiceValue,
}
/// A Choice's value, typed like its Option
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ApplicationCommandOptionChoiceValue {
/// For string Options
String(String),
/// For integer Options
Integer(i64),
/// For number Options
Double(f64),
}
/// [Modal](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-modal)
#[derive(Debug, Clone, Serialize)]
pub struct ModalCallbackData {
/// a developer-defined identifier for the modal, max 100 characters
pub custom_id: String,
/// the title of the popup modal, max 45 characters
pub title: String,
/// 1-5 top-level components: [`Label`](crate::types::Label)s wrapping inputs, and text
/// displays (action rows with text inputs are deprecated)
#[serde(skip_serializing_if = "Option::is_none")]
pub components: Option<Vec<Component>>,
/// is the response TTS
#[serde(skip_serializing_if = "Option::is_none")]
pub tts: Option<bool>,
/// message content
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
/// supports up to 10 embeds
#[serde(skip_serializing_if = "Option::is_none")]
pub embeds: Option<Vec<Embed>>,
/// [allowed mentions](https://discord.com/developers/docs/resources/channel#allowed-mentions-object) object
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_mentions: Option<AllowedMentions>,
/// [message flags](https://discord.com/developers/docs/resources/channel#message-object-message-flags) combined as a [bitfield](https://en.wikipedia.org/wiki/Bit_field) (only SUPPRESS_EMBEDS and EPHEMERAL can be set)
#[serde(skip_serializing_if = "Option::is_none")]
pub flags: Option<MessageFlags>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn serialize_test() {
let response = InteractionResponse::ChannelMessageWithSource(MessageCallbackData {
content: Some(String::from("hello")),
..Default::default()
});
println!("{}", serde_json::to_string_pretty(&response).unwrap());
}
#[test]
pub fn serialize_deferred() {
assert_eq!(
serde_json::to_value(InteractionResponse::DeferredChannelMessageWithSource(None))
.unwrap(),
serde_json::json!({ "type": 5 })
);
assert_eq!(
serde_json::to_value(InteractionResponse::DeferredChannelMessageWithSource(Some(
MessageFlags::Ephemeral
)))
.unwrap(),
serde_json::json!({ "type": 5, "data": { "flags": 64 } })
);
}
#[test]
pub fn serialize_components_v2() {
let container = Container::new(vec![Component::text("hi")])
.with_accent_color(0xff0000)
.spoiler();
let response = InteractionResponse::respond_with_components(vec![container.into()]);
let json = serde_json::json!({ "type": 4, "data": {
"flags": 1 << 15,
"components": [{
"type": 17,
"components": [{ "type": 10, "content": "hi" }],
"accent_color": 0xff0000,
"spoiler": true,
}],
}});
assert_eq!(serde_json::to_value(&response).unwrap(), json);
let parsed: Component = serde_json::from_value(json["data"]["components"][0].clone())
.expect("container deserializes");
let Component::Container(container) = parsed else {
panic!("not a container");
};
assert_eq!(container.accent_color, Some(0xff0000));
assert!(matches!(container.components[0], Component::TextDisplay(_)));
}
#[test]
pub fn serialize_ephemeral_message() {
let response = InteractionResponse::respond_with_ephemeral_message(String::from("hello"));
assert_eq!(
serde_json::to_value(&response).unwrap(),
serde_json::json!({ "type": 4, "data": { "content": "hello", "flags": 64 } })
);
}
}