Buttons
Answer a button click with ButtonHandler, read the values in its custom id, update the message, and limit who can click and how often.
Discord hands your bot one string when someone clicks, so which button they pressed and what it was pointed at both have to be inside it.
A click arrives as its own interaction carrying that string, the custom id your component minted. ButtonHandler decodes that id and puts the values on this.params.
import {
ButtonHandler,
ButtonRoute,
CustomId
} from '@seedcord/gateway';
// in your project, write this in the component file that builds the button
const AppealId = new CustomId('appeal').snowflake('userId');
@ButtonRoute(AppealId)
export class Appeal extends ButtonHandler<[typeof AppealId]> {
public async execute(): Promise<void> {
const { userId } = this.params;
await this.reply(`Appeal filed for <@${userId}>.`);
}
}Pass @ButtonRoute the CustomId your component used, and list the same one as a tuple in the generic. Passing the decorator one definition and the generic another is a compile error.
A click is an interaction like any other, so every reply method works here.
Gateway only
A gateway ButtonHandler takes a second type argument, discord.js's CacheType, which defaults to 'cached'. That default types this.event.member as a GuildMember, but seedcord doesn't check it at runtime. A button in a DM has no member, so pass CacheType for a handler that can get one. An http ButtonHandler takes only the route tuple.
Rewriting the source message
A reply to a click posts a new message under the old one. The old buttons stay there, so someone can click them again.
this.update() rewrites the message the button came from. It takes the same response shape every reply method takes, so a new components list replaces the old buttons.
const { userId } = this.params;
await this.update({
components: [
new ReviewCard(userId, 'under review').component
]
});
Discord shows "This interaction failed" on a click that nobody answers within three seconds. For a click that changes nothing on the message, this.deferUpdate() answers it and leaves the message unchanged.
Gateway and http differ
update() resolves to a discord.js Message on gateway and an
APIMessage on http.
One handler, several buttons
Approve and reject sit next to each other on the same message, and one handler can serve both. Pass every id to the decorator, list them in the generic, then branch with this.match.
@ButtonRoute<readonly [CustomId<"approve", {
userId: CustomIdField<string>;
}>, CustomId<"reject", {
userId: CustomIdField<string>;
reason: CustomIdField<string>;
}>]>(defs_0: CustomId<"approve", {
userId: CustomIdField<string>;
}>, defs_1: CustomId<"reject", {
userId: CustomIdField<string>;
reason: CustomIdField<string>;
}>): <TCtor>(constructor: AssertComponentRoute<InteractionKind.Button, readonly [CustomId<"approve", {
userId: CustomIdField<string>;
}>, CustomId<...>], TCtor>) => void
ButtonRoute(const ApproveId: CustomId<
"approve",
{
userId: CustomIdField<string>;
}
>
ApproveId, const RejectId: CustomId<
"reject",
{
userId: CustomIdField<string>;
reason: CustomIdField<string>;
}
>
RejectId)
export class class ReviewReview extends class ButtonHandler<
Defs extends readonly AnyCustomId[],
Cache extends CacheType = "cached"
>
ButtonHandler<
[typeof const ApproveId: CustomId<
"approve",
{
userId: CustomIdField<string>;
}
>
ApproveId, typeof const RejectId: CustomId<
"reject",
{
userId: CustomIdField<string>;
reason: CustomIdField<string>;
}
>
RejectId]
> {
public async Review.execute(): Promise<void>execute(): interface Promise<T>Promise<void> {
await this.ComponentHandler<ButtonInteraction<"cached">, [CustomId<"approve", { userId: CustomIdField<string>; }>, CustomId<"reject", { userId: CustomIdField<string>; reason: CustomIdField<...>; }>]>.match<never, {
approve: ({ userId }: {
userId: string;
}) => Promise<SentMessage>;
reject: ({ userId, reason }: {
userId: string;
reason: string;
}) => Promise<SentMessage>;
}>(cases: OnlyCases<{
approve: ({ userId }: {
userId: string;
}) => Promise<SentMessage>;
reject: ({ userId, reason }: {
userId: string;
reason: string;
}) => Promise<SentMessage>;
}, MatchCases<[CustomId<"approve", {
userId: CustomIdField<string>;
}>, CustomId<"reject", {
userId: CustomIdField<string>;
reason: CustomIdField<string>;
}>], never>>): Promise<...>
match({
approve: ({ userId }: {
userId: string;
}) => Promise<SentMessage>
approve: ({ userId: stringuserId }) =>
this.ComponentHandler<ButtonInteraction<"cached">, [CustomId<"approve", { userId: CustomIdField<string>; }>, CustomId<"reject", { userId: CustomIdField<string>; reason: CustomIdField<...>; }>]>.update(response: GatewayReplyResponse | string): Promise<SentMessage>update(`Approved <@${userId: stringuserId}>.`),
reject: ({ userId, reason }: {
userId: string;
reason: string;
}) => Promise<SentMessage>
reject: ({ userId: stringuserId, reason: stringreason }) =>
this.ComponentHandler<ButtonInteraction<"cached">, [CustomId<"approve", { userId: CustomIdField<string>; }>, CustomId<"reject", { userId: CustomIdField<string>; reason: CustomIdField<...>; }>]>.update(response: GatewayReplyResponse | string): Promise<SentMessage>update(`Rejected <@${userId: stringuserId}>. ${reason: stringreason}`)
});
}
}You key each case by its route's prefix, and each one receives that route's own values. reject reads a reason that approve never declared. Both cases pass update a plain string, which seedcord wraps in one text component. Leave a case out and the build stops, since the compiler requires one per registered prefix.
Keep two buttons in one handler when both cases need the same code first, like a check that the clicker is staff. Two buttons that share nothing belong in two handlers, where each file holds only the code its own button runs.
Warning
this.params is never on a handler registered for several routes, since the decoded shape depends on which button someone clicked. this.match is the only read there.
Decoding runs once, before any case, so a wire from an older shape throws before your code executes.
Who can click a button
You posted a ticket with a Close button, and someone else in the channel closed it. seedcord runs your handler for every click, whoever clicked.
If only one person needs the buttons, send them in an ephemeral reply, which nobody else can see. To keep the message public, put that person's id in the custom id and compare it to the clicker.
import {
ButtonHandler,
ButtonRoute,
CustomId
} from '@seedcord/gateway';
const CloseTicketId = new CustomId('close-ticket').snowflake(
'ownerId'
);
@ButtonRoute(CloseTicketId)
export class CloseTicket extends ButtonHandler<
[typeof CloseTicketId]
> {
public async execute(): Promise<void> {
const { ownerId } = this.params;
if (this.user.id !== ownerId) throw new NotYourTicket();
await this.update('Ticket closed.');
}
}NotYourTicket is a Notice, so seedcord sends its refusal to the person who clicked and leaves the message as it was.
Gateway and http differ
this.user is a discord.js
User on gateway and an APIUser on http. Both have id.
When someone clicks twice
Each click runs your handler, so a double click can run it twice at the same moment. That's a problem if the handler gives out a reward or writes to your database.
To stop the second click, call charge on the rate limiter first in execute(), with a window that allows one use.
import {
buildKey,
ButtonHandler,
ButtonRoute,
CustomId
} from '@seedcord/gateway';
import type { RateLimitWindow } from '@seedcord/gateway';
const ClaimRewardId = new CustomId('claim-reward').str('rewardId');
const ONE_CLAIM: RateLimitWindow = { windowMs: 60_000 };
@ButtonRoute(ClaimRewardId)
export class ClaimReward extends ButtonHandler<
[typeof ClaimRewardId]
> {
public async execute(): Promise<void> {
const { rewardId } = this.params;
const key = buildKey('claim-reward', rewardId);
const { limited } = await this.core.rateLimiter.charge(
key,
ONE_CLAIM
);
if (limited) {
await this.deferUpdate();
return;
}
try {
await rewards.give(rewardId, this.user.id);
} catch (error: unknown) {
await this.core.rateLimiter.reset(key);
throw error;
}
await this.update('Claimed.');
}
}charge counts one click at a time, and ONE_CLAIM leaves out limit, which defaults to one use. The second click gets limited as true, and deferUpdate() answers it without changing the message. That click still shows a result, because update() on the first click replaces the button with Claimed. for everyone. buildKey includes rewardId, so claiming one reward doesn't block the next one. If rewards.give throws, reset clears the charge so that the next click can try again.
ONE_CLAIM expires after a minute, so it only stops a double click. To stop a second claim for later, keep a record of who claimed in your database, or in the kv store with a driver.
A Cooldown gate also refuses the second click, but it shows a refusal card and counts every use of the route per person, server, or channel. charge with your own key limits one reward and answers the second click silently.