Skip to main content

djs_rest/endpoints/
application_command.rs

1//! [Application command endpoints](https://docs.discord.com/developers/interactions/application-commands#endpoints):
2//! registering slash, user and message commands, globally or in one guild, and their
3//! per-guild permissions.
4//!
5//! Global commands are available in every guild and DM the application is installed in;
6//! guild commands only in their guild. An application can have 100 global slash commands, 5
7//! user and 5 message commands (and as many again per guild). Creating more than 200
8//! commands a day in one guild is rate limited, so registering on every start is best done
9//! with a single bulk overwrite.
10
11use djs_model::{
12    application_command::{ApplicationCommand, GuildCommandPermissions},
13    id::{ApplicationId, CommandId, GuildId},
14    rest::{
15        CreateApplicationCommand, EditApplicationCommand, EditApplicationCommandPermissions,
16        GetApplicationCommands,
17    },
18};
19
20use crate::client::boxed;
21use crate::{Error, Request, Rest, Route};
22
23impl Rest {
24    /// [Get Global Application Commands](https://docs.discord.com/developers/interactions/application-commands#get-global-application-commands):
25    /// returns the application's global commands.
26    ///
27    /// discord.js counterpart: `ApplicationCommandManager#fetch`.
28    ///
29    /// # Errors
30    ///
31    /// See [`Rest::request`].
32    pub fn get_global_application_commands<'a>(
33        &'a self,
34        application_id: ApplicationId,
35        query: &'a GetApplicationCommands,
36    ) -> impl Future<Output = Result<Vec<ApplicationCommand>, Error>> + Send + 'a {
37        boxed(async move {
38            self.call(
39                Request::new(Route::GetGlobalApplicationCommands { application_id }).query(query),
40            )
41            .await
42        })
43    }
44
45    /// [Create Global Application Command](https://docs.discord.com/developers/interactions/application-commands#create-global-application-command):
46    /// registers a global command, or updates the one with the same name and type. Discord
47    /// answers `201 Created` for a new command and `200 OK` for an update.
48    ///
49    /// discord.js counterpart: `ApplicationCommandManager#create`.
50    ///
51    /// # Examples
52    ///
53    /// ```no_run
54    /// # async fn example(rest: djs_rest::Rest, application_id: djs_model::id::ApplicationId) -> Result<(), djs_rest::Error> {
55    /// use djs_model::rest::CreateApplicationCommand;
56    ///
57    /// let ping = CreateApplicationCommand::chat_input("ping", "Checks that the bot is alive");
58    /// let command = rest
59    ///     .create_global_application_command(application_id, &ping)
60    ///     .await?;
61    /// println!("registered /ping as {}", command.id);
62    /// # Ok(())
63    /// # }
64    /// ```
65    ///
66    /// # Errors
67    ///
68    /// See [`Rest::request`]; `30032` at the maximum number of commands, `50035` for an
69    /// invalid command (see [`ApiError::field_errors`](crate::ApiError::field_errors)).
70    pub fn create_global_application_command<'a>(
71        &'a self,
72        application_id: ApplicationId,
73        body: &'a CreateApplicationCommand,
74    ) -> impl Future<Output = Result<ApplicationCommand, Error>> + Send + 'a {
75        boxed(async move {
76            self.call(
77                Request::new(Route::CreateGlobalApplicationCommand { application_id })
78                    .json(body)?,
79            )
80            .await
81        })
82    }
83
84    /// [Get Global Application Command](https://docs.discord.com/developers/interactions/application-commands#get-global-application-command):
85    /// returns one global command.
86    ///
87    /// discord.js counterpart: `ApplicationCommandManager#fetch(id)`.
88    ///
89    /// # Errors
90    ///
91    /// See [`Rest::request`]; `10063` Unknown Application Command.
92    pub fn get_global_application_command(
93        &self,
94        application_id: ApplicationId,
95        command_id: CommandId,
96    ) -> impl Future<Output = Result<ApplicationCommand, Error>> + Send + '_ {
97        boxed(async move {
98            self.call(Request::new(Route::GetGlobalApplicationCommand {
99                application_id,
100                command_id,
101            }))
102            .await
103        })
104    }
105
106    /// [Edit Global Application Command](https://docs.discord.com/developers/interactions/application-commands#edit-global-application-command):
107    /// changes the fields of a global command that are set in `body`.
108    ///
109    /// discord.js counterpart: `ApplicationCommandManager#edit`.
110    ///
111    /// # Errors
112    ///
113    /// See [`Rest::request`].
114    pub fn edit_global_application_command<'a>(
115        &'a self,
116        application_id: ApplicationId,
117        command_id: CommandId,
118        body: &'a EditApplicationCommand,
119    ) -> impl Future<Output = Result<ApplicationCommand, Error>> + Send + 'a {
120        boxed(async move {
121            self.call(
122                Request::new(Route::EditGlobalApplicationCommand {
123                    application_id,
124                    command_id,
125                })
126                .json(body)?,
127            )
128            .await
129        })
130    }
131
132    /// [Delete Global Application Command](https://docs.discord.com/developers/interactions/application-commands#delete-global-application-command):
133    /// unregisters a global command.
134    ///
135    /// discord.js counterpart: `ApplicationCommandManager#delete`.
136    ///
137    /// # Errors
138    ///
139    /// See [`Rest::request`].
140    pub fn delete_global_application_command(
141        &self,
142        application_id: ApplicationId,
143        command_id: CommandId,
144    ) -> impl Future<Output = Result<(), Error>> + Send + '_ {
145        boxed(async move {
146            self.call(Request::new(Route::DeleteGlobalApplicationCommand {
147                application_id,
148                command_id,
149            }))
150            .await
151        })
152    }
153
154    /// [Bulk Overwrite Global Application Commands](https://docs.discord.com/developers/interactions/application-commands#bulk-overwrite-global-application-commands):
155    /// replaces all global commands with `commands`, and returns them.
156    ///
157    /// Commands not in the list are deleted (an empty list deletes all); listed commands keep
158    /// their IDs when their name and type match an existing command. This is the usual way
159    /// to register commands when a bot starts.
160    ///
161    /// discord.js counterpart: `ApplicationCommandManager#set`.
162    ///
163    /// # Examples
164    ///
165    /// ```no_run
166    /// # async fn example(rest: djs_rest::Rest, application_id: djs_model::id::ApplicationId) -> Result<(), djs_rest::Error> {
167    /// use djs_model::rest::CreateApplicationCommand;
168    ///
169    /// let commands = [
170    ///     CreateApplicationCommand::chat_input("ping", "Checks that the bot is alive"),
171    ///     CreateApplicationCommand::user("Show avatar"),
172    /// ];
173    /// rest.bulk_overwrite_global_application_commands(application_id, &commands)
174    ///     .await?;
175    /// # Ok(())
176    /// # }
177    /// ```
178    ///
179    /// # Errors
180    ///
181    /// See [`Rest::request`].
182    pub fn bulk_overwrite_global_application_commands<'a>(
183        &'a self,
184        application_id: ApplicationId,
185        commands: &'a [CreateApplicationCommand],
186    ) -> impl Future<Output = Result<Vec<ApplicationCommand>, Error>> + Send + 'a {
187        boxed(async move {
188            self.call(
189                Request::new(Route::BulkOverwriteGlobalApplicationCommands { application_id })
190                    .json(commands)?,
191            )
192            .await
193        })
194    }
195
196    /// [Get Guild Application Commands](https://docs.discord.com/developers/interactions/application-commands#get-guild-application-commands):
197    /// returns the application's commands in a guild (not its global commands).
198    ///
199    /// discord.js counterpart: `GuildApplicationCommandManager#fetch`.
200    ///
201    /// # Errors
202    ///
203    /// See [`Rest::request`].
204    pub fn get_guild_application_commands<'a>(
205        &'a self,
206        application_id: ApplicationId,
207        guild_id: GuildId,
208        query: &'a GetApplicationCommands,
209    ) -> impl Future<Output = Result<Vec<ApplicationCommand>, Error>> + Send + 'a {
210        boxed(async move {
211            self.call(
212                Request::new(Route::GetGuildApplicationCommands {
213                    application_id,
214                    guild_id,
215                })
216                .query(query),
217            )
218            .await
219        })
220    }
221
222    /// [Create Guild Application Command](https://docs.discord.com/developers/interactions/application-commands#create-guild-application-command):
223    /// registers a command in one guild, or updates the one with the same name and type.
224    /// Guild commands are available at once, which makes them handy while developing.
225    ///
226    /// discord.js counterpart: `GuildApplicationCommandManager#create`.
227    ///
228    /// # Errors
229    ///
230    /// See [`Rest::request`]; `50001` Missing Access when the application is not in the guild
231    /// with the `applications.commands` scope.
232    pub fn create_guild_application_command<'a>(
233        &'a self,
234        application_id: ApplicationId,
235        guild_id: GuildId,
236        body: &'a CreateApplicationCommand,
237    ) -> impl Future<Output = Result<ApplicationCommand, Error>> + Send + 'a {
238        boxed(async move {
239            self.call(
240                Request::new(Route::CreateGuildApplicationCommand {
241                    application_id,
242                    guild_id,
243                })
244                .json(body)?,
245            )
246            .await
247        })
248    }
249
250    /// [Get Guild Application Command](https://docs.discord.com/developers/interactions/application-commands#get-guild-application-command):
251    /// returns one guild command.
252    ///
253    /// discord.js counterpart: `GuildApplicationCommandManager#fetch(id)`.
254    ///
255    /// # Errors
256    ///
257    /// See [`Rest::request`]; `10063` Unknown Application Command.
258    pub fn get_guild_application_command(
259        &self,
260        application_id: ApplicationId,
261        guild_id: GuildId,
262        command_id: CommandId,
263    ) -> impl Future<Output = Result<ApplicationCommand, Error>> + Send + '_ {
264        boxed(async move {
265            self.call(Request::new(Route::GetGuildApplicationCommand {
266                application_id,
267                guild_id,
268                command_id,
269            }))
270            .await
271        })
272    }
273
274    /// [Edit Guild Application Command](https://docs.discord.com/developers/interactions/application-commands#edit-guild-application-command):
275    /// changes the fields of a guild command that are set in `body`.
276    ///
277    /// discord.js counterpart: `GuildApplicationCommandManager#edit`.
278    ///
279    /// # Errors
280    ///
281    /// See [`Rest::request`].
282    pub fn edit_guild_application_command<'a>(
283        &'a self,
284        application_id: ApplicationId,
285        guild_id: GuildId,
286        command_id: CommandId,
287        body: &'a EditApplicationCommand,
288    ) -> impl Future<Output = Result<ApplicationCommand, Error>> + Send + 'a {
289        boxed(async move {
290            self.call(
291                Request::new(Route::EditGuildApplicationCommand {
292                    application_id,
293                    guild_id,
294                    command_id,
295                })
296                .json(body)?,
297            )
298            .await
299        })
300    }
301
302    /// [Delete Guild Application Command](https://docs.discord.com/developers/interactions/application-commands#delete-guild-application-command):
303    /// unregisters a guild command.
304    ///
305    /// discord.js counterpart: `GuildApplicationCommandManager#delete`.
306    ///
307    /// # Errors
308    ///
309    /// See [`Rest::request`].
310    pub fn delete_guild_application_command(
311        &self,
312        application_id: ApplicationId,
313        guild_id: GuildId,
314        command_id: CommandId,
315    ) -> impl Future<Output = Result<(), Error>> + Send + '_ {
316        boxed(async move {
317            self.call(Request::new(Route::DeleteGuildApplicationCommand {
318                application_id,
319                guild_id,
320                command_id,
321            }))
322            .await
323        })
324    }
325
326    /// [Bulk Overwrite Guild Application Commands](https://docs.discord.com/developers/interactions/application-commands#bulk-overwrite-guild-application-commands):
327    /// replaces all of the application's commands in a guild with `commands`, and returns
328    /// them; see
329    /// [`bulk_overwrite_global_application_commands`](Self::bulk_overwrite_global_application_commands).
330    ///
331    /// discord.js counterpart: `GuildApplicationCommandManager#set`.
332    ///
333    /// # Errors
334    ///
335    /// See [`Rest::request`].
336    pub fn bulk_overwrite_guild_application_commands<'a>(
337        &'a self,
338        application_id: ApplicationId,
339        guild_id: GuildId,
340        commands: &'a [CreateApplicationCommand],
341    ) -> impl Future<Output = Result<Vec<ApplicationCommand>, Error>> + Send + 'a {
342        boxed(async move {
343            self.call(
344                Request::new(Route::BulkOverwriteGuildApplicationCommands {
345                    application_id,
346                    guild_id,
347                })
348                .json(commands)?,
349            )
350            .await
351        })
352    }
353
354    /// [Get Guild Application Command Permissions](https://docs.discord.com/developers/interactions/application-commands#get-guild-application-command-permissions):
355    /// returns the permission overwrites of the application's commands in a guild (only
356    /// commands that have overwrites).
357    ///
358    /// discord.js counterpart: `ApplicationCommandPermissionsManager#fetch`.
359    ///
360    /// # Errors
361    ///
362    /// See [`Rest::request`].
363    pub fn get_guild_application_command_permissions(
364        &self,
365        application_id: ApplicationId,
366        guild_id: GuildId,
367    ) -> impl Future<Output = Result<Vec<GuildCommandPermissions>, Error>> + Send + '_ {
368        boxed(async move {
369            self.call(Request::new(Route::GetGuildApplicationCommandPermissions {
370                application_id,
371                guild_id,
372            }))
373            .await
374        })
375    }
376
377    /// [Get Application Command Permissions](https://docs.discord.com/developers/interactions/application-commands#get-application-command-permissions):
378    /// returns the permission overwrites of one command in a guild.
379    ///
380    /// `command_id` may also be the application ID, for the overwrites that apply to all of
381    /// its commands without their own.
382    ///
383    /// discord.js counterpart: `ApplicationCommandPermissionsManager#fetch({ command })`.
384    ///
385    /// # Errors
386    ///
387    /// See [`Rest::request`]; `10066` Unknown Application Command Permissions when the
388    /// command has none.
389    pub fn get_application_command_permissions(
390        &self,
391        application_id: ApplicationId,
392        guild_id: GuildId,
393        command_id: CommandId,
394    ) -> impl Future<Output = Result<GuildCommandPermissions, Error>> + Send + '_ {
395        boxed(async move {
396            self.call(Request::new(Route::GetApplicationCommandPermissions {
397                application_id,
398                guild_id,
399                command_id,
400            }))
401            .await
402        })
403    }
404
405    /// [Edit Application Command Permissions](https://docs.discord.com/developers/interactions/application-commands#edit-application-command-permissions):
406    /// replaces the permission overwrites of one command in a guild.
407    ///
408    /// Discord rejects bot tokens here: the client must be built with
409    /// [`RestBuilder::bearer_token`](crate::RestBuilder::bearer_token), holding the `OAuth2`
410    /// access token (scope `applications.commands.permissions.update`) of a user who can
411    /// manage the guild and the command (D-108).
412    ///
413    /// discord.js counterpart: `ApplicationCommandPermissionsManager#set`.
414    ///
415    /// # Examples
416    ///
417    /// ```no_run
418    /// # async fn example(access_token: String, application_id: djs_model::id::ApplicationId, guild_id: djs_model::id::GuildId, command_id: djs_model::id::CommandId, role: djs_model::id::RoleId) -> Result<(), djs_rest::Error> {
419    /// use djs_model::{
420    ///     application_command::{CommandPermission, CommandPermissionType},
421    ///     rest::EditApplicationCommandPermissions,
422    /// };
423    /// use djs_rest::Rest;
424    ///
425    /// let user = Rest::builder().bearer_token(access_token).build();
426    /// let allow_role = CommandPermission::new(role.cast(), CommandPermissionType::Role, true);
427    /// let body = EditApplicationCommandPermissions::new(vec![allow_role]);
428    /// user.edit_application_command_permissions(application_id, guild_id, command_id, &body)
429    ///     .await?;
430    /// # Ok(())
431    /// # }
432    /// ```
433    ///
434    /// # Errors
435    ///
436    /// See [`Rest::request`]; `401 Unauthorized` with a bot token, `50001` Missing Access
437    /// when the user cannot manage the guild.
438    pub fn edit_application_command_permissions<'a>(
439        &'a self,
440        application_id: ApplicationId,
441        guild_id: GuildId,
442        command_id: CommandId,
443        body: &'a EditApplicationCommandPermissions,
444    ) -> impl Future<Output = Result<GuildCommandPermissions, Error>> + Send + 'a {
445        boxed(async move {
446            self.call(
447                Request::new(Route::EditApplicationCommandPermissions {
448                    application_id,
449                    guild_id,
450                    command_id,
451                })
452                .json(body)?,
453            )
454            .await
455        })
456    }
457}