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
mod resolved;

pub use self::resolved::{CommandInteractionDataResolved, InteractionChannel, InteractionMember};

use crate::{
    application::command::{CommandOptionType, Number},
    id::{ChannelId, CommandId, GenericId, RoleId, UserId},
};
use serde::{
    de::{Error as DeError, Unexpected},
    ser::SerializeStruct,
    Deserialize, Deserializer, Serialize, Serializer,
};
use std::borrow::Cow;

/// Data received when an [`ApplicationCommand`] interaction is executed.
///
/// Refer to [the discord docs] for more information.
///
/// [`ApplicationCommand`]: crate::application::interaction::Interaction::ApplicationCommand
/// [the discord docs]: https://discord.com/developers/docs/interactions/application-commands#interaction-applicationcommandinteractiondata
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CommandData {
    /// ID of the command.
    pub id: CommandId,
    /// Name of the command.
    pub name: String,
    /// List of parsed options specified by the user.
    #[serde(default)]
    pub options: Vec<CommandDataOption>,
    /// Data sent if any of the options are discord types.
    pub resolved: Option<CommandInteractionDataResolved>,
}

/// Data received when a user fills in a command option.
///
/// Refer to [the discord docs] for more information.
///
/// [the discord docs]: https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-interaction-data-option-structure
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommandDataOption {
    pub name: String,
    pub value: CommandOptionValue,
}

/// Value of a [`CommandDataOption`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CommandOptionValue {
    String(String),
    Integer(i64),
    Boolean(bool),
    User(UserId),
    Channel(ChannelId),
    Role(RoleId),
    Mentionable(GenericId),
    SubCommand(Vec<CommandDataOption>),
    SubCommandGroup(Vec<CommandDataOption>),
    Number(Number),
}

#[derive(Debug, Deserialize)]
struct CommandDataOptionRaw<'a> {
    name: String,
    #[serde(rename = "type")]
    kind: CommandOptionType,
    value: Option<CommandOptionValueRaw<'a>>,
    #[serde(default)]
    options: Option<Vec<CommandDataOption>>,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
enum CommandOptionValueRaw<'a> {
    String(Cow<'a, str>),
    Integer(i64),
    Number(f64),
    Boolean(bool),
}

impl Serialize for CommandDataOption {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut state = serializer.serialize_struct("CommandDataOptionRaw", 3)?;

        state.serialize_field("name", &self.name)?;

        state.serialize_field("type", &self.value.kind())?;

        match self.value {
            CommandOptionValue::SubCommand(ref opts)
            | CommandOptionValue::SubCommandGroup(ref opts) => {
                state.serialize_field("options", &Some(opts))?
            }
            CommandOptionValue::String(ref value) => state
                .serialize_field("value", &Some(CommandOptionValueRaw::String(value.into())))?,
            CommandOptionValue::Integer(value) => {
                state.serialize_field("value", &Some(CommandOptionValueRaw::Integer(value)))?
            }
            CommandOptionValue::Boolean(value) => {
                state.serialize_field("value", &Some(CommandOptionValueRaw::Boolean(value)))?
            }
            CommandOptionValue::User(UserId(id))
            | CommandOptionValue::Channel(ChannelId(id))
            | CommandOptionValue::Role(RoleId(id))
            | CommandOptionValue::Mentionable(GenericId(id)) => state.serialize_field(
                "value",
                &Some(CommandOptionValueRaw::String(id.to_string().into())),
            )?,
            CommandOptionValue::Number(value) => {
                state.serialize_field("value", &Some(CommandOptionValueRaw::Number(value.0)))?
            }
        }
        state.end()
    }
}

impl<'de> Deserialize<'de> for CommandDataOption {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = CommandDataOptionRaw::deserialize(deserializer)?;
        let value = if let Some(value) = raw.value {
            match (raw.kind, value) {
                (CommandOptionType::String, CommandOptionValueRaw::String(s)) => {
                    CommandOptionValue::String(s.into_owned())
                }
                (CommandOptionType::Integer, CommandOptionValueRaw::Integer(i)) => {
                    CommandOptionValue::Integer(i)
                }
                (CommandOptionType::Boolean, CommandOptionValueRaw::Boolean(b)) => {
                    CommandOptionValue::Boolean(b)
                }
                (CommandOptionType::User, CommandOptionValueRaw::String(s)) => {
                    let id =
                        UserId(s.parse().map_err(|_| {
                            DeError::invalid_value(Unexpected::Str(&s), &"user ID")
                        })?);

                    CommandOptionValue::User(id)
                }
                (CommandOptionType::Channel, CommandOptionValueRaw::String(s)) => {
                    let id =
                        ChannelId(s.parse().map_err(|_| {
                            DeError::invalid_value(Unexpected::Str(&s), &"channel ID")
                        })?);

                    CommandOptionValue::Channel(id)
                }
                (CommandOptionType::Role, CommandOptionValueRaw::String(s)) => {
                    let id =
                        RoleId(s.parse().map_err(|_| {
                            DeError::invalid_value(Unexpected::Str(&s), &"role ID")
                        })?);

                    CommandOptionValue::Role(id)
                }
                (CommandOptionType::Mentionable, CommandOptionValueRaw::String(s)) => {
                    let id = GenericId(s.parse().map_err(|_| {
                        DeError::invalid_value(Unexpected::Str(&s), &"snowflake ID")
                    })?);

                    CommandOptionValue::Mentionable(id)
                }
                (CommandOptionType::SubCommand | CommandOptionType::SubCommandGroup, _) => {
                    return Err(DeError::custom(format!(
                        "invalid option data: {:?} has value instead of options",
                        raw.kind
                    )));
                }
                (CommandOptionType::Number, CommandOptionValueRaw::String(s)) => {
                    let value = s
                        .parse::<f64>()
                        .map_err(|_| DeError::invalid_value(Unexpected::Str(&s), &"number"))?;

                    CommandOptionValue::Number(Number(value))
                }
                (kind, value) => {
                    return Err(DeError::custom(format!(
                        "invalid option value/type pair: value is {:?} but type is {:?}",
                        value, kind,
                    )));
                }
            }
        } else {
            let options = raw
                .options
                .ok_or_else(|| DeError::missing_field("options"))?;

            match raw.kind {
                CommandOptionType::SubCommand => CommandOptionValue::SubCommand(options),
                CommandOptionType::SubCommandGroup => CommandOptionValue::SubCommandGroup(options),
                kind => {
                    return Err(DeError::custom(format!(
                        "no `value` but type is {:?}",
                        kind
                    )))
                }
            }
        };
        Ok(CommandDataOption {
            name: raw.name,
            value,
        })
    }
}

impl CommandOptionValue {
    pub const fn kind(&self) -> CommandOptionType {
        match self {
            CommandOptionValue::String(_) => CommandOptionType::String,
            CommandOptionValue::Integer(_) => CommandOptionType::Integer,
            CommandOptionValue::Boolean(_) => CommandOptionType::Boolean,
            CommandOptionValue::User(_) => CommandOptionType::User,
            CommandOptionValue::Channel(_) => CommandOptionType::Channel,
            CommandOptionValue::Role(_) => CommandOptionType::Role,
            CommandOptionValue::Mentionable(_) => CommandOptionType::Mentionable,
            CommandOptionValue::SubCommand(_) => CommandOptionType::SubCommand,
            CommandOptionValue::SubCommandGroup(_) => CommandOptionType::SubCommandGroup,
            CommandOptionValue::Number(_) => CommandOptionType::Number,
        }
    }
}