The utilities module provides helper functions, validation tools, and type definitions for working with Discord components and data structures.
Calculate the total character length of an embed across all text fields.
function embedLength(data: APIEmbed): number;Parameters:
data - The embed data to calculate length forReturns: Total character count including title, description, fields, footer, and author text
Usage:
import { EmbedBuilder, embedLength } from "@discordjs/builders";
const embed = new EmbedBuilder()
.setTitle('Sample Embed')
.setDescription('This is a sample embed')
.addFields({ name: 'Field 1', value: 'Value 1' });
const length = embedLength(embed.toJSON());
console.log(`Embed length: ${length} characters`); // Output: Embed length: 52 charactersCreate appropriate component builder from Discord API component data.
function createComponentBuilder(data: APIMessageComponent | APIModalComponent): AnyComponentBuilder;Parameters:
data - API component data to convert to builderReturns: Appropriate component builder instance
Usage:
import { createComponentBuilder } from "@discordjs/builders";
const apiButtonData = {
type: 2, // ComponentType.Button
style: 1, // ButtonStyle.Primary
label: 'Click me!',
custom_id: 'my_button'
};
const buttonBuilder = createComponentBuilder(apiButtonData);
// Returns ButtonBuilder instanceConvert rest parameters or arrays into a flat array format.
function normalizeArray<T>(arr: RestOrArray<T>): T[];Parameters:
arr - Rest parameters or array to normalizeReturns: Flat array of elements
Usage:
import { normalizeArray } from "@discordjs/builders";
// With array
const array = normalizeArray(['a', 'b', 'c']);
console.log(array); // ['a', 'b', 'c']
// With rest parameters (internally used)
function addItems(...items: string[]) {
const normalized = normalizeArray(items);
return normalized;
}Check if component validation is currently enabled.
function isValidationEnabled(): boolean;Returns: true if validation is enabled, false otherwise
Globally disable all component validation.
function disableValidators(): void;Usage:
import { disableValidators, isValidationEnabled } from "@discordjs/builders";
console.log(isValidationEnabled()); // true (default)
disableValidators();
console.log(isValidationEnabled()); // false
// Validation is now disabled for all buildersGlobally enable all component validation.
function enableValidators(): void;Usage:
import { enableValidators, isValidationEnabled } from "@discordjs/builders";
enableValidators();
console.log(isValidationEnabled()); // true
// Validation is now enabled for all buildersType for parameters that can accept either rest parameters or an array.
type RestOrArray<T> = T[] | readonly T[];Type representing RGB color values as a tuple.
type RGBTuple = [red: number, green: number, blue: number];Usage:
import { EmbedBuilder, type RGBTuple } from "@discordjs/builders";
const redColor: RGBTuple = [255, 0, 0];
const embed = new EmbedBuilder()
.setColor(redColor);Base interface for icon-related data structures.
interface IconData {
iconURL?: string;
proxyIconURL?: string;
}type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;
type MessageActionRowComponentBuilder =
| ButtonBuilder
| ChannelSelectMenuBuilder
| MentionableSelectMenuBuilder
| RoleSelectMenuBuilder
| StringSelectMenuBuilder
| UserSelectMenuBuilder;
type ModalActionRowComponentBuilder = TextInputBuilder;
type MessageComponentBuilder =
| ActionRowBuilder<MessageActionRowComponentBuilder>
| MessageActionRowComponentBuilder;
type ModalComponentBuilder =
| ActionRowBuilder<ModalActionRowComponentBuilder>
| ModalActionRowComponentBuilder;Discord's unique identifier type.
type Snowflake = string;The library re-exports all utilities from @discordjs/formatters for convenience:
// All exports from @discordjs/formatters are available
import {
bold,
italic,
strikethrough,
underscore,
spoiler,
quote,
blockQuote,
inlineCode,
codeBlock,
time,
TimestampStyles,
userMention,
channelMention,
roleMention
} from "@discordjs/builders";The current version of the @discordjs/builders package.
const version: string;Usage:
import { version } from "@discordjs/builders";
console.log(`Using @discordjs/builders version ${version}`);Various assertion modules are exported as namespaces for validation functions:
namespace EmbedAssertions {
function colorPredicate(value: unknown): boolean;
function descriptionPredicate(value: unknown): boolean;
function titlePredicate(value: unknown): boolean;
// ... other embed validation functions
}namespace ComponentAssertions {
function customIdValidator(value: unknown): string;
function disabledValidator(value: unknown): boolean;
function labelValidator(value: unknown): string;
// ... other component validation functions
}namespace TextInputAssertions {
function labelValidator(value: unknown): string;
function maxLengthValidator(value: unknown): number;
function minLengthValidator(value: unknown): number;
// ... other text input validation functions
}namespace SlashCommandAssertions {
function validateName(value: unknown): string;
function validateDescription(value: unknown): string;
function validateLocale(value: unknown): string;
// ... other slash command validation functions
}namespace ContextMenuCommandAssertions {
function validateName(value: unknown): string;
function validateType(value: unknown): ContextMenuCommandType;
function validateDefaultMemberPermissions(value: unknown): Permissions | null;
// ... other context menu command validation functions
}namespace ModalAssertions {
function titleValidator(value: unknown): string;
function validateRequiredParameters(value: unknown): void;
// ... other modal validation functions
}namespace ComponentsV2Assertions {
// Validation functions for v2 preview components
function validateContainerData(value: unknown): boolean;
function validateFileData(value: unknown): boolean;
// ... other v2 component validation functions
}import { disableValidators, enableValidators, SlashCommandBuilder } from "@discordjs/builders";
// Disable validation for bulk operations
disableValidators();
const commands = [];
for (let i = 0; i < 1000; i++) {
commands.push(
new SlashCommandBuilder()
.setName(`command${i}`)
.setDescription(`Command number ${i}`)
);
}
// Re-enable validation
enableValidators();import { EmbedBuilder, embedLength } from "@discordjs/builders";
function createSafeEmbed(title: string, description: string): EmbedBuilder {
const embed = new EmbedBuilder()
.setTitle(title)
.setDescription(description);
// Check if embed exceeds Discord's limit
if (embedLength(embed.toJSON()) > 6000) {
throw new Error('Embed exceeds Discord\'s character limit');
}
return embed;
}import { createComponentBuilder } from "@discordjs/builders";
function createComponentsFromAPI(apiData: any[]) {
return apiData.map(componentData =>
createComponentBuilder(componentData)
);
}