Skip to main content

djs_formatters/
mention.rs

1//! Mentions of users, channels, roles and commands, custom emoji, and guild navigation.
2//!
3//! See Discord's [message formats](https://docs.discord.com/developers/reference#message-formatting-formats).
4
5use core::fmt;
6
7use djs_model::id::{ChannelId, CommandId, EmojiId, RoleId, UserId};
8
9/// Mentions a user: `<@USER_ID>`. Returned by [`user_mention`].
10///
11/// discord.js counterpart: `UserMention`.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13#[must_use = "a formatter does nothing until it is written"]
14pub struct UserMention(UserId);
15
16/// Mentions the user `id`: `<@80351110224678912>`.
17///
18/// Whether the user is notified depends on the message's `allowed_mentions`.
19///
20/// discord.js counterpart: `userMention`.
21///
22/// # Examples
23///
24/// ```
25/// use djs_formatters::user_mention;
26/// use djs_model::id::UserId;
27///
28/// let winner = UserId::new(80_351_110_224_678_912);
29/// assert_eq!(format!("{} won!", user_mention(winner)), "<@80351110224678912> won!");
30/// ```
31pub const fn user_mention(id: UserId) -> UserMention {
32    UserMention(id)
33}
34
35impl fmt::Display for UserMention {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        write!(f, "<@{}>", self.0)
38    }
39}
40
41/// Mentions a channel: `<#CHANNEL_ID>`. Returned by [`channel_mention`].
42///
43/// discord.js counterpart: `ChannelMention`.
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
45#[must_use = "a formatter does nothing until it is written"]
46pub struct ChannelMention(ChannelId);
47
48/// Mentions the channel `id` as a clickable link: `<#103735883630395392>`.
49///
50/// discord.js counterpart: `channelMention`.
51///
52/// # Examples
53///
54/// ```
55/// use djs_formatters::channel_mention;
56/// use djs_model::id::ChannelId;
57///
58/// let rules = ChannelId::new(103_735_883_630_395_392);
59/// assert_eq!(channel_mention(rules).to_string(), "<#103735883630395392>");
60/// ```
61pub const fn channel_mention(id: ChannelId) -> ChannelMention {
62    ChannelMention(id)
63}
64
65impl fmt::Display for ChannelMention {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "<#{}>", self.0)
68    }
69}
70
71/// Mentions a role: `<@&ROLE_ID>`. Returned by [`role_mention`].
72///
73/// discord.js counterpart: `RoleMention`.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
75#[must_use = "a formatter does nothing until it is written"]
76pub struct RoleMention(RoleId);
77
78/// Mentions the role `id`: `<@&165511591545143296>`.
79///
80/// Whether the role's members are notified depends on the message's `allowed_mentions` and
81/// the role's settings.
82///
83/// discord.js counterpart: `roleMention`.
84///
85/// # Examples
86///
87/// ```
88/// use djs_formatters::role_mention;
89/// use djs_model::id::RoleId;
90///
91/// assert_eq!(role_mention(RoleId::new(165_511_591_545_143_296)).to_string(), "<@&165511591545143296>");
92/// ```
93pub const fn role_mention(id: RoleId) -> RoleMention {
94    RoleMention(id)
95}
96
97impl fmt::Display for RoleMention {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        write!(f, "<@&{}>", self.0)
100    }
101}
102
103/// Links to a linked role: `<id:linked-roles:ROLE_ID>`. Returned by [`linked_role_mention`].
104///
105/// discord.js counterpart: the string `linkedRoleMention` returns (`@discordjs/formatters`).
106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
107#[must_use = "a formatter does nothing until it is written"]
108pub struct LinkedRoleMention(RoleId);
109
110/// Links to the [linked role](https://support.discord.com/hc/en-us/articles/10388356626711)
111/// `id`; clicking it opens the connection dialog: `<id:linked-roles:165511591545143296>`.
112///
113/// discord.js counterpart: `linkedRoleMention`.
114///
115/// # Examples
116///
117/// ```
118/// use djs_formatters::linked_role_mention;
119/// use djs_model::id::RoleId;
120///
121/// assert_eq!(
122///     linked_role_mention(RoleId::new(165_511_591_545_143_296)).to_string(),
123///     "<id:linked-roles:165511591545143296>"
124/// );
125/// ```
126pub const fn linked_role_mention(id: RoleId) -> LinkedRoleMention {
127    LinkedRoleMention(id)
128}
129
130impl fmt::Display for LinkedRoleMention {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        write!(f, "<id:linked-roles:{}>", self.0)
133    }
134}
135
136/// Mentions a slash command, a clickable link that fills in the command:
137/// `</NAME:ID>`, `</NAME SUBCOMMAND:ID>` or `</NAME GROUP SUBCOMMAND:ID>`. Returned by
138/// [`slash_command_mention`].
139///
140/// discord.js counterpart: the string `chatInputApplicationCommandMention` returns (`@discordjs/formatters`).
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
142#[must_use = "a formatter does nothing until it is written"]
143pub struct SlashCommandMention<'a> {
144    name: &'a str,
145    group: Option<&'a str>,
146    subcommand: Option<&'a str>,
147    id: CommandId,
148}
149
150/// Mentions the slash command `name` with the ID `id`: `</airhorn:816437322781949972>`.
151///
152/// A subcommand is added with [`subcommand`](SlashCommandMention::subcommand), a subcommand
153/// in a group with [`group`](SlashCommandMention::group) (D-213).
154///
155/// discord.js counterpart: `chatInputApplicationCommandMention`.
156///
157/// # Examples
158///
159/// ```
160/// use djs_formatters::slash_command_mention;
161/// use djs_model::id::CommandId;
162///
163/// let id = CommandId::new(123_456_789_012_345_678);
164/// assert_eq!(slash_command_mention("ping", id).to_string(), "</ping:123456789012345678>");
165/// assert_eq!(
166///     slash_command_mention("tag", id).subcommand("show").to_string(),
167///     "</tag show:123456789012345678>"
168/// );
169/// assert_eq!(
170///     slash_command_mention("admin", id).group("users", "ban").to_string(),
171///     "</admin users ban:123456789012345678>"
172/// );
173/// ```
174pub const fn slash_command_mention(name: &str, id: CommandId) -> SlashCommandMention<'_> {
175    SlashCommandMention {
176        name,
177        group: None,
178        subcommand: None,
179        id,
180    }
181}
182
183impl<'a> SlashCommandMention<'a> {
184    /// Mentions the command's subcommand `subcommand`, outside a group.
185    ///
186    /// discord.js counterpart: the `subcommandName` argument of `chatInputApplicationCommandMention` (`@discordjs/formatters`).
187    pub const fn subcommand(mut self, subcommand: &'a str) -> Self {
188        self.group = None;
189        self.subcommand = Some(subcommand);
190        self
191    }
192
193    /// Mentions the subcommand `subcommand` of the command's group `group`.
194    ///
195    /// discord.js counterpart: the `subcommandGroupName` argument of `chatInputApplicationCommandMention` (`@discordjs/formatters`).
196    pub const fn group(mut self, group: &'a str, subcommand: &'a str) -> Self {
197        self.group = Some(group);
198        self.subcommand = Some(subcommand);
199        self
200    }
201}
202
203impl fmt::Display for SlashCommandMention<'_> {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.write_str("</")?;
206        f.write_str(self.name)?;
207        for part in [self.group, self.subcommand].into_iter().flatten() {
208            f.write_str(" ")?;
209            f.write_str(part)?;
210        }
211        write!(f, ":{}>", self.id)
212    }
213}
214
215/// Shows a custom emoji: `<:NAME:ID>` or, animated, `<a:NAME:ID>`. Returned by [`emoji`].
216///
217/// discord.js counterpart: the string `formatEmoji` returns (`@discordjs/formatters`).
218#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219#[must_use = "a formatter does nothing until it is written"]
220pub struct Emoji<'a> {
221    id: EmojiId,
222    name: Option<&'a str>,
223    animated: bool,
224}
225
226/// Shows the custom emoji `id`: `<:emoji:216154654256398347>`.
227///
228/// Discord finds the emoji by its ID; the name only matters where the emoji cannot be shown,
229/// so it defaults to `emoji`. Set it with [`name`](Emoji::name); an animated emoji needs
230/// [`animated`](Emoji::animated) (D-213). A Unicode emoji is written as itself (`🪴`).
231///
232/// discord.js counterpart: `formatEmoji`.
233///
234/// # Examples
235///
236/// ```
237/// use djs_formatters::emoji;
238/// use djs_model::id::EmojiId;
239///
240/// let id = EmojiId::new(392_938_283_556_143_104);
241/// assert_eq!(emoji(id).to_string(), "<:emoji:392938283556143104>");
242/// assert_eq!(emoji(id).name("b1nzy").animated(true).to_string(), "<a:b1nzy:392938283556143104>");
243/// ```
244pub const fn emoji<'a>(id: EmojiId) -> Emoji<'a> {
245    Emoji {
246        id,
247        name: None,
248        animated: false,
249    }
250}
251
252impl<'a> Emoji<'a> {
253    /// Sets the emoji's name (default: `emoji`).
254    ///
255    /// discord.js counterpart: the `name` of `FormatEmojiOptions` (`@discordjs/formatters`).
256    pub const fn name(mut self, name: &'a str) -> Self {
257        self.name = Some(name);
258        self
259    }
260
261    /// Sets whether the emoji is animated (default: no).
262    ///
263    /// discord.js counterpart: the `animated` of `FormatEmojiOptions` (`@discordjs/formatters`).
264    pub const fn animated(mut self, animated: bool) -> Self {
265        self.animated = animated;
266        self
267    }
268}
269
270impl fmt::Display for Emoji<'_> {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        let prefix = if self.animated { "<a:" } else { "<:" };
273        write!(f, "{prefix}{}:{}>", self.name.unwrap_or("emoji"), self.id)
274    }
275}
276
277/// A [guild navigation](https://docs.discord.com/developers/reference#message-formatting-guild-navigation-types)
278/// link, opening a tab of the current server.
279///
280/// discord.js counterpart: `GuildNavigationMentions`.
281///
282/// # Examples
283///
284/// ```
285/// use djs_formatters::GuildNavigation;
286///
287/// assert_eq!(format!("Pick your roles in {}", GuildNavigation::Customize), "Pick your roles in <id:customize>");
288/// ```
289#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
290#[non_exhaustive]
291pub enum GuildNavigation {
292    /// The Browse Channels tab: `<id:browse>`.
293    Browse,
294    /// The Channels & Roles tab with the onboarding prompts: `<id:customize>`.
295    Customize,
296    /// The Server Guide tab: `<id:guide>`.
297    Guide,
298    /// The Linked Roles tab: `<id:linked-roles>`. One linked role is linked with
299    /// [`linked_role_mention`].
300    LinkedRoles,
301}
302
303impl GuildNavigation {
304    /// The link as written in a message, such as `<id:browse>`.
305    ///
306    /// discord.js counterpart: the values of `GuildNavigationMentions` (`@discordjs/formatters`).
307    #[must_use]
308    pub const fn as_str(self) -> &'static str {
309        match self {
310            Self::Browse => "<id:browse>",
311            Self::Customize => "<id:customize>",
312            Self::Guide => "<id:guide>",
313            Self::LinkedRoles => "<id:linked-roles>",
314        }
315    }
316}
317
318impl fmt::Display for GuildNavigation {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        f.write_str(self.as_str())
321    }
322}