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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use super::create_poll::Ready;
#[cfg(feature = "http")]
use super::{check_overflow, Builder};
use super::{
CreateActionRow,
CreateAllowedMentions,
CreateAttachment,
CreateEmbed,
CreatePoll,
EditAttachments,
};
#[cfg(feature = "http")]
use crate::constants;
#[cfg(feature = "http")]
use crate::http::CacheHttp;
use crate::internal::prelude::*;
use crate::model::prelude::*;
/// [Discord docs](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object).
#[derive(Clone, Debug)]
pub enum CreateInteractionResponse {
/// Acknowledges a Ping (only required when your bot uses an HTTP endpoint URL).
///
/// Corresponds to Discord's `PONG`.
Pong,
/// Responds to an interaction with a message.
///
/// Corresponds to Discord's `CHANNEL_MESSAGE_WITH_SOURCE`.
Message(CreateInteractionResponseMessage),
/// Acknowledges the interaction in order to edit a response later. The user sees a loading
/// state.
///
/// Corresponds to Discord's `DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE`.
Defer(CreateInteractionResponseMessage),
/// Only valid for component-based interactions (seems to work for modal submit interactions
/// too even though it's not documented).
///
/// Acknowledges the interaction. You can optionally edit the original message later. The user
/// does not see a loading state.
///
/// Corresponds to Discord's `DEFERRED_UPDATE_MESSAGE`.
Acknowledge,
/// Only valid for component-based interactions.
///
/// Edits the message the component was attached to.
///
/// Corresponds to Discord's `UPDATE_MESSAGE`.
UpdateMessage(CreateInteractionResponseMessage),
/// Only valid for autocomplete interactions.
///
/// Responds to the autocomplete interaction with suggested choices.
///
/// Corresponds to Discord's `APPLICATION_COMMAND_AUTOCOMPLETE_RESULT`.
Autocomplete(CreateAutocompleteResponse),
/// Not valid for Modal and Ping interactions
///
/// Responds to the interaction with a popup modal.
///
/// Corresponds to Discord's `MODAL`.
Modal(CreateModal),
/// Not valid for autocomplete and Ping interactions. Only available for applications with
/// monetization enabled.
///
/// Responds to the interaction with an upgrade button.
///
/// Corresponds to Discord's `PREMIUM_REQUIRED'.
#[deprecated = "use premium button components via `CreateButton::new_premium` instead"]
PremiumRequired,
/// Not valid for autocomplete and Ping interactions. Only available for applications with
/// Activities enabled.
///
/// Responds to the interaction by launching the Activity associated with the app.
///
/// Corresponds to Discord's `LAUNCH_ACTIVITY`.
LaunchActivity,
}
impl serde::Serialize for CreateInteractionResponse {
#[allow(deprecated)] // We have to cover deprecated variants
fn serialize<S: serde::Serializer>(&self, serializer: S) -> StdResult<S::Ok, S::Error> {
use serde::ser::SerializeMap as _;
let mut map = serializer.serialize_map(Some(2))?;
map.serialize_entry("type", &match self {
Self::Pong => 1,
Self::Message(_) => 4,
Self::Defer(_) => 5,
Self::Acknowledge => 6,
Self::UpdateMessage(_) => 7,
Self::Autocomplete(_) => 8,
Self::Modal(_) => 9,
Self::PremiumRequired => 10,
Self::LaunchActivity => 12,
})?;
match self {
Self::Autocomplete(x) => map.serialize_entry("data", &x)?,
Self::Modal(x) => map.serialize_entry("data", &x)?,
Self::Message(x) | Self::Defer(x) | Self::UpdateMessage(x) => {
map.serialize_entry("data", &x)?;
},
Self::Pong | Self::Acknowledge | Self::PremiumRequired | Self::LaunchActivity => {
map.serialize_entry("data", &None::<()>)?;
},
}
map.end()
}
}
impl CreateInteractionResponse {
#[cfg(feature = "http")]
fn check_length(&self) -> Result<()> {
if let CreateInteractionResponse::Message(data)
| CreateInteractionResponse::Defer(data)
| CreateInteractionResponse::UpdateMessage(data) = self
{
if let Some(content) = &data.content {
check_overflow(content.chars().count(), constants::MESSAGE_CODE_LIMIT)
.map_err(|overflow| Error::Model(ModelError::MessageTooLong(overflow)))?;
}
if let Some(embeds) = &data.embeds {
check_overflow(embeds.len(), constants::EMBED_MAX_COUNT)
.map_err(|_| Error::Model(ModelError::EmbedAmount))?;
for embed in embeds {
embed.check_length()?;
}
}
}
Ok(())
}
}
#[cfg(feature = "http")]
#[async_trait::async_trait]
impl Builder for CreateInteractionResponse {
type Context<'ctx> = (InteractionId, &'ctx str);
type Built = ();
/// Creates a response to the interaction received.
///
/// **Note**: Message contents must be under 2000 unicode code points, and embeds must be under
/// 6000 code points.
///
/// # Errors
///
/// Returns an [`Error::Model`] if the message content is too long. May also return an
/// [`Error::Http`] if the API returns an error, or an [`Error::Json`] if there is an error in
/// deserializing the API response.
async fn execute(
mut self,
cache_http: impl CacheHttp,
ctx: Self::Context<'_>,
) -> Result<Self::Built> {
self.check_length()?;
let files = match &mut self {
CreateInteractionResponse::Message(msg)
| CreateInteractionResponse::Defer(msg)
| CreateInteractionResponse::UpdateMessage(msg) => msg.attachments.take_files(),
_ => Vec::new(),
};
let http = cache_http.http();
if let Self::Message(msg) | Self::Defer(msg) | Self::UpdateMessage(msg) = &mut self {
if msg.allowed_mentions.is_none() {
msg.allowed_mentions.clone_from(&http.default_allowed_mentions);
}
}
http.create_interaction_response(ctx.0, ctx.1, &self, files).await
}
}
/// [Discord docs](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-messages).
#[derive(Clone, Debug, Default, Serialize)]
#[must_use]
pub struct CreateInteractionResponseMessage {
#[serde(skip_serializing_if = "Option::is_none")]
tts: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
embeds: Option<Vec<CreateEmbed>>,
#[serde(skip_serializing_if = "Option::is_none")]
allowed_mentions: Option<CreateAllowedMentions>,
#[serde(skip_serializing_if = "Option::is_none")]
flags: Option<InteractionResponseFlags>,
#[serde(skip_serializing_if = "Option::is_none")]
components: Option<Vec<CreateActionRow>>,
#[serde(skip_serializing_if = "Option::is_none")]
poll: Option<CreatePoll<Ready>>,
attachments: EditAttachments,
}
impl CreateInteractionResponseMessage {
/// Equivalent to [`Self::default`].
pub fn new() -> Self {
Self::default()
}
/// Set whether the message is text-to-speech.
///
/// Think carefully before setting this to `true`.
///
/// Defaults to `false`.
pub fn tts(mut self, tts: bool) -> Self {
self.tts = Some(tts);
self
}
/// Appends a file to the message.
pub fn add_file(mut self, file: CreateAttachment) -> Self {
self.attachments = self.attachments.add(file);
self
}
/// Appends a list of files to the message.
pub fn add_files(mut self, files: impl IntoIterator<Item = CreateAttachment>) -> Self {
for file in files {
self.attachments = self.attachments.add(file);
}
self
}
/// Sets a list of files to include in the message.
///
/// Calling this multiple times will overwrite the file list. To append files, call
/// [`Self::add_file`] or [`Self::add_files`] instead.
pub fn files(mut self, files: impl IntoIterator<Item = CreateAttachment>) -> Self {
self.attachments = EditAttachments::new();
self.add_files(files)
}
/// Set the content of the message.
///
/// **Note**: Message contents must be under 2000 unicode code points.
#[inline]
pub fn content(mut self, content: impl Into<String>) -> Self {
self.content = Some(content.into());
self
}
/// Adds an embed to the message.
///
/// Calling this while editing a message will overwrite existing embeds.
pub fn add_embed(mut self, embed: CreateEmbed) -> Self {
self.embeds.get_or_insert_with(Vec::new).push(embed);
self
}
/// Adds multiple embeds for the message.
///
/// Calling this while editing a message will overwrite existing embeds.
pub fn add_embeds(mut self, embeds: Vec<CreateEmbed>) -> Self {
self.embeds.get_or_insert_with(Vec::new).extend(embeds);
self
}
/// Sets a single embed to include in the message
///
/// Calling this will overwrite the embed list. To append embeds, call [`Self::add_embed`]
/// instead.
pub fn embed(self, embed: CreateEmbed) -> Self {
self.embeds(vec![embed])
}
/// Sets a list of embeds to include in the message.
///
/// Calling this will overwrite the embed list. To append embeds, call [`Self::add_embeds`]
/// instead.
pub fn embeds(mut self, embeds: Vec<CreateEmbed>) -> Self {
self.embeds = Some(embeds);
self
}
/// Set the allowed mentions for the message.
pub fn allowed_mentions(mut self, allowed_mentions: CreateAllowedMentions) -> Self {
self.allowed_mentions = Some(allowed_mentions);
self
}
/// Sets the flags for the message.
pub fn flags(mut self, flags: InteractionResponseFlags) -> Self {
self.flags = Some(flags);
self
}
/// Adds or removes the ephemeral flag.
pub fn ephemeral(mut self, ephemeral: bool) -> Self {
let mut flags = self.flags.unwrap_or_else(InteractionResponseFlags::empty);
if ephemeral {
flags |= InteractionResponseFlags::EPHEMERAL;
} else {
flags &= !InteractionResponseFlags::EPHEMERAL;
}
self.flags = Some(flags);
self
}
/// Sets the components of this message.
pub fn components(mut self, components: Vec<CreateActionRow>) -> Self {
self.components = Some(components);
self
}
/// Adds a poll to the message. Only one poll can be added per message.
///
/// See [`CreatePoll`] for more information on creating and configuring a poll.
pub fn poll(mut self, poll: CreatePoll<Ready>) -> Self {
self.poll = Some(poll);
self
}
super::button_and_select_menu_convenience_methods!(self.components);
}
// Same as CommandOptionChoice according to Discord, see
// [Autocomplete docs](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-autocomplete).
#[must_use]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct AutocompleteChoice(CommandOptionChoice);
impl AutocompleteChoice {
pub fn new(name: impl Into<String>, value: impl Into<Value>) -> Self {
Self(CommandOptionChoice {
name: name.into(),
name_localizations: None,
value: value.into(),
})
}
pub fn add_localized_name(
mut self,
locale: impl Into<String>,
localized_name: impl Into<String>,
) -> Self {
self.0
.name_localizations
.get_or_insert_with(Default::default)
.insert(locale.into(), localized_name.into());
self
}
}
impl<S: Into<String>> From<S> for AutocompleteChoice {
fn from(value: S) -> Self {
let value = value.into();
let name = value.clone();
Self::new(name, value)
}
}
/// [Discord docs](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-autocomplete)
#[derive(Clone, Debug, Default, Serialize)]
#[must_use]
pub struct CreateAutocompleteResponse {
choices: Vec<AutocompleteChoice>,
}
impl CreateAutocompleteResponse {
/// Equivalent to [`Self::default`].
pub fn new() -> Self {
Self::default()
}
/// For autocomplete responses this sets their autocomplete suggestions.
///
/// See the official docs on [`Application Command Option Choices`] for more information.
///
/// [`Application Command Option Choices`]: https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-choice-structure
pub fn set_choices(mut self, choices: Vec<AutocompleteChoice>) -> Self {
self.choices = choices;
self
}
/// Add an int autocomplete choice.
///
/// **Note**: There can be no more than 25 choices set. Name must be between 1 and 100
/// characters. Value must be between -2^53 and 2^53.
pub fn add_int_choice(self, name: impl Into<String>, value: i64) -> Self {
self.add_choice(AutocompleteChoice::new(name, value))
}
/// Adds a string autocomplete choice.
///
/// **Note**: There can be no more than 25 choices set. Name must be between 1 and 100
/// characters. Value must be up to 100 characters.
pub fn add_string_choice(self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.add_choice(AutocompleteChoice::new(name, value.into()))
}
/// Adds a number autocomplete choice.
///
/// **Note**: There can be no more than 25 choices set. Name must be between 1 and 100
/// characters. Value must be between -2^53 and 2^53.
pub fn add_number_choice(self, name: impl Into<String>, value: f64) -> Self {
self.add_choice(AutocompleteChoice::new(name, value))
}
fn add_choice(mut self, value: AutocompleteChoice) -> Self {
self.choices.push(value);
self
}
}
#[cfg(feature = "http")]
#[async_trait::async_trait]
impl Builder for CreateAutocompleteResponse {
type Context<'ctx> = (InteractionId, &'ctx str);
type Built = ();
/// Creates a response to an autocomplete interaction.
///
/// # Errors
///
/// Returns an [`Error::Http`] if the API returns an error.
async fn execute(
self,
cache_http: impl CacheHttp,
ctx: Self::Context<'_>,
) -> Result<Self::Built> {
cache_http.http().create_interaction_response(ctx.0, ctx.1, &self, Vec::new()).await
}
}
/// [Discord docs](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-modal).
#[derive(Clone, Debug, Default, Serialize)]
#[must_use]
pub struct CreateModal {
components: Vec<CreateActionRow>,
custom_id: String,
title: String,
}
impl CreateModal {
/// Creates a new modal.
pub fn new(custom_id: impl Into<String>, title: impl Into<String>) -> Self {
Self {
components: Vec::new(),
custom_id: custom_id.into(),
title: title.into(),
}
}
/// Sets the components of this message.
///
/// Overwrites existing components.
pub fn components(mut self, components: Vec<CreateActionRow>) -> Self {
self.components = components;
self
}
}