1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
//! A library for intuitively creating commands for use with the [`serenity`]
//! Discord library.

use serenity::all::{
    AttachmentId, ChannelId, CommandDataOption, CommandDataOptionValue, CommandOptionType,
    CreateCommand, CreateCommandOption, GenericId, RoleId, UserId,
};
/// Derive the [`Command`] trait.
///
/// This creates a top-level command for use with [`CommandData`]. The command
/// may contain regular options, sub-commands, and sub-command groups.
///
/// Documentation comments (`///`) will be used as the commands'/options'
/// descriptions, and are required whenever they are expected.
///
/// # Examples
///
/// ## `struct`s with named fields
///
/// A command with the specified options. Note that none of the fields can be
/// sub-commands or sub-command groups, and the macro will emit an error during
/// compilation if this is the case.
///
/// ```rust
/// use serenity_commands::Command;
///
/// #[derive(Command)]
/// struct Add {
///     /// The first number.
///     first: f64,
///
///     /// The second number.
///     second: f64,
/// }
/// ```
///
/// ## Newtype `struct`s
///
/// Delegates the implementation to the inner type, which must implement
/// [`Command`].
///
/// ```rust
/// use serenity_commands::Command;
///
/// # #[derive(Command)]
/// # struct InnerCommand;
/// #
/// #[derive(Command)]
/// struct CommandWrapper(InnerCommand);
/// ```
///
/// ## Unit `struct`s
///
/// A command with no options.
///
/// ```rust
/// use serenity_commands::Command;
///
/// #[derive(Command)]
/// struct Ping;
/// ```
///
/// ## `enum`s
///
/// A command with sub-commands. Note that the macro will emit an error during
/// compilation if any of the variants are not sub-commands or sub-command
/// groups.
///
/// The behaviour for each variant type is analagous to that of the
/// corresponding `struct` type:
///
/// - A variant with named fields is a sub-command with the specified options.
/// - A newtype variant is a sub-command/sub-command group which delegates the
///   implementation to the inner type, which must implement [`CommandOption`].
/// - A unit variant is a sub-command with no options.
///
/// ```rust
/// use serenity_commands::Command;
///
/// # #[derive(serenity_commands::CommandOption)]
/// # struct MathCommand;
/// #
/// #[derive(Command)]
/// enum MyCommands {
///     /// Ping the bot.
///     Ping,
///
///     /// Echo a message.
///     Echo {
///         /// The message to echo.
///         message: String,
///     },
///
///     /// Perform math operations.
///     Math(MathCommand),
/// }
/// ```
pub use serenity_commands_macros::Command;
/// Derive the [`CommandData`] trait.
///
/// This creates a top-level utility structure which can list all of its
/// commands (for use with [`GuildId::set_commands`], etc.) and extract data
/// from [`CommandInteraction`]s.
///
/// This macro only supports `enum`s, as it is intended to select from one of
/// many commands.
///
/// Documentation comments (`///`) will be used as the commands'/options'
/// descriptions, and are required whenever they are expected.
///
/// # Examples
///
/// - A variant with named fields is a command with the specified options.
/// - A newtype variant is a command which delegates the implementation to the
///   inner type, which must implement [`Command`].
/// - A unit variant is a command with no options.
///
/// ```rust
/// use serenity_commands::CommandData;
///
/// # #[derive(serenity_commands::Command)]
/// # struct MathCommand;
/// #
/// #[derive(CommandData)]
/// enum Commands {
///     /// Ping the bot.
///     Ping,
///
///     /// Echo a message.
///     Echo {
///         /// The message to echo.
///         message: String,
///     },
///
///     /// Perform math operations.
///     Math(MathCommand),
/// }
/// ```
///
/// [`GuildId::set_commands`]: serenity::all::GuildId::set_commands
/// [`CommandInteraction`]: serenity::all::CommandInteraction
pub use serenity_commands_macros::CommandData;
/// Derive the [`CommandOption`] trait.
///
/// This creates a sub-command or sub-command group which can be nested
/// within other [`CommandOption`]s or [`Command`]s.
///
/// Documentation comments (`///`) will be used as the options' descriptions,
/// and are required whenever they are expected.
///
/// # Examples
///
/// ## `struct`s with named fields
///
/// A sub-command with the specified options. Note that none of the fields
/// can be sub-commands or sub-command groups, and the macro will emit an
/// error during compilation if this is the case.
///
/// Sets [`CommandOption::TYPE`] to [`SubCommand`].
///
/// ```rust
/// use serenity_commands::CommandOption;
///
/// #[derive(CommandOption)]
/// struct AddNumbers {
///     /// The first number.
///     first: f64,
///
///     /// The second number, optional.
///     second: Option<f64>,
/// }
/// ```
///
/// ## Newtype `struct`s
///
/// Delegates the implementation to the inner type, which must implement
/// [`CommandOption`].
///
/// Sets [`CommandOption::TYPE`] to the inner type's [`CommandOption::TYPE`].
///
/// ```rust
/// use serenity_commands::CommandOption;
///
/// #[derive(CommandOption)]
/// struct FloatWrapper(f64);
/// ```
///
/// ## Unit `struct`s
///
/// A sub-command with no options.
///
/// Sets [`CommandOption::TYPE`] to [`SubCommand`].
///
/// ```rust
/// use serenity_commands::CommandOption;
///
/// #[derive(CommandOption)]
/// struct Ping;
/// ```
///
/// ## `enum`s
///
/// Sets [`CommandOption::TYPE`] to [`SubCommandGroup`].
///
/// A sub-command group. Note that the macro will emit an
/// error during compilation if any of the variants are not sub-commands or
/// sub-command groups.
///
/// The behaviour for each variant type is analagous to that of the
/// corresponding `struct` type:
///
/// - A variant with named fields is a sub-command with the specified options.
/// - A newtype variant is a sub-command/sub-command group which
///  delegates the implementation to the inner type, which must implement
/// [`CommandOption`].
/// - A unit variant is a sub-command with no options.
///
/// ```rust
/// use serenity_commands::CommandOption;
///
/// # #[derive(CommandOption)]
/// # struct MathSubCommand;
/// #
/// #[derive(CommandOption)]
/// enum MyCommands {
///     /// Ping the bot.
///     Ping,
///
///     /// Echo a message.
///     Echo {
///         /// The message to echo.
///         message: String,
///     },
///
///     /// Perform math operations.
///     Math(MathSubCommand),
/// }
/// ```
///
/// [`SubCommand`]: serenity::all::CommandOptionType::SubCommand
/// [`SubCommandGroup`]: serenity::all::CommandOptionType::SubCommandGroup
pub use serenity_commands_macros::CommandOption;
use thiserror::Error;

