Skip to main content

Crate djs_formatters

Crate djs_formatters 

Source
Expand description

§djs-formatters

Markdown, mention and timestamp formatting helpers for Discord messages.

Status: alpha. Every formatter and escaper of @discordjs/formatters. The API may still change between alpha releases; see the changelog.

discord.js counterpart: @discordjs/formatters

§How the formatters work

Each formatter returns a small value that implements Display, so nothing is allocated until it is written: put it in format! or write!, or call .to_string(). Formatters take any Display content, so they nest (bold(italic("x")) is **_x_**), and mentions take the typed IDs of djs-model. Optional parts are methods on the returned value.

use djs_formatters::{TimestampStyle, bold, code_block, slash_command_mention, time, user_mention};
use djs_model::id::{CommandId, UserId};

let winner = UserId::new(80_351_110_224_678_912);
let text = format!(
    "{} {} won {}!",
    bold("Giveaway:"),
    user_mention(winner),
    time(1_618_953_630).style(TimestampStyle::RelativeTime),
);
assert_eq!(text, "**Giveaway:** <@80351110224678912> won <t:1618953630:R>!");

let help = slash_command_mention("tag", CommandId::new(1)).subcommand("show");
assert_eq!(help.to_string(), "</tag show:1>");
assert_eq!(code_block("fn main() {}").language("rust").to_string(), "```rust\nfn main() {}\n```");

Formatters do not escape their content. Text from users goes through escape_markdown first, which returns a Cow<str> and borrows the text when there is nothing to escape:

use djs_formatters::{EscapeOptions, bold, escape_markdown};

let name = "**not bold**";
assert_eq!(bold(escape_markdown(name)).to_string(), r"**\*\*not bold\*\***");

// Links and mentions are left alone, so they keep working.
assert_eq!(escape_markdown("https://x.dev/a_b <@1>"), "https://x.dev/a_b <@1>");

// discord.js' options, with its defaults.
let strict = EscapeOptions::new().heading(true).bulleted_list(true);
assert_eq!(strict.escape("# Title\n- item"), "\\# Title\n\\- item");

§Formatters

