Skip to main content

djs_model/
application_command.rs

1//! [Application commands](https://docs.discord.com/developers/interactions/application-commands):
2//! slash commands, user and message context menu commands, and Activity entry points.
3//!
4//! These are the commands as Discord returns them (`GET .../commands`). Their options are an
5//! enum keyed by option type (D-069), with typed choices.
6
7use std::collections::BTreeMap;
8
9use compact_str::CompactString;
10use serde::{
11    Deserialize, Deserializer, Serialize, Serializer,
12    de::{Error as DeError, Unexpected, Visitor},
13};
14
15use crate::{
16    application::IntegrationType,
17    channel::ChannelType,
18    id::{ApplicationId, CommandId, CommandVersionId, GenericId, GuildId},
19    interaction::InteractionContextType,
20    macros::int_enum,
21    permissions::Permissions,
22    util::Locale,
23};
24
25/// An [application command](https://docs.discord.com/developers/interactions/application-commands#application-command-object).
26///
27/// Contains floats (number option bounds and choices), so it is `PartialEq` but not `Eq`
28/// (D-064).
29///
30/// discord.js counterpart: `ApplicationCommand`.
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32#[non_exhaustive]
33pub struct ApplicationCommand {
34    /// The command's ID.
35    pub id: CommandId,
36    /// The kind of command (Discord's default: [`ChatInput`](CommandType::ChatInput)).
37    #[serde(rename = "type", default)]
38    pub kind: CommandType,
39    /// The application that owns the command.
40    pub application_id: ApplicationId,
41    /// The guild of a guild command (`None` for global commands).
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub guild_id: Option<GuildId>,
44    /// The command's name (1-32 characters; lowercase for slash commands).
45    pub name: CompactString,
46    /// Translations of the name, keyed by locale (D-058).
47    #[serde(
48        default,
49        skip_serializing_if = "BTreeMap::is_empty",
50        deserialize_with = "crate::serde_util::null_as_default"
51    )]
52    pub name_localizations: BTreeMap<Locale, CompactString>,
53    /// The description (1-100 characters; empty for user and message commands).
54    #[serde(default)]
55    pub description: CompactString,
56    /// Translations of the description, keyed by locale (D-058).
57    #[serde(
58        default,
59        skip_serializing_if = "BTreeMap::is_empty",
60        deserialize_with = "crate::serde_util::null_as_default"
61    )]
62    pub description_localizations: BTreeMap<Locale, CompactString>,
63    /// The name in the requester's locale, returned instead of
64    /// [`name_localizations`](Self::name_localizations) by the endpoints that list commands
65    /// (unless asked for the full translations).
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub name_localized: Option<CompactString>,
68    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub description_localized: Option<CompactString>,
71    /// The parameters of a slash command (max 25).
72    #[serde(
73        default,
74        skip_serializing_if = "Vec::is_empty",
75        deserialize_with = "crate::serde_util::null_as_default"
76    )]
77    pub options: Vec<CommandOption>,
78    /// The permissions a member needs by default (`None`: everyone; empty: administrators
79    /// only). Guild admins can override them.
80    #[serde(default)]
81    pub default_member_permissions: Option<Permissions>,
82    /// Whether the command is available in DMs. **Deprecated** by Discord in favor of
83    /// [`contexts`](Self::contexts).
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub dm_permission: Option<bool>,
86    /// Whether the command is enabled by default. **Deprecated** by Discord in favor of
87    /// [`default_member_permissions`](Self::default_member_permissions).
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub default_permission: Option<bool>,
90    /// Whether the command is age-restricted.
91    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
92    pub nsfw: bool,
93    /// The installation contexts the command is available in.
94    #[serde(
95        default,
96        skip_serializing_if = "Vec::is_empty",
97        deserialize_with = "crate::serde_util::null_as_default"
98    )]
99    pub integration_types: Vec<IntegrationType>,
100    /// The interaction contexts the command can be used in.
101    #[serde(
102        default,
103        skip_serializing_if = "Vec::is_empty",
104        deserialize_with = "crate::serde_util::null_as_default"
105    )]
106    pub contexts: Vec<InteractionContextType>,
107    /// An auto-incrementing version, updated on substantial changes.
108    pub version: CommandVersionId,
109    /// Who handles a primary entry point command.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub handler: Option<EntryPointHandlerType>,
112}
113
114int_enum! {
115    /// The [type of an application command](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-types).
116    ///
117    /// discord.js counterpart: `ApplicationCommandType`.
118    #[doc(alias = "ApplicationCommandType")]
119    #[derive(Default)]
120    pub enum CommandType: u8 {
121        /// A slash command, shown when typing `/`.
122        #[default]
123        ChatInput = 1,
124        /// A context menu command on users.
125        User = 2,
126        /// A context menu command on messages.
127        Message = 3,
128        /// The primary way to launch the app's Activity.
129        PrimaryEntryPoint = 4,
130    }
131}
132
133int_enum! {
134    /// [Who handles a primary entry point command](https://docs.discord.com/developers/interactions/application-commands#application-command-object-entry-point-command-handler-types).
135    ///
136    /// discord.js counterpart: `EntryPointCommandHandlerType`.
137    #[doc(alias = "EntryPointCommandHandlerType")]
138    pub enum EntryPointHandlerType: u8 {
139        /// The app handles the interaction with its interaction token.
140        AppHandler = 1,
141        /// Discord launches the Activity and sends a follow-up message itself.
142        DiscordLaunchActivity = 2,
143    }
144}
145
146/// An [option (parameter) of a slash command](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-structure),
147/// one variant per option type (D-069).
148///
149/// discord.js counterpart: `ApplicationCommandOption` (the `ApplicationCommand*Option` types).
150#[derive(Clone, Debug, PartialEq)]
151#[non_exhaustive]
152#[doc(alias = "ApplicationCommandOption")]
153pub enum CommandOption {
154    /// A subcommand, with its own options.
155    SubCommand(SubCommandOption),
156    /// A group of subcommands (its options are subcommands).
157    SubCommandGroup(SubCommandOption),
158    /// A string.
159    String(StringOption),
160    /// An integer between -2^53+1 and 2^53-1.
161    Integer(IntegerOption),
162    /// A boolean.
163    Boolean(BasicOption),
164    /// A user.
165    User(BasicOption),
166    /// A channel (including categories).
167    Channel(ChannelOption),
168    /// A role.
169    Role(BasicOption),
170    /// A user or a role.
171    Mentionable(BasicOption),
172    /// A double between -2^53 and 2^53.
173    Number(NumberOption),
174    /// An uploaded file.
175    Attachment(AttachmentOption),
176    /// An option type this version of the library does not know about.
177    Unknown(UnknownOption),
178}
179
180/// The fields every [`CommandOption`] has, as returned by [`CommandOption::common`].
181///
182/// discord.js counterpart: none (a borrowed view of the fields every `APIApplicationCommandOption` has).
183#[derive(Clone, Copy, Debug)]
184#[non_exhaustive]
185pub struct OptionInfo<'a> {
186    /// The option's name.
187    pub name: &'a str,
188    /// Translations of the name.
189    pub name_localizations: &'a BTreeMap<Locale, CompactString>,
190    /// The option's description.
191    pub description: &'a str,
192    /// Translations of the description.
193    pub description_localizations: &'a BTreeMap<Locale, CompactString>,
194    /// The name in the requester's locale, if Discord sent it.
195    pub name_localized: Option<&'a str>,
196    /// The description in the requester's locale, if Discord sent it.
197    pub description_localized: Option<&'a str>,
198}
199
200macro_rules! common_fields {
201    ($self:ident) => {
202        match $self {
203            Self::SubCommand(option) | Self::SubCommandGroup(option) => OptionInfo {
204                name: &option.name,
205                name_localizations: &option.name_localizations,
206                description: &option.description,
207                description_localizations: &option.description_localizations,
208                name_localized: option.name_localized.as_deref(),
209                description_localized: option.description_localized.as_deref(),
210            },
211            Self::String(option) => OptionInfo {
212                name: &option.name,
213                name_localizations: &option.name_localizations,
214                description: &option.description,
215                description_localizations: &option.description_localizations,
216                name_localized: option.name_localized.as_deref(),
217                description_localized: option.description_localized.as_deref(),
218            },
219            Self::Integer(option) => OptionInfo {
220                name: &option.name,
221                name_localizations: &option.name_localizations,
222                description: &option.description,
223                description_localizations: &option.description_localizations,
224                name_localized: option.name_localized.as_deref(),
225                description_localized: option.description_localized.as_deref(),
226            },
227            Self::Boolean(option)
228            | Self::User(option)
229            | Self::Role(option)
230            | Self::Mentionable(option) => OptionInfo {
231                name: &option.name,
232                name_localizations: &option.name_localizations,
233                description: &option.description,
234                description_localizations: &option.description_localizations,
235                name_localized: option.name_localized.as_deref(),
236                description_localized: option.description_localized.as_deref(),
237            },
238            Self::Channel(option) => OptionInfo {
239                name: &option.name,
240                name_localizations: &option.name_localizations,
241                description: &option.description,
242                description_localizations: &option.description_localizations,
243                name_localized: option.name_localized.as_deref(),
244                description_localized: option.description_localized.as_deref(),
245            },
246            Self::Number(option) => OptionInfo {
247                name: &option.name,
248                name_localizations: &option.name_localizations,
249                description: &option.description,
250                description_localizations: &option.description_localizations,
251                name_localized: option.name_localized.as_deref(),
252                description_localized: option.description_localized.as_deref(),
253            },
254            Self::Attachment(option) => OptionInfo {
255                name: &option.name,
256                name_localizations: &option.name_localizations,
257                description: &option.description,
258                description_localizations: &option.description_localizations,
259                name_localized: option.name_localized.as_deref(),
260                description_localized: option.description_localized.as_deref(),
261            },
262            Self::Unknown(option) => OptionInfo {
263                name: &option.name,
264                name_localizations: &option.name_localizations,
265                description: &option.description,
266                description_localizations: &option.description_localizations,
267                name_localized: option.name_localized.as_deref(),
268                description_localized: option.description_localized.as_deref(),
269            },
270        }
271    };
272}
273
274impl CommandOption {
275    /// Returns the option's type.
276    ///
277    /// discord.js counterpart: the `type` of `ApplicationCommandOption`.
278    #[must_use]
279    pub const fn kind(&self) -> CommandOptionType {
280        match self {
281            Self::SubCommand(_) => CommandOptionType::SubCommand,
282            Self::SubCommandGroup(_) => CommandOptionType::SubCommandGroup,
283            Self::String(_) => CommandOptionType::String,
284            Self::Integer(_) => CommandOptionType::Integer,
285            Self::Boolean(_) => CommandOptionType::Boolean,
286            Self::User(_) => CommandOptionType::User,
287            Self::Channel(_) => CommandOptionType::Channel,
288            Self::Role(_) => CommandOptionType::Role,
289            Self::Mentionable(_) => CommandOptionType::Mentionable,
290            Self::Number(_) => CommandOptionType::Number,
291            Self::Attachment(_) => CommandOptionType::Attachment,
292            Self::Unknown(option) => option.kind,
293        }
294    }
295
296    /// Returns the fields every option has (name, description and their translations).
297    ///
298    /// discord.js counterpart: none (the fields every `APIApplicationCommandOption` has).
299    #[must_use]
300    pub fn common(&self) -> OptionInfo<'_> {
301        common_fields!(self)
302    }
303
304    /// Returns the option's name.
305    ///
306    /// discord.js counterpart: the `name` of `ApplicationCommandOption`.
307    #[must_use]
308    pub fn name(&self) -> &str {
309        self.common().name
310    }
311
312    /// Returns the nested options of a subcommand or subcommand group (empty otherwise).
313    ///
314    /// discord.js counterpart: `ApplicationCommandSubCommand#options`.
315    #[must_use]
316    pub fn options(&self) -> &[Self] {
317        match self {
318            Self::SubCommand(option) | Self::SubCommandGroup(option) => &option.options,
319            _ => &[],
320        }
321    }
322}
323
324int_enum! {
325    /// The [type of a command option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type).
326    ///
327    /// discord.js counterpart: `ApplicationCommandOptionType`.
328    #[doc(alias = "ApplicationCommandOptionType")]
329    pub enum CommandOptionType: u8 {
330        /// [`CommandOption::SubCommand`].
331        SubCommand = 1,
332        /// [`CommandOption::SubCommandGroup`].
333        SubCommandGroup = 2,
334        /// [`CommandOption::String`].
335        String = 3,
336        /// [`CommandOption::Integer`].
337        Integer = 4,
338        /// [`CommandOption::Boolean`].
339        Boolean = 5,
340        /// [`CommandOption::User`].
341        User = 6,
342        /// [`CommandOption::Channel`].
343        Channel = 7,
344        /// [`CommandOption::Role`].
345        Role = 8,
346        /// [`CommandOption::Mentionable`].
347        Mentionable = 9,
348        /// [`CommandOption::Number`].
349        Number = 10,
350        /// [`CommandOption::Attachment`].
351        Attachment = 11,
352    }
353}
354
355/// A subcommand or a subcommand group.
356///
357/// discord.js counterpart: `APIApplicationCommandSubcommandOption` / `APIApplicationCommandSubcommandGroupOption` (discord-api-types).
358#[derive(Clone, Debug, PartialEq, Serialize)]
359#[non_exhaustive]
360pub struct SubCommandOption {
361    /// The name (1-32 characters).
362    pub name: CompactString,
363    /// Translations of the name.
364    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
365    pub name_localizations: BTreeMap<Locale, CompactString>,
366    /// The description (1-100 characters).
367    pub description: CompactString,
368    /// Translations of the description.
369    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
370    pub description_localizations: BTreeMap<Locale, CompactString>,
371    /// The name in the requester's locale, from endpoints that do not return the full
372    /// translations.
373    #[serde(skip_serializing_if = "Option::is_none")]
374    pub name_localized: Option<CompactString>,
375    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
376    #[serde(skip_serializing_if = "Option::is_none")]
377    pub description_localized: Option<CompactString>,
378    /// The options of a subcommand, or the subcommands of a group.
379    #[serde(skip_serializing_if = "Vec::is_empty")]
380    pub options: Vec<CommandOption>,
381}
382
383impl SubCommandOption {
384    /// Creates a subcommand or a subcommand group, named `name` and described by `description`, without translations.
385    ///
386    /// Nothing is validated; `djs-builders` checks Discord's rules.
387    ///
388    /// discord.js counterpart: `SlashCommandSubcommandBuilder` (`@discordjs/builders`).
389    #[must_use]
390    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
391        Self {
392            name: name.into(),
393            name_localizations: BTreeMap::new(),
394            description: description.into(),
395            description_localizations: BTreeMap::new(),
396            name_localized: None,
397            description_localized: None,
398            options: Vec::new(),
399        }
400    }
401}
402
403/// A string option.
404///
405/// discord.js counterpart: `APIApplicationCommandStringOption` (discord-api-types).
406#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
407#[non_exhaustive]
408pub struct StringOption {
409    /// The name (1-32 characters).
410    pub name: CompactString,
411    /// Translations of the name.
412    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
413    pub name_localizations: BTreeMap<Locale, CompactString>,
414    /// The description (1-100 characters).
415    pub description: CompactString,
416    /// Translations of the description.
417    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
418    pub description_localizations: BTreeMap<Locale, CompactString>,
419    /// The name in the requester's locale, from endpoints that do not return the full
420    /// translations.
421    #[serde(skip_serializing_if = "Option::is_none")]
422    pub name_localized: Option<CompactString>,
423    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
424    #[serde(skip_serializing_if = "Option::is_none")]
425    pub description_localized: Option<CompactString>,
426    /// Whether the option must be filled.
427    #[serde(skip_serializing_if = "core::ops::Not::not")]
428    pub required: bool,
429    /// The values to choose from (max 25; values up to 100 characters).
430    #[serde(skip_serializing_if = "Vec::is_empty")]
431    pub choices: Vec<Choice<CompactString>>,
432    /// The minimum length (0-6000).
433    #[serde(skip_serializing_if = "Option::is_none")]
434    pub min_length: Option<u16>,
435    /// The maximum length (1-6000).
436    #[serde(skip_serializing_if = "Option::is_none")]
437    pub max_length: Option<u16>,
438    /// Whether the app suggests values through autocomplete interactions (not with
439    /// [`choices`](Self::choices)).
440    #[serde(skip_serializing_if = "core::ops::Not::not")]
441    pub autocomplete: bool,
442}
443
444impl StringOption {
445    /// Creates an optional string option without choices or bounds, named `name` and described by `description`, without translations.
446    ///
447    /// Nothing is validated; `djs-builders` checks Discord's rules.
448    ///
449    /// discord.js counterpart: `SlashCommandStringOption` (`@discordjs/builders`).
450    #[must_use]
451    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
452        Self {
453            name: name.into(),
454            name_localizations: BTreeMap::new(),
455            description: description.into(),
456            description_localizations: BTreeMap::new(),
457            name_localized: None,
458            description_localized: None,
459            required: false,
460            choices: Vec::new(),
461            min_length: None,
462            max_length: None,
463            autocomplete: false,
464        }
465    }
466}
467
468/// An integer option.
469///
470/// discord.js counterpart: `APIApplicationCommandIntegerOption` (discord-api-types).
471#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
472#[non_exhaustive]
473pub struct IntegerOption {
474    /// The name (1-32 characters).
475    pub name: CompactString,
476    /// Translations of the name.
477    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
478    pub name_localizations: BTreeMap<Locale, CompactString>,
479    /// The description (1-100 characters).
480    pub description: CompactString,
481    /// Translations of the description.
482    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
483    pub description_localizations: BTreeMap<Locale, CompactString>,
484    /// The name in the requester's locale, from endpoints that do not return the full
485    /// translations.
486    #[serde(skip_serializing_if = "Option::is_none")]
487    pub name_localized: Option<CompactString>,
488    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
489    #[serde(skip_serializing_if = "Option::is_none")]
490    pub description_localized: Option<CompactString>,
491    /// Whether the option must be filled.
492    #[serde(skip_serializing_if = "core::ops::Not::not")]
493    pub required: bool,
494    /// The values to choose from (max 25).
495    #[serde(skip_serializing_if = "Vec::is_empty")]
496    pub choices: Vec<Choice<i64>>,
497    /// The minimum value.
498    #[serde(skip_serializing_if = "Option::is_none")]
499    pub min_value: Option<i64>,
500    /// The maximum value.
501    #[serde(skip_serializing_if = "Option::is_none")]
502    pub max_value: Option<i64>,
503    /// Whether the app suggests values through autocomplete interactions.
504    #[serde(skip_serializing_if = "core::ops::Not::not")]
505    pub autocomplete: bool,
506}
507
508impl IntegerOption {
509    /// Creates an optional integer option without choices or bounds, named `name` and described by `description`, without translations.
510    ///
511    /// Nothing is validated; `djs-builders` checks Discord's rules.
512    ///
513    /// discord.js counterpart: `SlashCommandIntegerOption` (`@discordjs/builders`).
514    #[must_use]
515    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
516        Self {
517            name: name.into(),
518            name_localizations: BTreeMap::new(),
519            description: description.into(),
520            description_localizations: BTreeMap::new(),
521            name_localized: None,
522            description_localized: None,
523            required: false,
524            choices: Vec::new(),
525            min_value: None,
526            max_value: None,
527            autocomplete: false,
528        }
529    }
530}
531
532/// A number (double) option.
533///
534/// discord.js counterpart: `APIApplicationCommandNumberOption` (discord-api-types).
535#[derive(Clone, Debug, PartialEq, Serialize)]
536#[non_exhaustive]
537pub struct NumberOption {
538    /// The name (1-32 characters).
539    pub name: CompactString,
540    /// Translations of the name.
541    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
542    pub name_localizations: BTreeMap<Locale, CompactString>,
543    /// The description (1-100 characters).
544    pub description: CompactString,
545    /// Translations of the description.
546    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
547    pub description_localizations: BTreeMap<Locale, CompactString>,
548    /// The name in the requester's locale, from endpoints that do not return the full
549    /// translations.
550    #[serde(skip_serializing_if = "Option::is_none")]
551    pub name_localized: Option<CompactString>,
552    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
553    #[serde(skip_serializing_if = "Option::is_none")]
554    pub description_localized: Option<CompactString>,
555    /// Whether the option must be filled.
556    #[serde(skip_serializing_if = "core::ops::Not::not")]
557    pub required: bool,
558    /// The values to choose from (max 25).
559    #[serde(skip_serializing_if = "Vec::is_empty")]
560    pub choices: Vec<Choice<f64>>,
561    /// The minimum value.
562    #[serde(skip_serializing_if = "Option::is_none")]
563    pub min_value: Option<f64>,
564    /// The maximum value.
565    #[serde(skip_serializing_if = "Option::is_none")]
566    pub max_value: Option<f64>,
567    /// Whether the app suggests values through autocomplete interactions.
568    #[serde(skip_serializing_if = "core::ops::Not::not")]
569    pub autocomplete: bool,
570}
571
572impl NumberOption {
573    /// Creates an optional number option without choices or bounds, named `name` and described by `description`, without translations.
574    ///
575    /// Nothing is validated; `djs-builders` checks Discord's rules.
576    ///
577    /// discord.js counterpart: `SlashCommandNumberOption` (`@discordjs/builders`).
578    #[must_use]
579    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
580        Self {
581            name: name.into(),
582            name_localizations: BTreeMap::new(),
583            description: description.into(),
584            description_localizations: BTreeMap::new(),
585            name_localized: None,
586            description_localized: None,
587            required: false,
588            choices: Vec::new(),
589            min_value: None,
590            max_value: None,
591            autocomplete: false,
592        }
593    }
594}
595
596/// A boolean, user, role or mentionable option (they share this structure).
597///
598/// discord.js counterpart: `APIApplicationCommandBasicOption` (discord-api-types).
599#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
600#[non_exhaustive]
601pub struct BasicOption {
602    /// The name (1-32 characters).
603    pub name: CompactString,
604    /// Translations of the name.
605    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
606    pub name_localizations: BTreeMap<Locale, CompactString>,
607    /// The description (1-100 characters).
608    pub description: CompactString,
609    /// Translations of the description.
610    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
611    pub description_localizations: BTreeMap<Locale, CompactString>,
612    /// The name in the requester's locale, from endpoints that do not return the full
613    /// translations.
614    #[serde(skip_serializing_if = "Option::is_none")]
615    pub name_localized: Option<CompactString>,
616    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
617    #[serde(skip_serializing_if = "Option::is_none")]
618    pub description_localized: Option<CompactString>,
619    /// Whether the option must be filled.
620    #[serde(skip_serializing_if = "core::ops::Not::not")]
621    pub required: bool,
622}
623
624impl BasicOption {
625    /// Creates an optional boolean, user, role or mentionable option, named `name` and described by `description`, without translations.
626    ///
627    /// Nothing is validated; `djs-builders` checks Discord's rules.
628    ///
629    /// discord.js counterpart: `SlashCommandBooleanOption` and its siblings (`@discordjs/builders`).
630    #[must_use]
631    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
632        Self {
633            name: name.into(),
634            name_localizations: BTreeMap::new(),
635            description: description.into(),
636            description_localizations: BTreeMap::new(),
637            name_localized: None,
638            description_localized: None,
639            required: false,
640        }
641    }
642}
643
644/// A channel option.
645///
646/// discord.js counterpart: `APIApplicationCommandChannelOption` (discord-api-types).
647#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
648#[non_exhaustive]
649pub struct ChannelOption {
650    /// The name (1-32 characters).
651    pub name: CompactString,
652    /// Translations of the name.
653    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
654    pub name_localizations: BTreeMap<Locale, CompactString>,
655    /// The description (1-100 characters).
656    pub description: CompactString,
657    /// Translations of the description.
658    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
659    pub description_localizations: BTreeMap<Locale, CompactString>,
660    /// The name in the requester's locale, from endpoints that do not return the full
661    /// translations.
662    #[serde(skip_serializing_if = "Option::is_none")]
663    pub name_localized: Option<CompactString>,
664    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
665    #[serde(skip_serializing_if = "Option::is_none")]
666    pub description_localized: Option<CompactString>,
667    /// Whether the option must be filled.
668    #[serde(skip_serializing_if = "core::ops::Not::not")]
669    pub required: bool,
670    /// The channel types offered (all when empty).
671    #[serde(skip_serializing_if = "Vec::is_empty")]
672    pub channel_types: Vec<ChannelType>,
673}
674
675impl ChannelOption {
676    /// Creates an optional channel option offering every channel type, named `name` and described by `description`, without translations.
677    ///
678    /// Nothing is validated; `djs-builders` checks Discord's rules.
679    ///
680    /// discord.js counterpart: `SlashCommandChannelOption` (`@discordjs/builders`).
681    #[must_use]
682    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
683        Self {
684            name: name.into(),
685            name_localizations: BTreeMap::new(),
686            description: description.into(),
687            description_localizations: BTreeMap::new(),
688            name_localized: None,
689            description_localized: None,
690            required: false,
691            channel_types: Vec::new(),
692        }
693    }
694}
695
696/// An attachment option.
697///
698/// discord.js counterpart: `APIApplicationCommandAttachmentOption` (discord-api-types).
699#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
700#[non_exhaustive]
701pub struct AttachmentOption {
702    /// The name (1-32 characters).
703    pub name: CompactString,
704    /// Translations of the name.
705    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
706    pub name_localizations: BTreeMap<Locale, CompactString>,
707    /// The description (1-100 characters).
708    pub description: CompactString,
709    /// Translations of the description.
710    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
711    pub description_localizations: BTreeMap<Locale, CompactString>,
712    /// The name in the requester's locale, from endpoints that do not return the full
713    /// translations.
714    #[serde(skip_serializing_if = "Option::is_none")]
715    pub name_localized: Option<CompactString>,
716    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
717    #[serde(skip_serializing_if = "Option::is_none")]
718    pub description_localized: Option<CompactString>,
719    /// Whether the option must be filled.
720    #[serde(skip_serializing_if = "core::ops::Not::not")]
721    pub required: bool,
722    /// The [file types to accept](https://docs.discord.com/developers/reference#file-type-filtering)
723    /// (extensions only; all when empty).
724    #[serde(skip_serializing_if = "Vec::is_empty")]
725    pub file_types: Vec<CompactString>,
726}
727
728impl AttachmentOption {
729    /// Creates an optional attachment option accepting every file type, named `name` and described by `description`, without translations.
730    ///
731    /// Nothing is validated; `djs-builders` checks Discord's rules.
732    ///
733    /// discord.js counterpart: `SlashCommandAttachmentOption` (`@discordjs/builders`).
734    #[must_use]
735    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
736        Self {
737            name: name.into(),
738            name_localizations: BTreeMap::new(),
739            description: description.into(),
740            description_localizations: BTreeMap::new(),
741            name_localized: None,
742            description_localized: None,
743            required: false,
744            file_types: Vec::new(),
745        }
746    }
747}
748
749/// An option of a type this version of the library does not know about; the fields every
750/// option has are kept.
751///
752/// discord.js counterpart: none (an option type unknown to this version, kept as received).
753#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
754#[non_exhaustive]
755pub struct UnknownOption {
756    /// The raw option type.
757    #[serde(skip)]
758    pub kind: CommandOptionType,
759    /// The name.
760    pub name: CompactString,
761    /// Translations of the name.
762    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
763    pub name_localizations: BTreeMap<Locale, CompactString>,
764    /// The description.
765    pub description: CompactString,
766    /// Translations of the description.
767    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
768    pub description_localizations: BTreeMap<Locale, CompactString>,
769    /// The name in the requester's locale, from endpoints that do not return the full
770    /// translations.
771    #[serde(skip_serializing_if = "Option::is_none")]
772    pub name_localized: Option<CompactString>,
773    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
774    #[serde(skip_serializing_if = "Option::is_none")]
775    pub description_localized: Option<CompactString>,
776    /// Whether the option must be filled.
777    #[serde(skip_serializing_if = "core::ops::Not::not")]
778    pub required: bool,
779}
780
781/// A [choice of an option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-choice-structure)
782/// (also used for autocomplete suggestions). `T` is the option's value type.
783///
784/// discord.js counterpart: `APIApplicationCommandOptionChoice`.
785#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
786#[non_exhaustive]
787#[doc(alias = "ApplicationCommandOptionChoice")]
788pub struct Choice<T> {
789    /// The name shown to the user (1-100 characters).
790    pub name: CompactString,
791    /// Translations of the name, keyed by locale (D-058).
792    #[serde(
793        default,
794        skip_serializing_if = "BTreeMap::is_empty",
795        deserialize_with = "crate::serde_util::null_as_default"
796    )]
797    pub name_localizations: BTreeMap<Locale, CompactString>,
798    /// The value sent to the app.
799    pub value: T,
800}
801
802impl<T> Choice<T> {
803    /// Creates a choice without translations.
804    ///
805    /// discord.js counterpart: `ApplicationCommandOptionChoiceData`.
806    #[must_use]
807    pub fn new(name: impl Into<CompactString>, value: T) -> Self {
808        Self {
809            name: name.into(),
810            name_localizations: BTreeMap::new(),
811            value,
812        }
813    }
814}
815
816/// A JSON number or string as found in choices and option bounds, before the option type tells
817/// what it must be.
818#[derive(Clone, Debug, PartialEq)]
819pub(crate) enum RawValue {
820    String(CompactString),
821    Integer(i64),
822    Float(f64),
823}
824
825impl<'de> Deserialize<'de> for RawValue {
826    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
827        struct RawValueVisitor;
828
829        impl Visitor<'_> for RawValueVisitor {
830            type Value = RawValue;
831
832            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
833                f.write_str("a string or a number")
834            }
835
836            fn visit_i64<E: DeError>(self, value: i64) -> Result<RawValue, E> {
837                Ok(RawValue::Integer(value))
838            }
839
840            fn visit_u64<E: DeError>(self, value: u64) -> Result<RawValue, E> {
841                i64::try_from(value)
842                    .map(RawValue::Integer)
843                    .map_err(|_| E::invalid_value(Unexpected::Unsigned(value), &self))
844            }
845
846            fn visit_f64<E: DeError>(self, value: f64) -> Result<RawValue, E> {
847                Ok(RawValue::Float(value))
848            }
849
850            fn visit_str<E: DeError>(self, value: &str) -> Result<RawValue, E> {
851                Ok(RawValue::String(value.into()))
852            }
853        }
854
855        deserializer.deserialize_any(RawValueVisitor)
856    }
857}
858
859impl RawValue {
860    pub(crate) fn into_string<E: DeError>(self) -> Result<CompactString, E> {
861        match self {
862            Self::String(value) => Ok(value),
863            Self::Integer(value) => Err(E::invalid_type(Unexpected::Signed(value), &"a string")),
864            Self::Float(value) => Err(E::invalid_type(Unexpected::Float(value), &"a string")),
865        }
866    }
867
868    pub(crate) fn into_integer<E: DeError>(self) -> Result<i64, E> {
869        match self {
870            Self::Integer(value) => Ok(value),
871            Self::String(value) => Err(E::invalid_type(Unexpected::Str(&value), &"an integer")),
872            Self::Float(value) => Err(E::invalid_type(Unexpected::Float(value), &"an integer")),
873        }
874    }
875
876    #[expect(
877        clippy::cast_precision_loss,
878        reason = "Discord limits command numbers to ±2^53, which f64 represents exactly"
879    )]
880    pub(crate) fn into_number<E: DeError>(self) -> Result<f64, E> {
881        match self {
882            Self::Integer(value) => Ok(value as f64),
883            Self::Float(value) => Ok(value),
884            Self::String(value) => Err(E::invalid_type(Unexpected::Str(&value), &"a number")),
885        }
886    }
887}
888
889pub(crate) fn convert_choices<T, E: DeError>(
890    choices: Vec<Choice<RawValue>>,
891    convert: impl Fn(RawValue) -> Result<T, E>,
892) -> Result<Vec<Choice<T>>, E> {
893    choices
894        .into_iter()
895        .map(|choice| {
896            Ok(Choice {
897                name: choice.name,
898                name_localizations: choice.name_localizations,
899                value: convert(choice.value)?,
900            })
901        })
902        .collect()
903}
904
905/// Every field of every option type, decoded in one pass and converted by `type` (D-069).
906#[derive(Deserialize)]
907struct RawOption {
908    #[serde(rename = "type")]
909    kind: CommandOptionType,
910    name: CompactString,
911    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
912    name_localizations: BTreeMap<Locale, CompactString>,
913    #[serde(default)]
914    description: CompactString,
915    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
916    description_localizations: BTreeMap<Locale, CompactString>,
917    #[serde(default)]
918    name_localized: Option<CompactString>,
919    #[serde(default)]
920    description_localized: Option<CompactString>,
921    #[serde(default)]
922    required: bool,
923    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
924    choices: Vec<Choice<RawValue>>,
925    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
926    options: Vec<CommandOption>,
927    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
928    channel_types: Vec<ChannelType>,
929    #[serde(default)]
930    min_value: Option<RawValue>,
931    #[serde(default)]
932    max_value: Option<RawValue>,
933    #[serde(default)]
934    min_length: Option<u16>,
935    #[serde(default)]
936    max_length: Option<u16>,
937    #[serde(default)]
938    autocomplete: bool,
939    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
940    file_types: Vec<CompactString>,
941}
942
943impl RawOption {
944    fn into_option<E: DeError>(self) -> Result<CommandOption, E> {
945        let basic = |raw: Self| BasicOption {
946            name: raw.name,
947            name_localizations: raw.name_localizations,
948            description: raw.description,
949            description_localizations: raw.description_localizations,
950            name_localized: raw.name_localized,
951            description_localized: raw.description_localized,
952            required: raw.required,
953        };
954        Ok(match self.kind {
955            kind @ (CommandOptionType::SubCommand | CommandOptionType::SubCommandGroup) => {
956                let option = SubCommandOption {
957                    name: self.name,
958                    name_localizations: self.name_localizations,
959                    description: self.description,
960                    description_localizations: self.description_localizations,
961                    name_localized: self.name_localized,
962                    description_localized: self.description_localized,
963                    options: self.options,
964                };
965                if kind == CommandOptionType::SubCommand {
966                    CommandOption::SubCommand(option)
967                } else {
968                    CommandOption::SubCommandGroup(option)
969                }
970            }
971            CommandOptionType::String => CommandOption::String(StringOption {
972                choices: convert_choices(self.choices, RawValue::into_string)?,
973                name: self.name,
974                name_localizations: self.name_localizations,
975                description: self.description,
976                description_localizations: self.description_localizations,
977                name_localized: self.name_localized,
978                description_localized: self.description_localized,
979                required: self.required,
980                min_length: self.min_length,
981                max_length: self.max_length,
982                autocomplete: self.autocomplete,
983            }),
984            CommandOptionType::Integer => CommandOption::Integer(IntegerOption {
985                choices: convert_choices(self.choices, RawValue::into_integer)?,
986                min_value: self.min_value.map(RawValue::into_integer).transpose()?,
987                max_value: self.max_value.map(RawValue::into_integer).transpose()?,
988                name: self.name,
989                name_localizations: self.name_localizations,
990                description: self.description,
991                description_localizations: self.description_localizations,
992                name_localized: self.name_localized,
993                description_localized: self.description_localized,
994                required: self.required,
995                autocomplete: self.autocomplete,
996            }),
997            CommandOptionType::Number => CommandOption::Number(NumberOption {
998                choices: convert_choices(self.choices, RawValue::into_number)?,
999                min_value: self.min_value.map(RawValue::into_number).transpose()?,
1000                max_value: self.max_value.map(RawValue::into_number).transpose()?,
1001                name: self.name,
1002                name_localizations: self.name_localizations,
1003                description: self.description,
1004                description_localizations: self.description_localizations,
1005                name_localized: self.name_localized,
1006                description_localized: self.description_localized,
1007                required: self.required,
1008                autocomplete: self.autocomplete,
1009            }),
1010            CommandOptionType::Boolean => CommandOption::Boolean(basic(self)),
1011            CommandOptionType::User => CommandOption::User(basic(self)),
1012            CommandOptionType::Role => CommandOption::Role(basic(self)),
1013            CommandOptionType::Mentionable => CommandOption::Mentionable(basic(self)),
1014            CommandOptionType::Channel => CommandOption::Channel(ChannelOption {
1015                name: self.name,
1016                name_localizations: self.name_localizations,
1017                description: self.description,
1018                description_localizations: self.description_localizations,
1019                name_localized: self.name_localized,
1020                description_localized: self.description_localized,
1021                required: self.required,
1022                channel_types: self.channel_types,
1023            }),
1024            CommandOptionType::Attachment => CommandOption::Attachment(AttachmentOption {
1025                name: self.name,
1026                name_localizations: self.name_localizations,
1027                description: self.description,
1028                description_localizations: self.description_localizations,
1029                name_localized: self.name_localized,
1030                description_localized: self.description_localized,
1031                required: self.required,
1032                file_types: self.file_types,
1033            }),
1034            kind @ CommandOptionType::Unknown(_) => CommandOption::Unknown(UnknownOption {
1035                kind,
1036                name: self.name,
1037                name_localizations: self.name_localizations,
1038                description: self.description,
1039                description_localizations: self.description_localizations,
1040                name_localized: self.name_localized,
1041                description_localized: self.description_localized,
1042                required: self.required,
1043            }),
1044        })
1045    }
1046}
1047
1048impl<'de> Deserialize<'de> for CommandOption {
1049    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1050        RawOption::deserialize(deserializer)?.into_option::<D::Error>()
1051    }
1052}
1053
1054/// Serializes a variant's struct together with its `type`.
1055#[derive(Serialize)]
1056struct Tagged<'a, T> {
1057    #[serde(rename = "type")]
1058    kind: CommandOptionType,
1059    #[serde(flatten)]
1060    option: &'a T,
1061}
1062
1063impl Serialize for CommandOption {
1064    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1065        let kind = self.kind();
1066        match self {
1067            Self::SubCommand(option) | Self::SubCommandGroup(option) => {
1068                Tagged { kind, option }.serialize(serializer)
1069            }
1070            Self::String(option) => Tagged { kind, option }.serialize(serializer),
1071            Self::Integer(option) => Tagged { kind, option }.serialize(serializer),
1072            Self::Boolean(option)
1073            | Self::User(option)
1074            | Self::Role(option)
1075            | Self::Mentionable(option) => Tagged { kind, option }.serialize(serializer),
1076            Self::Channel(option) => Tagged { kind, option }.serialize(serializer),
1077            Self::Number(option) => Tagged { kind, option }.serialize(serializer),
1078            Self::Attachment(option) => Tagged { kind, option }.serialize(serializer),
1079            Self::Unknown(option) => Tagged { kind, option }.serialize(serializer),
1080        }
1081    }
1082}
1083
1084/// The [permissions of an app's command(s) in a guild](https://docs.discord.com/developers/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure).
1085///
1086/// discord.js counterpart: `ApplicationCommandPermissions` (per guild).
1087#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1088#[non_exhaustive]
1089#[doc(alias = "GuildApplicationCommandPermissions")]
1090pub struct GuildCommandPermissions {
1091    /// The command, or the application ID for permissions that apply to all its commands
1092    /// without their own.
1093    pub id: GenericId,
1094    /// The application the command belongs to.
1095    pub application_id: ApplicationId,
1096    /// The guild.
1097    pub guild_id: GuildId,
1098    /// The permissions (max 100).
1099    pub permissions: Vec<CommandPermission>,
1100}
1101
1102/// One [command permission](https://docs.discord.com/developers/interactions/application-commands#application-command-permissions-object-application-command-permissions-structure):
1103/// allows or denies a command for a role, user or channel.
1104///
1105/// discord.js counterpart: `ApplicationCommandPermissions`.
1106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1107#[non_exhaustive]
1108#[doc(alias = "ApplicationCommandPermissions")]
1109pub struct CommandPermission {
1110    /// The role, user or channel; see [`everyone`](Self::everyone) and
1111    /// [`all_channels`](Self::all_channels) for the special values.
1112    pub id: GenericId,
1113    /// What [`id`](Self::id) refers to.
1114    #[serde(rename = "type")]
1115    pub kind: CommandPermissionType,
1116    /// `true` to allow, `false` to deny.
1117    pub permission: bool,
1118}
1119
1120impl CommandPermission {
1121    /// Creates a permission.
1122    ///
1123    /// discord.js counterpart: `ApplicationCommandPermissions`.
1124    #[must_use]
1125    pub const fn new(id: GenericId, kind: CommandPermissionType, permission: bool) -> Self {
1126        Self {
1127            id,
1128            kind,
1129            permission,
1130        }
1131    }
1132
1133    /// The ID that stands for `@everyone` (all members) in `guild_id`: the guild ID itself.
1134    ///
1135    /// discord.js counterpart: `Guild#roles.everyone`'s ID (the guild's ID).
1136    #[must_use]
1137    pub const fn everyone(guild_id: GuildId) -> GenericId {
1138        guild_id.cast()
1139    }
1140
1141    /// The ID that stands for all channels in `guild_id`: the guild ID minus one, or `None`
1142    /// for the (impossible) guild ID `1`.
1143    ///
1144    /// discord.js counterpart: none (discord.js leaves the guild ID minus one to the bot).
1145    #[must_use]
1146    pub const fn all_channels(guild_id: GuildId) -> Option<GenericId> {
1147        GenericId::new_checked(guild_id.get() - 1)
1148    }
1149}
1150
1151int_enum! {
1152    /// [What a command permission applies to](https://docs.discord.com/developers/interactions/application-commands#application-command-permissions-object-application-command-permission-type).
1153    ///
1154    /// discord.js counterpart: `ApplicationCommandPermissionType`.
1155    #[doc(alias = "ApplicationCommandPermissionType")]
1156    pub enum CommandPermissionType: u8 {
1157        /// A role (or `@everyone`).
1158        Role = 1,
1159        /// A user.
1160        User = 2,
1161        /// A channel (or all channels).
1162        Channel = 3,
1163    }
1164}