/// A type alias for [`Result`]s which use [`Error`] as the error type.
pub type Result<T> = std::result::Result<T, Error>;

/// An error which can occur when extracting data from a command interaction.
#[derive(Debug, Clone, Error)]
pub enum Error {
    /// An unknown command was provided.
    #[error("unknown command: {0}")]
    UnknownCommand(String),

    /// An incorrect command option type was provided.
    #[error("incorrect command option type: got {got:?}, expected {expected:?}")]
    IncorrectCommandOptionType {
        /// The type of command option that was provided.
        got: CommandOptionType,

        /// The type of command option that was expected.
        expected: CommandOptionType,
    },

    /// An incorrect number of command options were provided.
    #[error("incorrect command option count: got {got}, expected {expected}")]
    IncorrectCommandOptionCount {
        /// The number of command options that were provided.
        got: usize,

        /// The number of command options that were expected.
        expected: usize,
    },

    /// An unknown command option was provided.
    #[error("unknown command option: {0}")]
    UnknownCommandOption(String),

    /// A required command option was not provided.
    #[error("required command option not provided")]
    MissingRequiredCommandOption,
}

/// A top-level utility structure which can list all of its commands (for use
/// with [`GuildId::set_commands`], etc.) and extract data from
/// [`CommandInteraction`]s.
///
/// [`GuildId::set_commands`]: serenity::all::GuildId::set_commands
/// [`CommandInteraction`]: serenity::all::CommandInteraction
pub trait CommandData: Sized {
    /// List all of the commands that this type represents.
    fn to_command_data() -> Vec<CreateCommand>;

    /// Extract data from a [`serenity::all::CommandData`].
    ///
    /// # Errors
    ///
    /// Returns an error if the implementation fails.
    fn from_command_data(data: &serenity::all::CommandData) -> Result<Self>;
}

/// A top-level command for use with [`CommandData`]. The command may contain
/// regular options, sub-commands, and sub-command groups.
pub trait Command: Sized {
    /// Create the command.
    fn to_command(name: impl Into<String>, description: impl Into<String>) -> CreateCommand;