FormatterOutputdiscord.js
user_mention, channel_mention, role_mention<@id>, <#id>, <@&id>userMention, channelMention, roleMention
linked_role_mention, GuildNavigation<id:linked-roles:id>, <id:browse>, …linkedRoleMention, GuildNavigationMentions
slash_command_mention .subcommand(…) / .group(…, …)</name sub:id>chatInputApplicationCommandMention
emoji .name(…) .animated(…)<a:name:id>formatEmoji
time .style(…), TimestampStyle<t:seconds:R>time, TimestampStyles
bold, italic, underline, strikethrough, spoiler**x**, _x_, __x__, ~~x~~, ||x||the same names
inline_code, code_block .language(…)`x`, ```langinlineCode, codeBlock
quote, block_quote, subtext, heading .level(…)> x, >>> x, -# x, ## xthe same names
unordered_list, ordered_list .start(…), ListItem- x, 1. x, nestedunorderedList, orderedList
hyperlink .title(…), hide_link_embed[x](url "title"), <url>hyperlink, hideLinkEmbed
channel_link, message_link .guild(…)https://discord.com/channels/…channelLink, messageLink
application_directory .sku(…)https://discord.com/application-directory/…applicationDirectory
email .headers(…), phone_number<a@b.c?subject=…>, <+1…>email, phoneNumber
Face¯\_(ツ)_/¯, …Faces
escape_markdown, EscapeOptions, escape_bold, escape_italic, …escapeMarkdown, escapeBold, …

§Escaping rules

The same options and defaults as discord.js, and the same result for ordinary text. Links (http://, https://) and <…> tokens (mentions, emoji, timestamps, e-mail and phone links) are copied as they are, so escaping never breaks them. In unusual input the rules differ on purpose; see EscapeOptions for the full list.

§Part of djs-rs

djs-formatters is one crate of djs-rs, a high-performance Rust library for building Discord bots modelled on discord.js v14. It can be used on its own or through the main djs-rs crate, as djs_rs::formatters.

§License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Structs§

ApplicationDirectory
A link to an app’s store page in the App Directory, or to one of its SKUs. Returned by application_directory.
BlockQuote
Content written as >>> …. Returned by block_quote.
Bold
Content written as **…**. Returned by bold.
ChannelLink
A link to a channel: https://discord.com/channels/GUILD_ID/CHANNEL_ID, or @me in place of the server for a DM. Returned by channel_link.
ChannelMention
Mentions a channel: <#CHANNEL_ID>. Returned by channel_mention.
CodeBlock
A code block: ```language\ncontent\n```. Returned by code_block.
Email
An e-mail link: <address> or <address?header=value&…>. Returned by email.
Emoji
Shows a custom emoji: <:NAME:ID> or, animated, <a:NAME:ID>. Returned by emoji.
EscapeOptions
Which kinds of markdown escape neutralizes.
Heading
A heading: # content, ## content or ### content. Returned by heading.
HideLinkEmbed
Content written as <…>. Returned by hide_link_embed.
Hyperlink
A masked link: [content](url) or [content](url "title"). Returned by hyperlink.
InlineCode
Content written as …. Returned by inline_code.
Italic
Content written as _…_. Returned by italic.
LinkedRoleMention
Links to a linked role: <id:linked-roles:ROLE_ID>. Returned by linked_role_mention.
MessageLink
A link to a message: https://discord.com/channels/GUILD_ID/CHANNEL_ID/MESSAGE_ID. Returned by message_link.
OrderedList
A numbered list: 1. item, 2. item, … Returned by ordered_list.
PhoneNumber
A phone link: <+number>. Returned by phone_number.
Quote
Content written as > …. Returned by quote.
RoleMention
Mentions a role: <@&ROLE_ID>. Returned by role_mention.
SlashCommandMention
Mentions a slash command, a clickable link that fills in the command: </NAME:ID>, </NAME SUBCOMMAND:ID> or </NAME GROUP SUBCOMMAND:ID>. Returned by slash_command_mention.
Spoiler
Content written as ||…||. Returned by spoiler.
Strikethrough
Content written as ~~…~~. Returned by strikethrough.
Subtext
Content written as -# …. Returned by subtext.
Time
A timestamp: <t:SECONDS> or <t:SECONDS:STYLE>. Returned by time.
Underline
Content written as __…__. Returned by underline.
UnorderedList
A bulleted list: one - item per line. Returned by unordered_list.
UserMention
Mentions a user: <@USER_ID>. Returned by user_mention.

Enums§

Face
A text face Discord offers as a slash command, ready to send.
GuildNavigation
A guild navigation link, opening a tab of the current server.
HeadingLevel
The size of a heading.
ListItem
An item of a list: a line of text, or a nested list indented under the line before it.
TimestampStyle
How Discord shows a time; the examples are for 20 April 2021, 16:20:30, in an English client.

Traits§

ListEntry
What a list can hold: any Display value, or a ListItem.
UnixSeconds
A point in time that time can show: seconds since the Unix epoch.

Functions§

application_directory
Links to the App Directory store page of the app application (https://discord.com/application-directory/ID/store), or of one of its SKUs with sku (D-213). Discord shows the link as a card.
block_quote
Quotes content and everything after it in the message: >>> content.
bold
Shows content in bold: **content**.
channel_link
Links to the channel channel, a DM unless the guild is set (D-213).
channel_mention
Mentions the channel id as a clickable link: <#103735883630395392>.
code_block
Shows content as a block of code, highlighted for a language such as rust if set (D-213).
email
Links to the e-mail address address; clicking it opens a new e-mail, with the headers (such as subject) filled in if set (D-213).
emoji
Shows the custom emoji id: <:emoji:216154654256398347>.
escape_bold
Escapes only ** in text (EscapeOptions::bold).
escape_bulleted_list
Escapes only bullets at the start of a line in text (EscapeOptions::bulleted_list).
escape_code_block
Escapes only runs of three or more backticks in text (EscapeOptions::code_block).
escape_escape
Escapes only backslashes in text (EscapeOptions::backslash).
escape_heading
Escapes only headings at the start of a line in text (EscapeOptions::heading).
escape_inline_code
Escapes only runs of one or two backticks in text (EscapeOptions::inline_code).
escape_italic
Escapes only a single * or _ in text (EscapeOptions::italic).
escape_markdown
Escapes text with discord.js’ defaults (EscapeOptions::new): emphasis, code, strikethrough, spoilers and backslashes, outside links and mentions.
escape_masked_link
Escapes only masked links in text (EscapeOptions::masked_link).
escape_numbered_list
Escapes only numbered list items at the start of a line in text (EscapeOptions::numbered_list).
escape_spoiler
Escapes only || in text (EscapeOptions::spoiler).
escape_strikethrough
Escapes only ~~ in text (EscapeOptions::strikethrough).
escape_underline
Escapes only __ in text (EscapeOptions::underline).
heading
Shows content as a heading, the largest unless a smaller level is set (D-213).
hide_link_embed
Links to url without an embed preview: <url>.
hyperlink
Shows content as a link to url, with a title shown on hover if set (D-213).
inline_code
Shows content as code on one line: `content`.
italic
Shows content in italics: _content_.
linked_role_mention
Links to the linked role id; clicking it opens the connection dialog: <id:linked-roles:165511591545143296>.
message_link
Links to the message message of the channel channel, a DM unless the guild is set (D-213).
ordered_list
Shows items as a numbered list from 1, or from start (D-213); nested lists count from 1.
phone_number
Links to the phone number number, which must be international (start with +); None otherwise (discord.js throws an error).
quote
Quotes one line: > content.
role_mention
Mentions the role id: <@&165511591545143296>.
slash_command_mention
Mentions the slash command name with the ID id: </airhorn:816437322781949972>.
spoiler
Hides content until it is clicked: ||content||.
strikethrough
Strikes content through: ~~content~~.
subtext
Shows content small and grey, as a line of subtext: -# content.
time
Shows at in each reader’s time zone and language: <t:1618953630>.
underline
Underlines content: __content__.
unordered_list
Shows items as a bulleted list, one per line; ListItem::Nested indents a list under the line before it (two spaces per level).
user_mention
Mentions the user id: <@80351110224678912>.