Skip to main content

Crate djs_builders

Crate djs_builders 

Source
Expand description

§djs-builders

Validated builders for Discord embeds, application commands, components and modals.

Status: alpha. The embed, command, component (classic and Components V2) and modal builders, benchmarked (results). The API may still change between alpha releases; see the changelog.

discord.js counterpart: @discordjs/builders

§How the builders work

Every builder takes and returns itself, so calls chain; a value that depends on a condition is set by reassigning (builder = builder.field(…)). Setters only store what they are given and never fail. build() checks every Discord limit at the end and returns the finished djs-model type, or the first problem it found as a ValidationError that names the offending part the way Discord does (fields[3].name). build_unchecked() skips the checks, for example when Discord raises a limit before this crate does.

use djs_builders::{EmbedBuilder, ValidationError};

let mut builder = EmbedBuilder::new()
    .title("Leaderboard")
    .color(0xFE_E75C)
    .timestamp_now();
for (rank, (name, points)) in [("Ada", 31), ("Grace", 27)].into_iter().enumerate() {
    builder = builder.inline_field(format!("#{}", rank + 1), format!("{name}: {points}"));
}
let embed = builder.build()?;
assert_eq!(embed.fields.len(), 2);

let error = EmbedBuilder::new().title("🔥".repeat(257)).build().unwrap_err();
assert_eq!(error.to_string(), "title is too long: 257 characters, at most 256 allowed");

Commands are built the same way, with options as values:

use djs_builders::{
    ContextMenuCommandBuilder, SlashCommandBuilder, SlashCommandStringOption,
    SlashCommandSubcommandBuilder,
};

let tag = SlashCommandBuilder::new("tag", "Manages tags")
    .subcommand(
        SlashCommandSubcommandBuilder::new("show", "Shows a tag")
            .option(SlashCommandStringOption::new("name", "The tag").required(true).autocomplete(true)),
    )
    .subcommand(SlashCommandSubcommandBuilder::new("list", "Lists every tag"))
    .build()?;
let report = ContextMenuCommandBuilder::message("Report message").build()?;

A modal is a list of labels around its fields:

use djs_builders::{ModalBuilder, RadioGroupBuilder, TextInputBuilder};

let modal = ModalBuilder::new("feedback", "Your feedback")
    .label("Topic", TextInputBuilder::short("topic").max_length(80))
    .label(
        "Rating",
        RadioGroupBuilder::new("rating").option("Good", "good").option("Bad", "bad"),
    )
    .build()?;
assert_eq!(modal.components.len(), 2);

§What is checked

The rules follow Discord’s documentation and were checked on the live API with a test bot:

  • Text lengths are counted in Unicode code points after removing leading and trailing whitespace, as Discord counts them. An emoji such as 🔥 is one character (discord.js counts two UTF-16 units); a family emoji made of seven code points is seven.
  • URLs must start with an allowed scheme (any letter case): http:// or https:// for links, and also attachment:// for images and icons. The rest of the address is not parsed; Discord rejects a malformed one.
  • Empty texts are allowed, because Discord accepts them, but an embed needs some content (a non-blank title, description, footer or author name, a field, an image or a thumbnail).
  • Command names follow Discord’s pattern: 1-32 lower-case letters or numbers of any script, -, _ and ʼ (an approximation that never rejects a name Discord accepts). Option names are unique per level, required options come first, subcommands do not mix with other options, and a whole command stays within 8000 characters, counting the longest translation of each text.
  • Two things Discord accepts are still rejected because they cannot work: max_value below min_value, and choices together with autocomplete.
  • Components: custom_ids have 1-100 characters counted as given (Discord accepts a whitespace-only one) and are unique in a message; a button needs a label or an emoji; link buttons take http, https or discord URLs; an action row holds 1-5 buttons or one select menu; a select menu offers at least max_values options with unique values. A Components V2 message has at most 40 components, nested ones included, and 4000 characters of text; check a whole message with validate_components. A container holds 1-40 components, a section 1-3 texts and a button or thumbnail, a gallery 1-10 items; file components need attachment://.
  • Modals (from Discord’s documentation — a modal can only be shown in answer to a user): a title of 1-45 characters and 1-5 labels or texts; a label (1-45 characters) holds one field — a text input, a select menu, a file upload, a radio group, a checkbox group or a checkbox — and a select menu in it cannot be disabled. Text inputs take lengths of 0-4000, uploads 0-10 files, radio groups 2-10 options with one default, checkbox groups 1-10 options. The deprecated rows of text inputs are rejected.
  • Limits that span a whole message — at most 10 embeds and 6000 characters across them — are checked by validate_embeds; embed_length measures one embed.

