Skip to content

Commit

Permalink
rethinked the button handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Szedann committed Dec 28, 2023
1 parent b637b29 commit 3c6d792
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
24 changes: 11 additions & 13 deletions src/handlers/button.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,32 @@ import {
ButtonBuilder,
ButtonInteraction,
Events,
Interaction,
InteractionButtonComponentData,
} from 'discord.js';
import { Handler } from '..';
import { BaseSchema, Output } from 'valibot';
import { error } from 'console';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buttonMap = new Map<string, Button<any>>();

Check failure on line 10 in src/handlers/button.handler.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

export class Button<ArgsType extends BaseSchema> {
export class Button<ArgsType> {
id: string;
args?: ArgsType;
_onPress?: (interaction: ButtonInteraction, args: ArgsType) => unknown;
constructor(
id: string,
args: ArgsType,
onPress: (
interaction: ButtonInteraction,
args: Output<ArgsType>
args: ArgsType
) => unknown
) {
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(
data: Partial<InteractionButtonComponentData>,
args: Output<ArgsType>
args: ArgsType
): ButtonBuilder {
const button = new ButtonBuilder({
...data,
Expand All @@ -43,17 +38,20 @@ export class Button<ArgsType extends BaseSchema> {
}

export const buttonHandler: Handler = (client) => {
client.on(Events.InteractionCreate, async (interaction) => {
client.on(Events.InteractionCreate, async (interaction:Interaction) => {
if (!interaction.isButton()) return;
const data = JSON.parse(interaction.customId);
const args = data.args;
if (!data.id) return;
if (!buttonMap.has(data.id)) return;
const button = buttonMap.get(data.id);
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);
try{
button._onPress(interaction, args);
}catch{
interaction.reply("error while executing")
}
});
};
4 changes: 1 addition & 3 deletions src/webserver/banshare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@ import {
TextInputBuilder,
} from 'discord.js';
import { Button } from '../handlers/button.handler';
import { string, object } from 'valibot';

const banButton = new Button(
'ban',
object({ userId: string() }),
async (interaction, data) => {
async (interaction, data:{userId:string}) => {
const reason =
'aero banshare: ' +
(interaction.message.embeds[0].fields[3].value ??
Expand Down

0 comments on commit 3c6d792

Please sign in to comment.