djs_builders/command/option.rs
1//! The option types of slash commands: `SlashCommandStringOption`, `SlashCommandIntegerOption`,
2//! and so on, one per [option type](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type).
3
4use compact_str::CompactString;
5use djs_model::{
6 application_command::{
7 AttachmentOption, BasicOption, ChannelOption, Choice, CommandOption, IntegerOption,
8 NumberOption, StringOption,
9 },
10 channel::ChannelType,
11};
12
13use super::validate;
14use crate::ValidationError;
15
16/// Defines an option type: the struct around its model value, `new`, `required`, the
17/// translations, `build` / `build_unchecked` and the conversion into [`CommandOption`].
18macro_rules! option_type {
19 (
20 $(#[$meta:meta])*
21 $name:ident($model:ident) => $variant:ident
22 ) => {
23 $(#[$meta])*
24 #[derive(Clone, Debug, PartialEq)]
25 #[must_use = "an option does nothing until it is added to a command or built"]
26 pub struct $name {
27 option: $model,
28 }
29
30 impl $name {
31 /// Creates an optional option named `name` (1-32 lower-case letters, numbers, `-`,
32 /// `_` or `ʼ`) and described by `description` (1-100 characters).
33 ///
34 /// discord.js counterpart: the constructor of the option builders (`SlashCommandStringOption`, …), with `setName`.
35 pub fn new(
36 name: impl Into<CompactString>,
37 description: impl Into<CompactString>,
38 ) -> Self {
39 Self {
40 option: $model::new(name, description),
41 }
42 }
43
44 /// Sets whether users must fill the option in (default: no). Required options
45 /// must come before optional ones.
46 ///
47 /// discord.js counterpart: `setRequired`.
48 pub fn required(mut self, required: bool) -> Self {
49 self.option.required = required;
50 self
51 }
52
53 name_localizations!(option);
54 description_localizations!(option);
55
56 /// Checks the option on its own and returns it as a [`CommandOption`]; the paths
57 /// in a [`ValidationError`] start at its fields (`name`, `choices[0].name`).
58 ///
59 /// Adding the builder to a command checks it as part of the command instead.
60 ///
61 /// discord.js counterpart: `toJSON` of the option builders (`SlashCommandStringOption`, …).
62 ///
63 /// # Errors
64 ///
65 /// The first [`ValidationError`] found, as in
66 /// [`SlashCommandBuilder::build`](crate::SlashCommandBuilder::build).
67 pub fn build(self) -> Result<CommandOption, ValidationError> {
68 let option = CommandOption::from(self);
69 validate::option_alone(&option)?;
70 Ok(option)
71 }
72
73 /// Returns the option without any check (D-180).
74 ///
75 /// discord.js counterpart: `toJSON` of the option builders with validation off (`disableValidators`).
76 #[must_use]
77 pub fn build_unchecked(self) -> CommandOption {
78 self.into()
79 }
80 }
81
82 impl From<$name> for CommandOption {
83 fn from(option: $name) -> Self {
84 Self::$variant(option.option)
85 }
86 }
87 };
88}
89
90option_type! {
91 /// Builds a [string option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
92 /// of a slash command: free text, optionally limited in length, picked from up to 25
93 /// [choices](Self::choice), or suggested by the app through
94 /// [autocomplete](Self::autocomplete) (not together with choices, D-196).
95 ///
96 /// discord.js counterpart: `SlashCommandStringOption`.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// use djs_builders::{SlashCommandBuilder, SlashCommandStringOption};
102 ///
103 /// let command = SlashCommandBuilder::new("language", "Sets your language")
104 /// .option(
105 /// SlashCommandStringOption::new("language", "The language")
106 /// .required(true)
107 /// .choice("English", "en")
108 /// .choice("Polski", "pl"),
109 /// )
110 /// .option(SlashCommandStringOption::new("note", "Anything else").max_length(200))
111 /// .build()
112 /// .unwrap();
113 /// assert_eq!(command.options.len(), 2);
114 /// ```
115 SlashCommandStringOption(StringOption) => String
116}
117
118impl SlashCommandStringOption {
119 /// Adds a choice: `name` is shown to users (1-100 characters), `value` is what the app
120 /// receives (at most 100 characters). An option has at most 25 choices.
121 ///
122 /// discord.js counterpart: `addChoices`.
123 pub fn choice(
124 mut self,
125 name: impl Into<CompactString>,
126 value: impl Into<CompactString>,
127 ) -> Self {
128 self.option.choices.push(Choice::new(name, value.into()));
129 self
130 }
131
132 /// Adds several choices, after those already added — for example with translated names
133 /// ([`Choice::name_localizations`]).
134 ///
135 /// discord.js counterpart: `addChoices`.
136 pub fn choices(mut self, choices: impl IntoIterator<Item = Choice<CompactString>>) -> Self {
137 self.option.choices.extend(choices);
138 self
139 }
140
141 /// Sets the shortest text users may enter (0-6000).
142 ///
143 /// discord.js counterpart: `setMinLength`.
144 pub fn min_length(mut self, min_length: u16) -> Self {
145 self.option.min_length = Some(min_length);
146 self
147 }
148
149 /// Sets the longest text users may enter (1-6000, at least the
150 /// [`min_length`](Self::min_length)).
151 ///
152 /// discord.js counterpart: `setMaxLength`.
153 pub fn max_length(mut self, max_length: u16) -> Self {
154 self.option.max_length = Some(max_length);
155 self
156 }
157
158 /// Sets whether the app suggests values as users type, through autocomplete interactions
159 /// (not together with choices).
160 ///
161 /// discord.js counterpart: `setAutocomplete`.
162 pub fn autocomplete(mut self, autocomplete: bool) -> Self {
163 self.option.autocomplete = autocomplete;
164 self
165 }
166}
167
168option_type! {
169 /// Builds an [integer option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
170 /// of a slash command: a whole number between -(2^53 − 1) and 2^53 − 1, optionally bounded,
171 /// picked from up to 25 [choices](Self::choice), or suggested through
172 /// [autocomplete](Self::autocomplete).
173 ///
174 /// discord.js counterpart: `SlashCommandIntegerOption`.
175 ///
176 /// # Examples
177 ///
178 /// ```
179 /// use djs_builders::{SlashCommandBuilder, SlashCommandIntegerOption};
180 ///
181 /// let command = SlashCommandBuilder::new("roll", "Rolls a die")
182 /// .option(SlashCommandIntegerOption::new("sides", "How many sides").min_value(2).max_value(100))
183 /// .build()
184 /// .unwrap();
185 /// assert_eq!(command.options[0].name(), "sides");
186 /// ```
187 SlashCommandIntegerOption(IntegerOption) => Integer
188}
189
190impl SlashCommandIntegerOption {
191 /// Adds a choice: `name` is shown to users (1-100 characters), `value` is what the app
192 /// receives. An option has at most 25 choices.
193 ///
194 /// discord.js counterpart: `addChoices`.
195 pub fn choice(mut self, name: impl Into<CompactString>, value: i64) -> Self {
196 self.option.choices.push(Choice::new(name, value));
197 self
198 }
199
200 /// Adds several choices, after those already added.
201 ///
202 /// discord.js counterpart: `addChoices`.
203 pub fn choices(mut self, choices: impl IntoIterator<Item = Choice<i64>>) -> Self {
204 self.option.choices.extend(choices);
205 self
206 }
207
208 /// Sets the smallest value users may enter.
209 ///
210 /// discord.js counterpart: `setMinValue`.
211 pub fn min_value(mut self, min_value: i64) -> Self {
212 self.option.min_value = Some(min_value);
213 self
214 }
215
216 /// Sets the largest value users may enter (at least the [`min_value`](Self::min_value)).
217 ///
218 /// discord.js counterpart: `setMaxValue`.
219 pub fn max_value(mut self, max_value: i64) -> Self {
220 self.option.max_value = Some(max_value);
221 self
222 }
223
224 /// Sets whether the app suggests values as users type (not together with choices).
225 ///
226 /// discord.js counterpart: `setAutocomplete`.
227 pub fn autocomplete(mut self, autocomplete: bool) -> Self {
228 self.option.autocomplete = autocomplete;
229 self
230 }
231}
232
233option_type! {
234 /// Builds a [number option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
235 /// of a slash command: a finite double between -2^53 and 2^53, optionally bounded, picked
236 /// from up to 25 [choices](Self::choice), or suggested through
237 /// [autocomplete](Self::autocomplete).
238 ///
239 /// discord.js counterpart: `SlashCommandNumberOption`.
240 SlashCommandNumberOption(NumberOption) => Number
241}
242
243impl SlashCommandNumberOption {
244 /// Adds a choice: `name` is shown to users (1-100 characters), `value` is what the app
245 /// receives. An option has at most 25 choices.
246 ///
247 /// discord.js counterpart: `addChoices`.
248 pub fn choice(mut self, name: impl Into<CompactString>, value: f64) -> Self {
249 self.option.choices.push(Choice::new(name, value));
250 self
251 }
252
253 /// Adds several choices, after those already added.
254 ///
255 /// discord.js counterpart: `addChoices`.
256 pub fn choices(mut self, choices: impl IntoIterator<Item = Choice<f64>>) -> Self {
257 self.option.choices.extend(choices);
258 self
259 }
260
261 /// Sets the smallest value users may enter.
262 ///
263 /// discord.js counterpart: `setMinValue`.
264 pub fn min_value(mut self, min_value: f64) -> Self {
265 self.option.min_value = Some(min_value);
266 self
267 }
268
269 /// Sets the largest value users may enter (at least the [`min_value`](Self::min_value)).
270 ///
271 /// discord.js counterpart: `setMaxValue`.
272 pub fn max_value(mut self, max_value: f64) -> Self {
273 self.option.max_value = Some(max_value);
274 self
275 }
276
277 /// Sets whether the app suggests values as users type (not together with choices).
278 ///
279 /// discord.js counterpart: `setAutocomplete`.
280 pub fn autocomplete(mut self, autocomplete: bool) -> Self {
281 self.option.autocomplete = autocomplete;
282 self
283 }
284}
285
286option_type! {
287 /// Builds a [boolean option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
288 /// of a slash command: true or false.
289 ///
290 /// discord.js counterpart: `SlashCommandBooleanOption`.
291 SlashCommandBooleanOption(BasicOption) => Boolean
292}
293
294option_type! {
295 /// Builds a [user option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
296 /// of a slash command: a user (and their member, in a server).
297 ///
298 /// discord.js counterpart: `SlashCommandUserOption`.
299 SlashCommandUserOption(BasicOption) => User
300}
301
302option_type! {
303 /// Builds a [role option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
304 /// of a slash command.
305 ///
306 /// discord.js counterpart: `SlashCommandRoleOption`.
307 SlashCommandRoleOption(BasicOption) => Role
308}
309
310option_type! {
311 /// Builds a [mentionable option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
312 /// of a slash command: a user or a role.
313 ///
314 /// discord.js counterpart: `SlashCommandMentionableOption`.
315 SlashCommandMentionableOption(BasicOption) => Mentionable
316}
317
318option_type! {
319 /// Builds a [channel option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
320 /// of a slash command: a channel or category, optionally only of some
321 /// [types](Self::channel_types).
322 ///
323 /// discord.js counterpart: `SlashCommandChannelOption`.
324 ///
325 /// # Examples
326 ///
327 /// ```
328 /// use djs_builders::SlashCommandChannelOption;
329 /// use djs_model::channel::ChannelType;
330 ///
331 /// let option = SlashCommandChannelOption::new("channel", "Where to post")
332 /// .channel_types([ChannelType::GuildText, ChannelType::GuildAnnouncement])
333 /// .build()
334 /// .unwrap();
335 /// assert_eq!(option.name(), "channel");
336 /// ```
337 SlashCommandChannelOption(ChannelOption) => Channel
338}
339
340impl SlashCommandChannelOption {
341 /// Sets the channel types offered (all when not set), replacing those set before.
342 ///
343 /// discord.js counterpart: `addChannelTypes`.
344 pub fn channel_types(mut self, channel_types: impl IntoIterator<Item = ChannelType>) -> Self {
345 self.option.channel_types = channel_types.into_iter().collect();
346 self
347 }
348}
349
350option_type! {
351 /// Builds an [attachment option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type)
352 /// of a slash command: a file users upload.
353 ///
354 /// discord.js counterpart: `SlashCommandAttachmentOption`.
355 SlashCommandAttachmentOption(AttachmentOption) => Attachment
356}
357
358impl SlashCommandAttachmentOption {
359 /// Sets the [file types](https://docs.discord.com/developers/reference#file-type-filtering)
360 /// users may pick, as extensions such as `png` (all when not set), replacing those set
361 /// before.
362 ///
363 /// discord.js counterpart: none (`@discordjs/builders` has no file types).
364 pub fn file_types<T: Into<CompactString>>(
365 mut self,
366 file_types: impl IntoIterator<Item = T>,
367 ) -> Self {
368 self.option.file_types = file_types.into_iter().map(Into::into).collect();
369 self
370 }
371}