§Builders

BuilderBuildsdiscord.js
EmbedBuilderEmbedEmbedBuilder
EmbedAuthorBuilderEmbedAuthorEmbedAuthorOptions
EmbedFooterBuilderEmbedFooterEmbedFooterOptions
SlashCommandBuilderCreateApplicationCommandSlashCommandBuilder
SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilderCommandOptionthe same names
SlashCommandStringOption, SlashCommandIntegerOption, SlashCommandNumberOption, SlashCommandBooleanOption, SlashCommandUserOption, SlashCommandChannelOption, SlashCommandRoleOption, SlashCommandMentionableOption, SlashCommandAttachmentOptionCommandOptionthe same names
ContextMenuCommandBuilderCreateApplicationCommandContextMenuCommandBuilder
ActionRowBuilderComponentActionRowBuilder
ButtonBuilder, PremiumButtonBuilderComponentButtonBuilder
StringSelectMenuBuilder, StringSelectMenuOptionBuilderComponent, SelectOptionthe same names
UserSelectMenuBuilder, RoleSelectMenuBuilder, MentionableSelectMenuBuilder, ChannelSelectMenuBuilderComponentthe same names
ContainerBuilder, SectionBuilder, SeparatorBuilderComponentthe same names
TextDisplayBuilder, ThumbnailBuilder, FileBuilderComponentthe same names
MediaGalleryBuilder, MediaGalleryItemBuilderComponent, MediaGalleryItemthe same names
ModalBuilderModalCallbackDataModalBuilder
LabelBuilder, TextInputBuilder, FileUploadBuilder, CheckboxBuilderComponentthe same names
RadioGroupBuilder, RadioGroupOptionBuilder, CheckboxGroupBuilder, CheckboxGroupOptionBuilderComponent, GroupOptionthe same names

§Part of djs-rs

djs-builders 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::builders.

§License

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

Structs§

