Skip to content

Commit

Permalink
button handler (#9)
Browse files Browse the repository at this point in the history
Co-authored-by: Szedann <[email protected]>
  • Loading branch information
IThundxr and Szedann authored Sep 17, 2023
1 parent 2a4d89e commit a85eba7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 19 deletions.
24 changes: 19 additions & 5 deletions src/commands/util/verificationEmbed.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ import {
SlashCommandBuilder,
} from 'discord.js';
import { Command } from '../../handlers/command.handler';
import { Button } from '../../handlers/button.handler';
import { string } from 'valibot';

const verifyButtonSchema = string();

const verifyButton = new Button(
'verify',
verifyButtonSchema,
(interaction, data) => {
interaction.reply(data);
}
);

export const verificationEmbedCommand: Command = {
data: new SlashCommandBuilder()
Expand Down Expand Up @@ -40,11 +52,13 @@ export const verificationEmbedCommand: Command = {
})
.setColor(Colors.Green);

const button = new ButtonBuilder()
.setStyle(ButtonStyle.Success)
.setLabel('Verify')
.setCustomId('verify-button')
.setDisabled(disabled);
const button = verifyButton.button(
{
style: ButtonStyle.Success,
label: 'Verify',
},
interaction.user.username
);

const actionRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
button
Expand Down
25 changes: 11 additions & 14 deletions src/handlers/button.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,19 @@ export class Button<ArgsType extends BaseSchema> {
id: string;
args?: ArgsType;
_onPress?: (interaction: ButtonInteraction, args: ArgsType) => unknown;
constructor(id: string) {
this.id = id;
if (buttonMap.has(id)) console.error(`Button ${id} is already defined`);
buttonMap.set(id, this);
}
setArgs(args: ArgsType) {
this.args = args;
return this;
}
onPress(
handler: (
constructor(
id: string,
args: ArgsType,
onPress: (
interaction: ButtonInteraction,
args: Output<ArgsType>
) => unknown
) {
this._onPress = handler;
return this;
this.id = id;
if (buttonMap.has(id)) console.error(`Button ${id} is already defined`);
buttonMap.set(id, this);
this._onPress = onPress;
this.args = args;
}

button(
Expand All @@ -54,7 +50,8 @@ export const buttonHandler: Handler = (client) => {
if (!data.id) return;
if (!buttonMap.has(data.id)) return;
const button = buttonMap.get(data.id);
if (!button?.args) throw error('No args set in button');
if (!button) return;
if (!button.args) throw error('No args set in button');
const parsedArgs = button.args.parse(args);
if (!button._onPress) return;
button._onPress(interaction, parsedArgs);
Expand Down

0 comments on commit a85eba7

Please sign in to comment.