    /// Extract this command's data from an option list.
    ///
    /// # Errors
    ///
    /// Returns an error if the implementation fails.
    fn from_command(options: &[CommandDataOption]) -> Result<Self>;
}

/// A sub-command or sub-command group which can be nested within other
/// [`CommandOption`]s or [`Command`]s.
pub trait CommandOption: Sized {
    /// The type of this command option.
    const TYPE: CommandOptionType;

    /// Create the command option.
    fn to_option(name: impl Into<String>, description: impl Into<String>) -> CreateCommandOption;

    /// Extract this command option's data from an option list.
    ///
    /// # Errors
    ///
    /// Returns an error if the implementation fails.
    fn from_option(option: Option<&CommandDataOptionValue>) -> Result<Self>;
}

macro_rules! impl_command_option {
    ($($Variant:ident($($Ty:ty),* $(,)?)),* $(,)?) => {
        $($(
            impl CommandOption for $Ty {
                const TYPE: CommandOptionType = CommandOptionType::$Variant;

                fn to_option(name: impl Into<String>, description: impl Into<String>) -> CreateCommandOption {
                    CreateCommandOption::new(Self::TYPE, name, description)
                        .required(true)
                }

                fn from_option(option: Option<&CommandDataOptionValue>) -> Result<Self> {
                    let option = option.ok_or(Error::MissingRequiredCommandOption)?;

                    match option {
                        CommandDataOptionValue::$Variant(v) => Ok(v.clone() as _),
                        _ => Err(Error::IncorrectCommandOptionType {
                            got: option.kind(),
                            expected: Self::TYPE,
                        }),
                    }
                }
            }
        )*)*
    };
}

impl_command_option! {
    Boolean(bool),
    String(String),
    Attachment(AttachmentId),
    Channel(ChannelId),
    Mentionable(GenericId),
    Role(RoleId),
    User(UserId),
}

macro_rules! impl_number_command_option {
    ($($Ty:ty),* $(,)?) => {
        $(
            impl CommandOption for $Ty {
                const TYPE: CommandOptionType = CommandOptionType::Number;

                fn to_option(name: impl Into<String>, description: impl Into<String>) -> CreateCommandOption {
                    CreateCommandOption::new(Self::TYPE, name, description)
                        .required(true)
                        .min_number_value(<$Ty>::MIN as _)
                        .max_number_value(<$Ty>::MAX as _)
                }

                fn from_option(option: Option<&CommandDataOptionValue>) -> Result<Self> {
                    let option = option.ok_or(Error::MissingRequiredCommandOption)?;

                    match option {
                        CommandDataOptionValue::Number(v) => Ok(*v as _),
                        _ => Err(Error::IncorrectCommandOptionType {
                            got: option.kind(),
                            expected: Self::TYPE,
                        }),
                    }
                }
            }
        )*
    };
}

impl_number_command_option!(f32, f64);

macro_rules! impl_integer_command_option {
    ($($Ty:ty),* $(,)?) => {
        $(
            impl CommandOption for $Ty {
                const TYPE: CommandOptionType = CommandOptionType::Integer;

                fn to_option(name: impl Into<String>, description: impl Into<String>) -> CreateCommandOption {
                    CreateCommandOption::new(Self::TYPE, name, description)
                        .required(true)
                        .min_int_value(<$Ty>::MIN as _)
                        .max_int_value(<$Ty>::MAX as _)
                }

                fn from_option(option: Option<&CommandDataOptionValue>) -> Result<Self> {
                    let option = option.ok_or(Error::MissingRequiredCommandOption)?;

                    match option {
                        CommandDataOptionValue::Integer(v) => Ok(*v as _),
                        _ => Err(Error::IncorrectCommandOptionType {
                            got: option.kind(),
                            expected: Self::TYPE,
                        }),
                    }
                }
            }
        )*
    };
}

impl_integer_command_option!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);

impl<T: CommandOption> CommandOption for Option<T> {
    const TYPE: CommandOptionType = T::TYPE;

    fn to_option(name: impl Into<String>, description: impl Into<String>) -> CreateCommandOption {
        T::to_option(name, description).required(false)
    }

    fn from_option(option: Option<&CommandDataOptionValue>) -> Result<Self> {
        option
            .map(|option| T::from_option(Some(option)))
            .transpose()
    }
}