ActionRowBuilder
Builds an action row: a line of up to five buttons, or one select menu.
ButtonBuilder
Builds a button for an action row or a section accessory.
ChannelSelectMenuBuilder
Builds a channel select menu, which Discord fills with the server’s channels, optionally only of some types.
CheckboxBuilder
Builds a checkbox for a modal’s label: a single yes/no choice, never required (use a one-option checkbox group for that).
CheckboxGroupBuilder
Builds a checkbox group for a modal’s label: users check some of 1-10 options.
CheckboxGroupOptionBuilder
Builds an option of a checkbox group with a description or checked by default, for CheckboxGroupBuilder::option_with.
ContainerBuilder
Builds a container: a box around 1-40 components with an optional accent color, like an embed made of components.
ContextMenuCommandBuilder
Builds a context-menu command: an entry in the “Apps” menu of a user or of a message, with a name and no options.
EmbedAuthorBuilder
Builds the author of an embed — a name with an optional link and icon — for EmbedBuilder::author.
EmbedBuilder
Builds an embed — a rich content block for a message, an interaction reply or a webhook — and checks it against Discord’s limits.
EmbedFooterBuilder
Builds the footer of an embed — a text with an optional icon — for EmbedBuilder::footer.
FileBuilder
Builds a file component: a file uploaded with the message, shown as a downloadable box.
FileUploadBuilder
Builds a file upload for a modal’s label: users attach 0-10 files.
LabelBuilder
Builds a label: a title (1-45 characters) and an optional description (at most 100) around one field of a modal.
MediaGalleryBuilder
Builds a media gallery: a grid of 1-10 images and videos.
MediaGalleryItemBuilder
Builds an item of a media gallery with alt text or a spoiler, for MediaGalleryBuilder::item_with.
MentionableSelectMenuBuilder
Builds a mentionable select menu, which Discord fills with the server’s members and roles.
ModalBuilder
Builds a modal: a pop-up form your app shows in answer to an interaction.
PremiumButtonBuilder
Builds a premium button, which lets users buy one of your app’s SKUs; created by ButtonBuilder::premium.
RadioGroupBuilder
Builds a radio group for a modal’s label: users pick exactly one of 2-10 options.
RadioGroupOptionBuilder
Builds an option of a radio group with a description or selected by default, for RadioGroupBuilder::option_with.
RoleSelectMenuBuilder
Builds a role select menu, which Discord fills with the server’s roles.
SectionBuilder
Builds a section: 1-3 text displays next to an accessory — a button or a thumbnail.
SeparatorBuilder
Builds a separator: vertical space between components, with a line by default.
SlashCommandAttachmentOption
Builds an attachment option of a slash command: a file users upload.
SlashCommandBooleanOption
Builds a boolean option of a slash command: true or false.
SlashCommandBuilder
Builds a slash command (CHAT_INPUT): a name users type after /, a description, and options, subcommands or subcommand groups.
SlashCommandChannelOption
Builds a channel option of a slash command: a channel or category, optionally only of some types.
SlashCommandIntegerOption
Builds an integer option of a slash command: a whole number between -(2^53 − 1) and 2^53 − 1, optionally bounded, picked from up to 25 choices, or suggested through autocomplete.
SlashCommandMentionableOption
Builds a mentionable option of a slash command: a user or a role.
SlashCommandNumberOption
Builds a number option of a slash command: a finite double between -2^53 and 2^53, optionally bounded, picked from up to 25 choices, or suggested through autocomplete.
SlashCommandRoleOption
Builds a role option of a slash command.
SlashCommandStringOption
Builds a string option of a slash command: free text, optionally limited in length, picked from up to 25 choices, or suggested by the app through autocomplete (not together with choices, D-196).
SlashCommandSubcommandBuilder
Builds a subcommand of a slash command (/command subcommand), with its own options.
SlashCommandSubcommandGroupBuilder
Builds a group of subcommands of a slash command (/command group subcommand).
SlashCommandUserOption
Builds a user option of a slash command: a user (and their member, in a server).
StringSelectMenuBuilder
Builds a string select menu: a drop-down of up to 25 options you define, sending the chosen values to your app.
StringSelectMenuOptionBuilder
Builds an option of a string select menu with more than a label and a value, for StringSelectMenuBuilder::option_with.
TextDisplayBuilder
Builds a text display: markdown text in a Components V2 message, a container or a section (1-4000 characters, not blank). All text displays of a message share 4000 characters (D-200).
TextInputBuilder
Builds a text input for a modal’s label: one line (short) or several (paragraph).
ThumbnailBuilder
Builds a thumbnail: a small image, the accessory of a section.
UserSelectMenuBuilder
Builds a user select menu, which Discord fills with the server’s members.

Enums§

ComponentsVersion
Which component system a message uses — the IS_COMPONENTS_V2 message flag.
ValidationError
A Discord limit or rule broken by a builder’s content, returned by build() (D-179).

Functions§

embed_length
Returns the number of characters of embed that count toward Discord’s 6000-character limit: its title, description, field names and values, footer text and author name, each measured in Unicode code points after trimming (D-183).
validate_components
Checks the limits that apply to all components of one message together (D-199), and each component itself.
validate_embeds
Checks the limits that apply to all embeds of one message together: at most 10 embeds and at most 6000 characters across them (see embed_length).