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
use twilight_model::{
    application::{
        command::Number,
        interaction::application_command::{
            CommandData, CommandInteractionDataResolved, CommandOptionValue, InteractionChannel,
            InteractionMember,
        },
    },
    guild::Role,
    id::{ChannelId, GenericId, RoleId, UserId},
    user::User,
};

use crate::error::{ParseError, ParseErrorType};

/// Parse [`CommandData`] into a concrete type.
///
/// This trait represent a slash command model, that can be initialized
/// from a [`CommandData`]. See the module-level documentation to learn more.
///
/// ## Derive macro
/// A derive macro is provided to implement this trait. The macro only works
/// with structs with named fields where all field types implement [`CommandOption`].
///
/// ### Macro attributes
/// The macro provide a `#[command]` attribute to configure generated code.
///
/// **Field parameters**:
/// - `#[command(rename = "")]`: use a different name for the field when parsing.
///
/// ## Example
/// ```
/// use twilight_interactions::command::{CommandModel, ResolvedUser};
///
/// #[derive(CommandModel)]
/// struct HelloCommand {
///     message: String,
///     user: Option<ResolvedUser>
/// }
/// ```
pub trait CommandModel: Sized {
    /// Construct this type from a [`CommandData`].
    fn from_interaction(data: CommandData) -> Result<Self, ParseError>;
}

/// Convert a [`CommandOptionValue`] into a concrete type.
///
/// This trait is used by the implementation of [`CommandData`] generated
/// by the derive macro.
pub trait CommandOption: Sized {
    /// Convert a [`CommandOptionValue`] into this value.
    fn from_option(
        value: CommandOptionValue,
        resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType>;
}

/// A resolved Discord user.
///
/// This struct implement [`CommandOption`] and can be used to
/// obtain resolved data for a given user id. The struct holds
/// a [`User`] and maybe an [`InteractionMember`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedUser {
    /// The resolved user.
    pub resolved: User,
    /// The resolved member, if found.
    pub member: Option<InteractionMember>,
}

macro_rules! lookup {
    ($resolved:ident.$cat:ident, $id:expr) => {
        $resolved
            .and_then(|resolved| resolved.$cat.iter().find(|val| val.id == $id).cloned())
            .ok_or_else(|| ParseErrorType::LookupFailed($id.0))
    };
}

impl CommandOption for String {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::String(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for i64 {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::Integer(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for Number {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::Number(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for f64 {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::Number(value) => Ok(value.0),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for bool {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::Boolean(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for UserId {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::User(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for ChannelId {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::Channel(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for RoleId {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::Role(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for GenericId {
    fn from_option(
        value: CommandOptionValue,
        _resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        match value {
            CommandOptionValue::Mentionable(value) => Ok(value),
            other => Err(ParseErrorType::InvalidType(other.kind())),
        }
    }
}

impl CommandOption for User {
    fn from_option(
        value: CommandOptionValue,
        resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        let user_id: UserId = match value {
            CommandOptionValue::User(value) => value,
            other => return Err(ParseErrorType::InvalidType(other.kind())),
        };

        lookup!(resolved.users, user_id)
    }
}

impl CommandOption for ResolvedUser {
    fn from_option(
        value: CommandOptionValue,
        resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        let user_id: UserId = match value {
            CommandOptionValue::User(value) => value,
            other => return Err(ParseErrorType::InvalidType(other.kind())),
        };

        Ok(Self {
            resolved: lookup!(resolved.users, user_id)?,
            member: lookup!(resolved.members, user_id).ok(),
        })
    }
}

impl CommandOption for InteractionChannel {
    fn from_option(
        value: CommandOptionValue,
        resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        let channel_id: ChannelId = match value {
            CommandOptionValue::Channel(value) => value,
            other => return Err(ParseErrorType::InvalidType(other.kind())),
        };

        lookup!(resolved.channels, channel_id)
    }
}

impl CommandOption for Role {
    fn from_option(
        value: CommandOptionValue,
        resolved: Option<&CommandInteractionDataResolved>,
    ) -> Result<Self, ParseErrorType> {
        let role_id: RoleId = match value {
            CommandOptionValue::Role(value) => value,
            other => return Err(ParseErrorType::InvalidType(other.kind())),
        };

        lookup!(resolved.roles, role_id)
    }
}