djs_builders/command/slash.rs
1//! [`SlashCommandBuilder`] and its subcommands.
2
3use compact_str::CompactString;
4use djs_model::{
5 application_command::{CommandOption, SubCommandOption},
6 rest::CreateApplicationCommand,
7};
8
9use super::validate;
10use crate::ValidationError;
11
12/// Builds a [slash command](https://docs.discord.com/developers/interactions/application-commands#slash-commands)
13/// (`CHAT_INPUT`): a name users type after `/`, a description, and options, subcommands or
14/// subcommand groups.
15///
16/// Register the result with `Rest::create_global_application_command` (or the guild or bulk
17/// variants). As for every builder, setters only store and [`build`](Self::build) checks
18/// everything (D-179); [`build_unchecked`](Self::build_unchecked) skips the checks (D-180).
19///
20/// `build` checks what Discord checks, as measured on the live API (D-194–D-196):
21///
22/// | Part | Rule |
23/// |------|------|
24/// | names (command, subcommands, options, translations) | 1-32 lower-case letters, numbers, `-`, `_`, `ʼ` |
25/// | descriptions (and translations) | 1-100 characters, not blank |
26/// | options per level | at most 25, unique names, required ones first |
27/// | the command's own options | all subcommands / groups, or none |
28/// | a group's options | subcommands only |
29/// | a subcommand's options | no subcommands or groups |
30/// | choices | at most 25; names 1-100 characters; string values at most 100 |
31/// | `min_length` / `max_length` | 0-6000 / 1-6000, `max_length` ≥ `min_length` |
32/// | integers / numbers | within ±(2^53 − 1) / ±2^53; `max_value` ≥ `min_value` |
33/// | choices and autocomplete | not both |
34/// | the whole command | at most 8000 characters |
35///
36/// Characters are Unicode code points; descriptions and choice texts are measured after
37/// trimming. The 8000 total counts every name, description and string choice value, taking
38/// the longest translation of each (D-195).
39///
40/// discord.js counterpart: `SlashCommandBuilder`. Unlike discord.js, options are added with one
41/// [`option`](Self::option) method and mixing subcommands with options is reported by `build`
42/// instead of the type system (D-192, D-193).
43///
44/// # Examples
45///
46/// ```
47/// use djs_builders::{
48/// SlashCommandBuilder, SlashCommandIntegerOption, SlashCommandStringOption,
49/// SlashCommandUserOption,
50/// };
51/// use djs_model::{interaction::InteractionContextType, permissions::Permissions, util::Locale};
52///
53/// # fn main() -> Result<(), djs_builders::ValidationError> {
54/// let ban = SlashCommandBuilder::new("ban", "Bans a member")
55/// .name_localization(Locale::Polish, "zbanuj")
56/// .description_localization(Locale::Polish, "Banuje członka")
57/// .default_member_permissions(Permissions::BAN_MEMBERS)
58/// .contexts([InteractionContextType::Guild])
59/// .option(SlashCommandUserOption::new("user", "Who to ban").required(true))
60/// .option(SlashCommandStringOption::new("reason", "Why").max_length(512))
61/// .option(
62/// SlashCommandIntegerOption::new("days", "Days of messages to delete")
63/// .choice("None", 0)
64/// .choice("A week", 7),
65/// )
66/// .build()?;
67/// assert_eq!(ban.options.len(), 3);
68/// # Ok(())
69/// # }
70/// ```
71///
72/// A problem is reported by `build`:
73///
74/// ```
75/// use djs_builders::{SlashCommandBuilder, SlashCommandStringOption, ValidationError};
76///
77/// let error = SlashCommandBuilder::new("Ping", "Checks the bot").build().unwrap_err();
78/// assert_eq!(error.to_string(), "name must be lower case: use 'p' instead of 'P'");
79///
80/// let error = SlashCommandBuilder::new("echo", "Repeats a text")
81/// .option(SlashCommandStringOption::new("prefix", "Put before"))
82/// .option(SlashCommandStringOption::new("text", "What to repeat").required(true))
83/// .build()
84/// .unwrap_err();
85/// assert_eq!(error.field(), "options[1].required");
86/// ```
87#[derive(Clone, Debug, PartialEq)]
88#[must_use = "a builder does nothing until `build` is called"]
89pub struct SlashCommandBuilder {
90 command: CreateApplicationCommand,
91}
92
93impl SlashCommandBuilder {
94 /// Creates a slash command named `name` (1-32 lower-case letters, numbers, `-`, `_` or
95 /// `ʼ`) and described by `description` (1-100 characters).
96 ///
97 /// discord.js counterpart: `new SlashCommandBuilder().setName(…).setDescription(…)`.
98 pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
99 Self {
100 command: CreateApplicationCommand::chat_input(name, description),
101 }
102 }
103
104 name_localizations!(command);
105 description_localizations!(command);
106 command_settings!();
107
108 /// Adds an option (a parameter users fill in), after those already added: any
109 /// `SlashCommand…Option` of this crate, or a [`CommandOption`] of `djs-model`.
110 ///
111 /// A command has at most 25 options, with unique names and the required ones first. It
112 /// either has options or subcommands, not both.
113 ///
114 /// discord.js counterpart: `addStringOption`, `addIntegerOption`, … (one per type).
115 pub fn option(mut self, option: impl Into<CommandOption>) -> Self {
116 self.command.options.push(option.into());
117 self
118 }
119
120 /// Adds a subcommand (`/command subcommand`).
121 ///
122 /// discord.js counterpart: `addSubcommand`.
123 pub fn subcommand(self, subcommand: SlashCommandSubcommandBuilder) -> Self {
124 self.option(subcommand)
125 }
126
127 /// Adds a group of subcommands (`/command group subcommand`).
128 ///
129 /// discord.js counterpart: `addSubcommandGroup`.
130 pub fn subcommand_group(self, group: SlashCommandSubcommandGroupBuilder) -> Self {
131 self.option(group)
132 }
133
134 /// Checks the command against Discord's rules (see the [type docs](Self)) and returns it.
135 ///
136 /// discord.js counterpart: `SlashCommandBuilder#toJSON`.
137 ///
138 /// # Errors
139 ///
140 /// The first [`ValidationError`] found, checking the name, its translations, the
141 /// description, its translations, then each option in order (with what it contains), and
142 /// finally the 8000-character total ([`TooLong`](ValidationError::TooLong) with the field
143 /// `command`).
144 pub fn build(self) -> Result<CreateApplicationCommand, ValidationError> {
145 validate::slash_command(&self.command)?;
146 Ok(self.command)
147 }
148
149 /// Returns the command without any check (D-180).
150 ///
151 /// discord.js counterpart: `SlashCommandBuilder#toJSON` with validation off (`disableValidators`).
152 #[must_use]
153 pub fn build_unchecked(self) -> CreateApplicationCommand {
154 self.command
155 }
156}
157
158/// Builds a [subcommand](https://docs.discord.com/developers/interactions/application-commands#subcommands-and-subcommand-groups)
159/// of a slash command (`/command subcommand`), with its own options.
160///
161/// Add it with [`SlashCommandBuilder::subcommand`] or
162/// [`SlashCommandSubcommandGroupBuilder::subcommand`]. [`build`](Self::build) checks it on its
163/// own, with paths starting at its fields.
164///
165/// discord.js counterpart: `SlashCommandSubcommandBuilder`.
166///
167/// # Examples
168///
169/// ```
170/// use djs_builders::{SlashCommandBuilder, SlashCommandStringOption, SlashCommandSubcommandBuilder};
171///
172/// let tag = SlashCommandBuilder::new("tag", "Manages tags")
173/// .subcommand(
174/// SlashCommandSubcommandBuilder::new("show", "Shows a tag")
175/// .option(SlashCommandStringOption::new("name", "The tag").required(true)),
176/// )
177/// .subcommand(SlashCommandSubcommandBuilder::new("list", "Lists every tag"))
178/// .build()
179/// .unwrap();
180/// assert_eq!(tag.options[1].name(), "list");
181/// ```
182#[derive(Clone, Debug, PartialEq)]
183#[must_use = "a builder does nothing until it is added to a command or built"]
184pub struct SlashCommandSubcommandBuilder {
185 option: SubCommandOption,
186}
187
188impl SlashCommandSubcommandBuilder {
189 /// Creates a subcommand named `name` (1-32 lower-case letters, numbers, `-`, `_` or `ʼ`)
190 /// and described by `description` (1-100 characters).
191 ///
192 /// discord.js counterpart: `new SlashCommandSubcommandBuilder().setName(name)`.
193 pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
194 Self {
195 option: SubCommandOption::new(name, description),
196 }
197 }
198
199 name_localizations!(option);
200 description_localizations!(option);
201
202 /// Adds an option of the subcommand (at most 25; not a subcommand or group).
203 ///
204 /// discord.js counterpart: `addStringOption`, `addIntegerOption`, … (one per type).
205 pub fn option(mut self, option: impl Into<CommandOption>) -> Self {
206 self.option.options.push(option.into());
207 self
208 }
209
210 /// Checks the subcommand on its own and returns it as a [`CommandOption`].
211 ///
212 /// discord.js counterpart: `SlashCommandSubcommandBuilder#toJSON`.
213 ///
214 /// # Errors
215 ///
216 /// The first [`ValidationError`] found, as in [`SlashCommandBuilder::build`] (without the
217 /// 8000-character total, which applies to the whole command).
218 pub fn build(self) -> Result<CommandOption, ValidationError> {
219 let option = CommandOption::from(self);
220 validate::option_alone(&option)?;
221 Ok(option)
222 }
223
224 /// Returns the subcommand without any check (D-180).
225 ///
226 /// discord.js counterpart: `SlashCommandSubcommandBuilder#toJSON` with validation off (`disableValidators`).
227 #[must_use]
228 pub fn build_unchecked(self) -> CommandOption {
229 self.into()
230 }
231}
232
233impl From<SlashCommandSubcommandBuilder> for CommandOption {
234 fn from(subcommand: SlashCommandSubcommandBuilder) -> Self {
235 Self::SubCommand(subcommand.option)
236 }
237}
238
239/// Builds a [group of subcommands](https://docs.discord.com/developers/interactions/application-commands#subcommands-and-subcommand-groups)
240/// of a slash command (`/command group subcommand`).
241///
242/// Add it with [`SlashCommandBuilder::subcommand_group`]. A group contains only subcommands.
243///
244/// discord.js counterpart: `SlashCommandSubcommandGroupBuilder`.
245///
246/// # Examples
247///
248/// ```
249/// use djs_builders::{
250/// SlashCommandBuilder, SlashCommandStringOption, SlashCommandSubcommandBuilder,
251/// SlashCommandSubcommandGroupBuilder,
252/// };
253///
254/// let config = SlashCommandBuilder::new("config", "Bot settings")
255/// .subcommand_group(
256/// SlashCommandSubcommandGroupBuilder::new("set", "Changes a setting").subcommand(
257/// SlashCommandSubcommandBuilder::new("prefix", "Sets the prefix")
258/// .option(SlashCommandStringOption::new("value", "The new prefix").required(true)),
259/// ),
260/// )
261/// .build()
262/// .unwrap();
263/// assert_eq!(config.options[0].options()[0].name(), "prefix");
264/// ```
265#[derive(Clone, Debug, PartialEq)]
266#[must_use = "a builder does nothing until it is added to a command or built"]
267pub struct SlashCommandSubcommandGroupBuilder {
268 option: SubCommandOption,
269}
270
271impl SlashCommandSubcommandGroupBuilder {
272 /// Creates a group named `name` (1-32 lower-case letters, numbers, `-`, `_` or `ʼ`) and
273 /// described by `description` (1-100 characters).
274 ///
275 /// discord.js counterpart: `new SlashCommandSubcommandGroupBuilder().setName(name)`.
276 pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
277 Self {
278 option: SubCommandOption::new(name, description),
279 }
280 }
281
282 name_localizations!(option);
283 description_localizations!(option);
284
285 /// Adds a subcommand to the group (at most 25).
286 ///
287 /// discord.js counterpart: `addSubcommand`.
288 pub fn subcommand(mut self, subcommand: SlashCommandSubcommandBuilder) -> Self {
289 self.option.options.push(subcommand.into());
290 self
291 }
292
293 /// Checks the group on its own and returns it as a [`CommandOption`].
294 ///
295 /// discord.js counterpart: `SlashCommandSubcommandGroupBuilder#toJSON`.
296 ///
297 /// # Errors
298 ///
299 /// The first [`ValidationError`] found, as in [`SlashCommandBuilder::build`] (without the
300 /// 8000-character total).
301 pub fn build(self) -> Result<CommandOption, ValidationError> {
302 let option = CommandOption::from(self);
303 validate::option_alone(&option)?;
304 Ok(option)
305 }
306
307 /// Returns the group without any check (D-180).
308 ///
309 /// discord.js counterpart: `SlashCommandSubcommandGroupBuilder#toJSON` with validation off (`disableValidators`).
310 #[must_use]
311 pub fn build_unchecked(self) -> CommandOption {
312 self.into()
313 }
314}
315
316impl From<SlashCommandSubcommandGroupBuilder> for CommandOption {
317 fn from(group: SlashCommandSubcommandGroupBuilder) -> Self {
318 Self::SubCommandGroup(group.option)
319 }
320}