better handling

This commit is contained in:
DjDeveloperr 2021-04-04 13:51:08 +05:30
parent 38c02bb981
commit f7adfd0f7e
2 changed files with 40 additions and 38 deletions

View file

@ -1,7 +1,8 @@
import {
SlashCommandsManager,
SlashClient,
SlashCommandHandlerCallback
SlashCommandHandlerCallback,
SlashCommandHandler
} from './src/interactions/mod.ts'
import { InteractionResponseType, InteractionType } from './src/types/slash.ts'
@ -69,41 +70,10 @@ export function init(options: DeploySlashInitOptions): void {
}
export function handle(
cmd:
| string
| {
name: string
parent?: string
group?: string
guild?: string
},
handler: SlashCommandHandlerCallback
cmd: string | SlashCommandHandler,
handler?: SlashCommandHandlerCallback
): void {
const handle = {
name: typeof cmd === 'string' ? cmd : cmd.name,
handler,
...(typeof cmd === 'string' ? {} : cmd)
}
if (
typeof handle.name === 'string' &&
handle.name.includes(' ') &&
handle.parent === undefined &&
handle.group === undefined
) {
const parts = handle.name.split(/ +/).filter((e) => e !== '')
if (parts.length > 3 || parts.length < 1)
throw new Error('Invalid command name')
const root = parts.shift() as string
const group = parts.length === 2 ? parts.shift() : undefined
const sub = parts.shift()
handle.name = sub ?? root
handle.group = group
handle.parent = sub === undefined ? undefined : root
}
client.handle(handle)
client.handle(cmd, handler)
}
export { commands, client }

View file

@ -112,8 +112,38 @@ export class SlashClient extends HarmonyEventEmitter<SlashClientEvents> {
}
/** Adds a new Slash Command Handler */
handle(handler: SlashCommandHandler): SlashClient {
this.handlers.push(handler)
handle(
cmd: string | SlashCommandHandler,
handler?: SlashCommandHandlerCallback
): SlashClient {
const handle = {
name: typeof cmd === 'string' ? cmd : cmd.name,
...(handler !== undefined ? { handler } : {}),
...(typeof cmd === 'string' ? {} : cmd)
}
if (handle.handler === undefined)
throw new Error('Invalid usage. Handler function not provided')
if (
typeof handle.name === 'string' &&
handle.name.includes(' ') &&
handle.parent === undefined &&
handle.group === undefined
) {
const parts = handle.name.split(/ +/).filter((e) => e !== '')
if (parts.length > 3 || parts.length < 1)
throw new Error('Invalid command name')
const root = parts.shift() as string
const group = parts.length === 2 ? parts.shift() : undefined
const sub = parts.shift()
handle.name = sub ?? root
handle.group = group
handle.parent = sub === undefined ? undefined : root
}
this.handlers.push(handle as any)
return this
}
@ -180,7 +210,9 @@ export class SlashClient extends HarmonyEventEmitter<SlashClientEvents> {
)
return
const cmd = this._getCommand(interaction)
const cmd =
this._getCommand(interaction) ??
this.getHandlers().find((e) => e.name === '*')
if (cmd?.group !== undefined)
interaction.data.options = interaction.data.options[0].options ?? []
if (cmd?.parent !== undefined)