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
use std::collections::HashMap;
use serde::Serialize;
#[cfg(feature = "model")]
use crate::builder::{Builder, CreateCommand};
#[cfg(feature = "model")]
use crate::http::{CacheHttp, Http};
use crate::internal::prelude::*;
use crate::model::channel::ChannelType;
use crate::model::id::{
ApplicationId,
CommandId,
CommandPermissionId,
CommandVersionId,
GuildId,
RoleId,
UserId,
};
use crate::model::Permissions;
/// The base command model that belongs to an application.
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-structure).
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Command {
/// The command Id.
pub id: CommandId,
/// The application command kind.
#[serde(rename = "type")]
pub kind: CommandType,
/// The parent application Id.
pub application_id: ApplicationId,
/// The command guild Id, if it is a guild command.
///
/// **Note**: It may only be present if it is received through the gateway.
pub guild_id: Option<GuildId>,
/// The command name.
pub name: String,
/// The localized command name of the selected locale.
///
/// If the name is localized, either this field or [`Self::name_localizations`] is set,
/// depending on which endpoint this data was retrieved from
/// ([source](https://discord.com/developers/docs/interactions/application-commands#retrieving-localized-commands)).
pub name_localized: Option<String>,
/// All localized command names.
///
/// If the name is localized, either this field or [`Self::name_localized`] is set, depending
/// on which endpoint this data was retrieved from
/// ([source](https://discord.com/developers/docs/interactions/application-commands#retrieving-localized-commands)).
pub name_localizations: Option<HashMap<String, String>>,
/// The command description.
pub description: String,
/// The localized command description of the selected locale.
///
/// If the description is localized, either this field or [`Self::description_localizations`]
/// is set, depending on which endpoint this data was retrieved from
/// ([source](https://discord.com/developers/docs/interactions/application-commands#retrieving-localized-commands)).
pub description_localized: Option<String>,
/// All localized command descriptions.
///
/// If the description is localized, either this field or [`Self::description_localized`] is
/// set, depending on which endpoint this data was retrieved from
/// ([source](https://discord.com/developers/docs/interactions/application-commands#retrieving-localized-commands)).
pub description_localizations: Option<HashMap<String, String>>,
/// The parameters for the command.
#[serde(default)]
pub options: Vec<CommandOption>,
/// The default permissions required to execute the command.
pub default_member_permissions: Option<Permissions>,
/// Indicates whether the command is available in DMs with the app, only for globally-scoped
/// commands. By default, commands are visible.
#[serde(default)]
pub dm_permission: Option<bool>,
/// Indicates whether the command is [age-restricted](https://discord.com/developers/docs/interactions/application-commands#agerestricted-commands),
/// defaults to false.
#[serde(default)]
pub nsfw: bool,
/// An autoincremented version identifier updated during substantial record changes.
pub version: CommandVersionId,
}
#[cfg(feature = "model")]
impl Command {
/// Create a global [`Command`], overriding an existing one with the same name if it exists.
///
/// When a created [`Command`] is used, the [`InteractionCreate`] event will be emitted.
///
/// **Note**: Global commands may take up to an hour to be updated in the user slash commands
/// list. If an outdated command data is sent by a user, discord will consider it as an error
/// and then will instantly update that command.
///
/// As such, it is recommended that guild application commands be used for testing purposes.
///
/// # Examples
///
/// Create a simple ping command:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use std::sync::Arc;
/// #
/// # async fn run() {
/// # let http: Arc<Http> = unimplemented!();
/// use serenity::builder::CreateCommand;
/// use serenity::model::application::Command;
/// use serenity::model::id::ApplicationId;
///
/// let builder = CreateCommand::new("ping").description("A simple ping command");
/// let _ = Command::create_global_command(&http, builder).await;
/// # }
/// ```
///
/// Create a command that echoes what is inserted:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use std::sync::Arc;
/// #
/// # async fn run() {
/// # let http: Arc<Http> = unimplemented!();
/// use serenity::builder::{CreateCommand, CreateCommandOption as CreateOption};
/// use serenity::model::application::{Command, CommandOptionType};
/// use serenity::model::id::ApplicationId;
///
/// let builder =
/// CreateCommand::new("echo").description("Makes the bot send a message").add_option(
/// CreateOption::new(CommandOptionType::String, "message", "The message to send")
/// .required(true),
/// );
/// let _ = Command::create_global_command(&http, builder).await;
/// # }
/// ```
///
/// # Errors
///
/// See [`CreateCommand::execute`] for a list of possible errors.
///
/// [`InteractionCreate`]: crate::client::EventHandler::interaction_create
pub async fn create_global_command(
cache_http: impl CacheHttp,
builder: CreateCommand,
) -> Result<Command> {
builder.execute(cache_http, (None, None)).await
}
/// Override all global application commands.
///
/// # Errors
///
/// Returns the same errors as [`Self::create_global_command`].
pub async fn set_global_commands(
http: impl AsRef<Http>,
commands: Vec<CreateCommand>,
) -> Result<Vec<Command>> {
http.as_ref().create_global_commands(&commands).await
}
/// Edit a global command, given its Id.
///
/// # Errors
///
/// See [`CreateCommand::execute`] for a list of possible errors.
pub async fn edit_global_command(
cache_http: impl CacheHttp,
command_id: CommandId,
builder: CreateCommand,
) -> Result<Command> {
builder.execute(cache_http, (None, Some(command_id))).await
}
/// Gets all global commands.
///
/// # Errors
///
/// If there is an error, it will be either [`Error::Http`] or [`Error::Json`].
pub async fn get_global_commands(http: impl AsRef<Http>) -> Result<Vec<Command>> {
http.as_ref().get_global_commands().await
}
/// Gets all global commands with localizations.
///
/// # Errors
///
/// If there is an error, it will be either [`Error::Http`] or [`Error::Json`].
pub async fn get_global_commands_with_localizations(
http: impl AsRef<Http>,
) -> Result<Vec<Command>> {
http.as_ref().get_global_commands_with_localizations().await
}
/// Gets a global command by its Id.
///
/// # Errors
///
/// If there is an error, it will be either [`Error::Http`] or [`Error::Json`].
pub async fn get_global_command(
http: impl AsRef<Http>,
command_id: CommandId,
) -> Result<Command> {
http.as_ref().get_global_command(command_id).await
}
/// Deletes a global command by its Id.
///
/// # Errors
///
/// If there is an error, it will be either [`Error::Http`] or [`Error::Json`].
pub async fn delete_global_command(
http: impl AsRef<Http>,
command_id: CommandId,
) -> Result<()> {
http.as_ref().delete_global_command(command_id).await
}
}
enum_number! {
/// The type of an application command.
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-types).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[serde(from = "u8", into = "u8")]
#[non_exhaustive]
pub enum CommandType {
ChatInput = 1,
User = 2,
Message = 3,
_ => Unknown(u8),
}
}
/// The parameters for an [`Command`].
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure).
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CommandOption {
/// The option type.
#[serde(rename = "type")]
pub kind: CommandOptionType,
/// The option name.
pub name: String,
/// Localizations of the option name with locale as the key
#[serde(skip_serializing_if = "Option::is_none")]
pub name_localizations: Option<std::collections::HashMap<String, String>>,
/// The option description.
pub description: String,
/// Localizations of the option description with locale as the key
#[serde(skip_serializing_if = "Option::is_none")]
pub description_localizations: Option<std::collections::HashMap<String, String>>,
/// Whether the parameter is optional or required.
#[serde(default)]
pub required: bool,
/// Choices the user can pick from.
///
/// **Note**: Only available for [`String`] and [`Integer`] [`CommandOptionType`].
///
/// [`String`]: CommandOptionType::String
/// [`Integer`]: CommandOptionType::Integer
#[serde(default)]
pub choices: Vec<CommandOptionChoice>,
/// The nested options.
///
/// **Note**: Only available for [`SubCommand`] or [`SubCommandGroup`].
///
/// [`SubCommand`]: CommandOptionType::SubCommand
/// [`SubCommandGroup`]: CommandOptionType::SubCommandGroup
#[serde(default)]
pub options: Vec<CommandOption>,
/// If the option is a [`Channel`], it will only be able to show these types.
///
/// [`Channel`]: CommandOptionType::Channel
#[serde(default)]
pub channel_types: Vec<ChannelType>,
/// Minimum permitted value for Integer or Number options
#[serde(default)]
pub min_value: Option<serde_json::Number>,
/// Maximum permitted value for Integer or Number options
#[serde(default)]
pub max_value: Option<serde_json::Number>,
/// Minimum permitted length for String options
#[serde(default)]
pub min_length: Option<u16>,
/// Maximum permitted length for String options
#[serde(default)]
pub max_length: Option<u16>,
#[serde(default)]
pub autocomplete: bool,
}
enum_number! {
/// The type of an [`CommandOption`].
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[serde(from = "u8", into = "u8")]
#[non_exhaustive]
pub enum CommandOptionType {
SubCommand = 1,
SubCommandGroup = 2,
String = 3,
Integer = 4,
Boolean = 5,
User = 6,
Channel = 7,
Role = 8,
Mentionable = 9,
Number = 10,
Attachment = 11,
_ => Unknown(u8),
}
}
/// The only valid values a user can pick in an [`CommandOption`].
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-choice-structure).
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CommandOptionChoice {
/// The choice name.
pub name: String,
/// Localizations of the choice name, with locale as key
#[serde(skip_serializing_if = "Option::is_none")]
pub name_localizations: Option<std::collections::HashMap<String, String>>,
/// The choice value.
pub value: Value,
}
/// An [`Command`] permission.
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure).
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CommandPermissions {
/// The id of the command.
pub id: CommandId,
/// The id of the application the command belongs to.
pub application_id: ApplicationId,
/// The id of the guild.
pub guild_id: GuildId,
/// The permissions for the command in the guild.
pub permissions: Vec<CommandPermission>,
}
/// The [`CommandPermission`] data.
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permissions-structure).
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CommandPermission {
/// The [`RoleId`] or [`UserId`], depends on `kind` value.
pub id: CommandPermissionId,
/// The type of data this permissions applies to.
#[serde(rename = "type")]
pub kind: CommandPermissionType,
/// Whether or not the provided data can use the command or not.
pub permission: bool,
}
enum_number! {
/// The type of a [`CommandPermission`].
///
/// [Discord docs](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permission-type).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[serde(from = "u8", into = "u8")]
#[non_exhaustive]
pub enum CommandPermissionType {
Role = 1,
User = 2,
Channel = 3,
_ => Unknown(u8),
}
}
impl CommandPermissionId {
/// Converts this [`CommandPermissionId`] to [`UserId`].
#[must_use]
pub fn to_user_id(self) -> UserId {
self.into()
}
/// Converts this [`CommandPermissionId`] to [`RoleId`].
#[must_use]
pub fn to_role_id(self) -> RoleId {
self.into()
}
}
impl From<RoleId> for CommandPermissionId {
fn from(id: RoleId) -> Self {
Self::new(id.get())
}
}
impl From<UserId> for CommandPermissionId {
fn from(id: UserId) -> Self {
Self::new(id.get())
}
}
impl From<CommandPermissionId> for RoleId {
fn from(id: CommandPermissionId) -> Self {
Self::new(id.get())
}
}
impl From<CommandPermissionId> for UserId {
fn from(id: CommandPermissionId) -> Self {
Self::new(id.get())
}
}