djs_builders/command/context_menu.rs
1//! [`ContextMenuCommandBuilder`].
2
3use compact_str::CompactString;
4use djs_model::rest::CreateApplicationCommand;
5
6use super::validate;
7use crate::ValidationError;
8
9/// Builds a [context-menu command](https://docs.discord.com/developers/interactions/application-commands#user-commands):
10/// an entry in the "Apps" menu of a user or of a message, with a name and no options.
11///
12/// The name can have 1-32 characters of any kind — upper-case letters, spaces and emoji
13/// are fine (D-195). Register the result like a slash command.
14///
15/// discord.js counterpart: `ContextMenuCommandBuilder` (the type is chosen by the constructor
16/// instead of `setType`).
17///
18/// # Examples
19///
20/// ```
21/// use djs_builders::ContextMenuCommandBuilder;
22/// use djs_model::{application_command::CommandType, util::Locale};
23///
24/// let report = ContextMenuCommandBuilder::message("Report message")
25/// .name_localization(Locale::Polish, "Zgłoś wiadomość")
26/// .build()
27/// .unwrap();
28/// assert_eq!(report.kind, Some(CommandType::Message));
29/// assert_eq!(report.description, None);
30///
31/// let profile = ContextMenuCommandBuilder::user("Show profile").build().unwrap();
32/// assert_eq!(profile.kind, Some(CommandType::User));
33/// ```
34#[derive(Clone, Debug, PartialEq)]
35#[must_use = "a builder does nothing until `build` is called"]
36pub struct ContextMenuCommandBuilder {
37 command: CreateApplicationCommand,
38}
39
40impl ContextMenuCommandBuilder {
41 /// Creates a command in the context menu of users, named `name` (1-32 characters).
42 ///
43 /// discord.js counterpart: `setType(ApplicationCommandType.User)`.
44 pub fn user(name: impl Into<CompactString>) -> Self {
45 Self {
46 command: CreateApplicationCommand::user(name),
47 }
48 }
49
50 /// Creates a command in the context menu of messages, named `name` (1-32 characters).
51 ///
52 /// discord.js counterpart: `setType(ApplicationCommandType.Message)`.
53 pub fn message(name: impl Into<CompactString>) -> Self {
54 Self {
55 command: CreateApplicationCommand::message(name),
56 }
57 }
58
59 name_localizations!(command);
60 command_settings!();
61
62 /// Checks the name and its translations (1-32 characters, not blank) and returns the
63 /// command.
64 ///
65 /// discord.js counterpart: `ContextMenuCommandBuilder#toJSON`.
66 ///
67 /// # Errors
68 ///
69 /// [`ValidationError::Missing`] for a blank name, [`ValidationError::TooLong`] for one
70 /// above 32 characters.
71 pub fn build(self) -> Result<CreateApplicationCommand, ValidationError> {
72 validate::context_menu_command(&self.command)?;
73 Ok(self.command)
74 }
75
76 /// Returns the command without any check (D-180).
77 ///
78 /// discord.js counterpart: `ContextMenuCommandBuilder#toJSON` with validation off (`disableValidators`).
79 #[must_use]
80 pub fn build_unchecked(self) -> CreateApplicationCommand {
81 self.command
82 }
83}