Skip to main content

djs_model/rest/
application_command.rs

1//! Bodies and queries of the [application command endpoints](https://docs.discord.com/developers/interactions/application-commands#endpoints).
2
3use std::collections::BTreeMap;
4
5use compact_str::CompactString;
6use serde::Serialize;
7
8use crate::{
9    application::IntegrationType,
10    application_command::{CommandOption, CommandPermission, CommandType, EntryPointHandlerType},
11    interaction::InteractionContextType,
12    permissions::Permissions,
13    util::{Locale, Patch},
14};
15
16/// The body of [Create Global Application Command](https://docs.discord.com/developers/interactions/application-commands#create-global-application-command)
17/// and [Create Guild Application Command](https://docs.discord.com/developers/interactions/application-commands#create-guild-application-command),
18/// and one entry of the bulk overwrite endpoints.
19///
20/// Creating a command with the name of an existing one (of the same type) updates it. The
21/// deprecated `dm_permission` and `default_permission` fields are left out: use
22/// [`contexts`](Self::contexts) and [`default_member_permissions`](Self::default_member_permissions).
23///
24/// discord.js counterpart: `ApplicationCommandData` / `RESTPostAPIApplicationCommandsJSONBody`.
25///
26/// # Examples
27///
28/// ```
29/// use djs_model::rest::CreateApplicationCommand;
30///
31/// let ping = CreateApplicationCommand::chat_input("ping", "Checks that the bot is alive");
32/// assert_eq!(
33///     serde_json::to_string(&ping).unwrap(),
34///     r#"{"name":"ping","description":"Checks that the bot is alive","type":1}"#
35/// );
36/// let report = CreateApplicationCommand::message("Report message");
37/// assert_eq!(serde_json::to_string(&report).unwrap(), r#"{"name":"Report message","type":3}"#);
38/// ```
39#[derive(Clone, Debug, PartialEq, Serialize)]
40#[non_exhaustive]
41pub struct CreateApplicationCommand {
42    /// The [name](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-naming)
43    /// (1-32 characters; lowercase without spaces for slash commands).
44    pub name: CompactString,
45    /// The name in other languages.
46    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
47    pub name_localizations: BTreeMap<Locale, CompactString>,
48    /// The description (1-100 characters) of slash and primary entry point commands; must be
49    /// left out for user and message commands.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub description: Option<CompactString>,
52    /// The description in other languages.
53    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
54    pub description_localizations: BTreeMap<Locale, CompactString>,
55    /// The options of a slash command (max 25).
56    #[serde(skip_serializing_if = "Vec::is_empty")]
57    pub options: Vec<CommandOption>,
58    /// The permissions a member needs by default; [`Permissions::empty`] allows only
59    /// administrators, `None` everyone. Guild administrators can change it.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub default_member_permissions: Option<Permissions>,
62    /// The installation contexts the command is available in (Discord's default: those the
63    /// application supports).
64    #[serde(skip_serializing_if = "Vec::is_empty")]
65    pub integration_types: Vec<IntegrationType>,
66    /// The interaction contexts the command can be used in (Discord's default: all).
67    #[serde(skip_serializing_if = "Vec::is_empty")]
68    pub contexts: Vec<InteractionContextType>,
69    /// The command's type (Discord's default: a slash command).
70    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
71    pub kind: Option<CommandType>,
72    /// Whether the command is age-restricted.
73    #[serde(skip_serializing_if = "core::ops::Not::not")]
74    pub nsfw: bool,
75    /// Who handles a primary entry point command.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub handler: Option<EntryPointHandlerType>,
78}
79
80impl CreateApplicationCommand {
81    /// A command of type `kind` with only a name.
82    ///
83    /// discord.js counterpart: `ApplicationCommandData`.
84    #[must_use]
85    pub fn new(name: impl Into<CompactString>, kind: CommandType) -> Self {
86        Self {
87            name: name.into(),
88            name_localizations: BTreeMap::new(),
89            description: None,
90            description_localizations: BTreeMap::new(),
91            options: Vec::new(),
92            default_member_permissions: None,
93            integration_types: Vec::new(),
94            contexts: Vec::new(),
95            kind: Some(kind),
96            nsfw: false,
97            handler: None,
98        }
99    }
100
101    /// A slash command.
102    ///
103    /// discord.js counterpart: `ChatInputApplicationCommandData`.
104    #[must_use]
105    pub fn chat_input(
106        name: impl Into<CompactString>,
107        description: impl Into<CompactString>,
108    ) -> Self {
109        Self {
110            description: Some(description.into()),
111            ..Self::new(name, CommandType::ChatInput)
112        }
113    }
114
115    /// A user command (shown in the context menu of users).
116    ///
117    /// discord.js counterpart: `UserApplicationCommandData`.
118    #[must_use]
119    pub fn user(name: impl Into<CompactString>) -> Self {
120        Self::new(name, CommandType::User)
121    }
122
123    /// A message command (shown in the context menu of messages).
124    ///
125    /// discord.js counterpart: `MessageApplicationCommandData`.
126    #[must_use]
127    pub fn message(name: impl Into<CompactString>) -> Self {
128        Self::new(name, CommandType::Message)
129    }
130}
131
132/// The body of [Edit Global Application Command](https://docs.discord.com/developers/interactions/application-commands#edit-global-application-command)
133/// and [Edit Guild Application Command](https://docs.discord.com/developers/interactions/application-commands#edit-guild-application-command).
134///
135/// Every field is optional; a field that is sent replaces the old value entirely (e.g. all
136/// options). Nullable fields are [`Patch`]es.
137///
138/// discord.js counterpart: `ApplicationCommandManager#edit` data.
139#[derive(Clone, Debug, Default, PartialEq, Serialize)]
140#[non_exhaustive]
141pub struct EditApplicationCommand {
142    /// The name.
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub name: Option<CompactString>,
145    /// The name in other languages.
146    #[serde(skip_serializing_if = "Patch::is_keep")]
147    pub name_localizations: Patch<BTreeMap<Locale, CompactString>>,
148    /// The description.
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub description: Option<CompactString>,
151    /// The description in other languages.
152    #[serde(skip_serializing_if = "Patch::is_keep")]
153    pub description_localizations: Patch<BTreeMap<Locale, CompactString>>,
154    /// The options (all of them).
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub options: Option<Vec<CommandOption>>,
157    /// The permissions a member needs by default; [`Patch::Clear`] allows everyone.
158    #[serde(skip_serializing_if = "Patch::is_keep")]
159    pub default_member_permissions: Patch<Permissions>,
160    /// The installation contexts.
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub integration_types: Option<Vec<IntegrationType>>,
163    /// The interaction contexts.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub contexts: Option<Vec<InteractionContextType>>,
166    /// Whether the command is age-restricted.
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub nsfw: Option<bool>,
169    /// Who handles a primary entry point command.
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub handler: Option<EntryPointHandlerType>,
172}
173
174/// The query of [Get Global Application Commands](https://docs.discord.com/developers/interactions/application-commands#get-global-application-commands)
175/// and [Get Guild Application Commands](https://docs.discord.com/developers/interactions/application-commands#get-guild-application-commands).
176///
177/// discord.js counterpart: `RESTGetAPIApplicationCommandsQuery` (discord-api-types).
178#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
179#[non_exhaustive]
180pub struct GetApplicationCommands {
181    /// Whether to return the full localization dictionaries instead of the `name_localized`
182    /// and `description_localized` fields (Discord's default: no).
183    pub with_localizations: Option<bool>,
184}
185
186/// The body of [Edit Application Command Permissions](https://docs.discord.com/developers/interactions/application-commands#edit-application-command-permissions).
187///
188/// discord.js counterpart: `RESTPutAPIApplicationCommandPermissionsJSONBody` (discord-api-types).
189#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
190#[non_exhaustive]
191pub struct EditApplicationCommandPermissions {
192    /// The permission overwrites of the command in the guild (max 100); they replace the
193    /// existing ones.
194    pub permissions: Vec<CommandPermission>,
195}
196
197impl EditApplicationCommandPermissions {
198    /// Sets the permission overwrites to `permissions`.
199    ///
200    /// discord.js counterpart: the `permissions` of `ApplicationCommandPermissionsManager#set`.
201    #[must_use]
202    pub const fn new(permissions: Vec<CommandPermission>) -> Self {
203        Self { permissions }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn create_and_edit() {
213        let mut command = CreateApplicationCommand::chat_input("ban", "Bans a member");
214        command.default_member_permissions = Some(Permissions::BAN_MEMBERS);
215        command.contexts = vec![InteractionContextType::Guild];
216        command
217            .name_localizations
218            .insert(Locale::Polish, "zbanuj".into());
219        assert_eq!(
220            serde_json::to_string(&command).unwrap(),
221            concat!(
222                r#"{"name":"ban","name_localizations":{"pl":"zbanuj"},"description":"Bans a member","#,
223                r#""default_member_permissions":"4","contexts":[0],"type":1}"#
224            )
225        );
226
227        let edit = EditApplicationCommand {
228            description: Some("Bans someone".into()),
229            default_member_permissions: Patch::Clear,
230            name_localizations: Patch::Set(BTreeMap::new()),
231            ..EditApplicationCommand::default()
232        };
233        assert_eq!(
234            serde_json::to_string(&edit).unwrap(),
235            r#"{"name_localizations":{},"description":"Bans someone","default_member_permissions":null}"#
236        );
237    }
238}