Skip to content
Classcustom-idv0.2.7

CustomId

A typed customId. The single source of truth shared by the component that mints it and the handler that reads it. This gives you typed reads on the .customId field in components. Values are packed into a compact wire string, which fits more of them inside Discord's 100-char limit.

class CustomId<
    Prefix extends string,
    Shape extends CustomIdShape = {}
>
import { ButtonHandler, ButtonRoute, CustomId } from '@seedcord/gateway';

// declare this in the component file that mints the button
export const Approve = new CustomId('approve').snowflake('userId').oneOf('action', ['approve', 'deny']);

\@ButtonRoute(Approve)
export class ApproveButton extends ButtonHandler<[typeof Approve]> {
    public async execute(): Promise<void> {
        const { userId, action } = this.params;
        // userId: string, action: 'approve' | 'deny'

        await this.reply(`${action} for <@${userId}>`);
    }
}
// Using it outside seedcord:
import { ButtonBuilder, Events } from 'discord.js';
import { CustomId } from '@seedcord/custom-id';

// one declaration, imported by both sides
const Approve = new CustomId('approve').snowflake('userId').oneOf('action', ['approve', 'deny']);

// minting, on the button you send
new ButtonBuilder().setCustomId(Approve.encode({ userId: '123', action: 'deny' })).setLabel('Deny');

// reading, wherever your bot receives the click
client.on(Events.InteractionCreate, (interaction) => {
    if (!interaction.isButton()) return;
    if (!Approve.owns(interaction.customId)) return;

    const { userId, action } = Approve.decode(interaction.customId);
    // userId: string, action: 'approve' | 'deny'
});

Member visibility

Filter class members by access level.

constructor

Constructs a new instance of the CustomId class

CustomId(prefix: Prefix, shape?: Shape)

Showing members with Protected visibility and higher.

Prefix

The stable route prefix, e.g. 'approve'.

Prefix extends string

Shape

The accumulated fields, filled in by the chain.

Shape extends CustomIdShape = {}

prefix

The stable route prefix, e.g. 'approve'.

public readonly prefix: Prefix

routeKey

The prefix plus a short hash of the shape, the part of the wire before the colon.

public readonly routeKey: string

shape

The field definitions accumulated by the chain, keyed by name.

public readonly shape: Shape

decode()

Read a wire string back into values.

Throws two different errors. A wire minted before the shape changed throws the stale one. A corrupt wire, or one minted by a different definition, throws the invalid one. Use setCustomIdErrors to customize the two thrown Error classes.

public decode(wire: string): DecodedParams<Shape>
Parameter: wire

The customId string from the interaction.

const Ticket = new CustomId('ticket').snowflake('ownerId').int('page', 1, 50);

const { ownerId, page } = Ticket.decode(interaction.customId);
// ownerId: string, page: number

// a message from an older deploy still carries its old button. catch the throw and answer it
try {
    Ticket.decode(interaction.customId);
} catch {
    await interaction.reply('This button is out of date. Run the command again.');
}

encode()

Mint a wire string from values. Throws if a value is out of its field's range or the wire is over 100 chars.

public encode(values: DecodedParams<Shape>): string
Parameter: values

One value per field, typed by the chain.

const Ticket = new CustomId('ticket').snowflake('ownerId').int('page', 1, 50);

new ButtonBuilder().setCustomId(Ticket.encode({ ownerId: user.id, page: 3 })).setLabel('Next');

// 900 falls outside the declared 1 to 50. this throws at runtime
Ticket.encode({ ownerId: user.id, page: 900 });

int()

Add an integer field with no bounds, for a value up to 2^53.

public int<Name, Nullable>(
    name: Name,
    opts?: FieldOptions<Nullable>
): CustomId<
    Prefix,
    Shape &
        Record<
            Name,
            CustomIdField<Nullish<number, Nullable>>
        >
>
new CustomId('shop').int('amount');

oneOf()

Add a field that is one value from a fixed list, decoded as the literal union. No as const needed.

public oneOf<Name, Choices, Nullable>(
    name: Name,
    choices: Choices,
    opts?: FieldOptions<Nullable>
): CustomId<
    Prefix,
    Shape &
        Record<
            Name,
            CustomIdField<
                Nullish<Choices[number], Nullable>
            >
        >
>
new CustomId('poll').oneOf('choice', ['yes', 'no', 'abstain']);

owns()

True if this wire was minted from this customId's prefix, ignoring the shape hash.

Use it to pick which definition a click belongs to before decoding. decodeFor runs this loop for you across several definitions.

public owns(wire: string): boolean
Parameter: wire

The customId string from the interaction.

// a button from an older deploy still matches here
if (!Approve.owns(interaction.customId)) return;

snowflake()

Add a Discord ID field, decoded as a string (the Snowflake type from discord-api-types).

public snowflake<Name, Nullable>(
    name: Name,
    opts?: FieldOptions<Nullable>
): CustomId<
    Prefix,
    Shape &
        Record<
            Name,
            CustomIdField<Nullish<Snowflake, Nullable>>
        >
>
new CustomId('ban').snowflake('userId');

someOf()

Add a field that holds any subset of a fixed list, decoded as an array of the literal union.

A duplicate collapses into one entry. Decode returns the picks in the order the CustomId declares them. One choice costs one bit on the wire.

public someOf<Name, Choices, Nullable>(
    name: Name,
    choices: Choices,
    opts?: FieldOptions<Nullable>
): CustomId<
    Prefix,
    Shape &
        Record<
            Name,
            CustomIdField<
                Nullish<Choices[number][], Nullable>
            >
        >
>
// a member picks roles in a select menu, and the confirm button carries them
// roles: ('reader' | 'artist' | 'vip')[]
new CustomId('assign').someOf('roles', ['reader', 'artist', 'vip']);

str()

Add a free short text field. Avoid it where possible. It cannot be packed, which makes it the most expensive field on the wire.

public str<Name, Nullable>(
    name: Name,
    opts?: FieldOptions<Nullable>
): CustomId<
    Prefix,
    Shape &
        Record<
            Name,
            CustomIdField<Nullish<string, Nullable>>
        >
>
new CustomId('note').str('message');

uuid()

Add a UUID field, decoded as a lowercase uuid string.

public uuid<Name, Nullable>(
    name: Name,
    opts?: FieldOptions<Nullable>
): CustomId<
    Prefix,
    Shape &
        Record<
            Name,
            CustomIdField<Nullish<string, Nullable>>
        >
>
new CustomId('ticket').uuid('ticketId');