WE ARE COOKING (slash commands with some arg validation proto working)

This commit is contained in:
2024-11-16 17:07:31 -06:00
parent 7848ea0082
commit fbdff25c14
9 changed files with 302 additions and 102 deletions
+21 -12
View File
@@ -3,12 +3,12 @@ import { Gateway } from './connectors/gateway';
import { Processor } from './processor';
import { Expectation, fromDiscord, Intent, type ClientConfig } from '../types/common';
import { exists, isNil } from '../utils/index';
import type { Handler } from '../types/handler';
import { type DiscordMessage, Message } from '../types/message';
import { Guilds } from './caches/guilds';
import { Messages } from './caches/messages';
import { Users } from './caches/users';
import { hydrate, hydrator, type Hydrateable, type Hydrated } from './hydrator';
import type { User } from '../types/user';
export class Client {
readonly token: string;
@@ -21,7 +21,9 @@ export class Client {
protected gateway: Gateway;
guilds: Guilds;
users: Users;
messages: Messages
messages: Messages;
chatCommands: Processor['chat_commands'];
applicationCommands: Processor['application_commands'];
constructor(config: ClientConfig) {
// Validate the configuration
@@ -38,6 +40,9 @@ export class Client {
this.guilds = new Guilds(this.api, this.processor);
this.users = new Users(this.api, this.processor);
this.messages = new Messages(this, this.api, this.processor);
// Save references to the chat and application command handlers
this.chatCommands = this.processor.chat_commands;
this.applicationCommands = this.processor.application_commands;
}
private static validateConfig(config: ClientConfig) {
@@ -66,6 +71,10 @@ export class Client {
}
}
get self() {
return this.gateway.user;
}
/**
* Hydrates a given data object based on the provided expectations.
*
@@ -106,17 +115,17 @@ export class Client {
return Message[fromDiscord](await this.api.post<DiscordMessage>(`/channels/${channel_id}/messages`, message.toJSON()));
}
chatCommands = {
register: (name: string | string[], handler: Handler) => this.processor.chat_commands.register(name, handler),
unregister: (name: string | string[]) => this.processor.chat_commands.unregister(name),
has: (name: string) => this.processor.chat_commands.has(name)
}
// chatCommands = {
// register: (name: string | string[], handler: Handler) => this.processor.chat_commands.register(name, handler),
// unregister: (name: string | string[]) => this.processor.chat_commands.unregister(name),
// has: (name: string) => this.processor.chat_commands.has(name)
// }
slashCommands = {
register: (name: string, handler: Handler) => this.processor.slash_commands.register(name, handler),
unregister: (name: string) => this.processor.slash_commands.unregister(name),
has: (name: string) => this.processor.slash_commands.has(name)
}
// applicationCommands = {
// register: (name: string, type: ApplicationCommandType, handler: Handler) => this.processor.application_commands.register(name, type, handler),
// unregister: (name: string) => this.processor.application_commands.unregister(name),
// has: (name: string) => this.processor.application_commands.has(name)
// }
connect = () => this.gateway.connect();
}
+63 -7
View File
@@ -1,12 +1,14 @@
import { WebSocket, type Data } from 'ws';
import type { Client } from "../client";
import { fromDiscord, type Payload } from "../../types/common";
import { fromDiscord, type InteractionPayload, type Payload } from "../../types/common";
import { exists, isNil, isObject, log } from "../../utils";
import type { API } from "../api";
import type { Processor } from '../processor';
import { Context } from '../../types/context';
import { type DiscordMessage, Message } from '../../types/message';
import { DiscordUser, User } from '../../types/user';
import { Guild } from '../../types/guild';
import { Channel } from '../../types/channel';
export class Gateway {
private socket: WebSocket | null = null;
@@ -14,7 +16,7 @@ export class Gateway {
private heartbeat_timeout: Timer | null = null;
private sequence: number | null = null;
// Internal state
private user: any;
user: User | null = null;
constructor(private client: Client, private processor: Processor, private api: API) {}
@@ -126,10 +128,9 @@ export class Gateway {
}
if (event_name === 'READY') {
this.user = event_data.user;
log('User:', this.user);
this.user = User[fromDiscord](DiscordUser.fromAPIResponse(event_data.user));
} else if (event_name === 'INTERACTION_CREATE') {
// this.handleInteractionCreate(payload);
this.handleInteractionCreate(payload);
} else if (event_name === 'MESSAGE_CREATE') {
await this.handleMessageCreate(payload as Payload);
} else if (event_name === 'MESSAGE_UPDATE') {
@@ -143,7 +144,7 @@ export class Gateway {
// If the event is a message event, create a message object
const message = Message[fromDiscord](event_data as DiscordMessage);
// And then generate the context
context = new Context(this.client, this.api, message);
context = new Context(this.client, this.api, { message });
}
// Call event handlers
@@ -151,6 +152,10 @@ export class Gateway {
}
private handleMessageCreate = async (payload: Payload) => {
if (isNil(this.user)) {
throw new Error('Cannot handle MESSAGE_CREATE event without a user');
}
if (!isObject(payload.d)) {
throw new Error('Invalid MESSAGE_CREATE payload received');
}
@@ -188,7 +193,7 @@ export class Gateway {
// Create a new message object from the payload
const message = Message[fromDiscord](payload.d as DiscordMessage);
// Generate context
const context = new Context(this.client, this.api, message);
const context = new Context(this.client, this.api, { message });
// Check if command exists
if (this.processor.chat_commands.has(command)) {
// Execute the handler
@@ -200,6 +205,57 @@ export class Gateway {
}
};
private handleInteractionCreate = (payload: Payload) => {
if (isNil(payload.d)) {
throw new Error('Invalid INTERACTION_CREATE payload received');
}
if (!isObject(payload.d)) {
throw new Error('Invalid INTERACTION_CREATE data received');
}
if (typeof payload.d.type !== 'number') {
throw new Error('Invalid INTERACTION_CREATE type received');
}
if (payload.d.type === 2) {
this.handleShashInteraction(payload as Payload & { d: InteractionPayload });
} else {
// this.handleChatInteraction(payload);
}
};
private handleShashInteraction = (payload: Payload & { d: InteractionPayload }) => {
console.log('handleShashInteraction')
const command = payload.d.data.name;
const args = payload.d.data.options;
const context = new Context(this.client, this.api, { interaction: payload.d });
if (payload.d.data.guild) {
const guild = Guild[fromDiscord](payload.d.data.guild);
this.client.guilds.set(guild.id, guild);
}
if (payload.d.data.member) {
const member = User[fromDiscord](payload.d.data.member.user);
this.client.users.set(member.id, member);
}
// TODO: Fix when channel class is implemented
// if (payload.d.data.channel) {
// const channel = Channel[fromDiscord](payload.d.data.channel);
// this.client.channels.set(channel.id, channel);
// }
if (this.processor.application_commands.has(command)) {
this.processor.application_commands.execute(command, context, args);
} else {
// TODO: Custom unknown command handler
context.reply(`Unknown command: ${command}`);
}
};
async connect() {
// Fetch the Discord gateway URL
const response = await this.api.request('GET', '/gateway/bot');
+75 -21
View File
@@ -1,15 +1,15 @@
import type { Client } from "./client";
import type { Context } from "../types/context";
import { HandlerType, Trait, type EventPayload } from "../types/common";
import { type CommandHandler, type Handler } from "../types/handler";
import { CommandHandler, type Handler, type ArgsFromOptions, OptionTypeMap } from "../types/handler";
import type { API } from "./api";
import type { ApplicationCommandOption } from "../types/applicationCommand";
import { ApplicationCommandType, type ApplicationCommandOption, type ApplicationCommandOptionResult } from "../types/applicationCommand";
export class Processor {
private handlers = {
[HandlerType.Events]: new Map<string, Handler[]>(),
[HandlerType.ChatCommands]: new Map<string, Handler[]>(),
[HandlerType.SlashCommands]: new Map<string, Handler[]>(),
[HandlerType.ApplicationCommands]: new Map<string, Handler[]>(),
[HandlerType.Interactions]: new Map<string, Handler[]>()
};
@@ -19,7 +19,7 @@ export class Processor {
// Normalize events into an array
const events = Array.isArray(event) ? event : [event];
// Register the handler for each event
for (const e of events) {
for (const e of events) {
const handlers = this.handlers[type].get(e) || [];
handlers.push(handler);
this.handlers[type].set(e, handlers);
@@ -56,12 +56,13 @@ export class Processor {
if (handlers) {
for (const handler of handlers) {
if (isCommandHandler(handler)) {
if (type === HandlerType.Events) {
throw new Error('Event handlers cannot be a CommandHandler');
}
await Promise.resolve(handler[Trait.execute](context!, argsOrPayload));
if (Processor.isCommandHandler(handler)) {
// TODO: Enforce this?
// if (type === HandlerType.Events) {
// throw new Error('Event handlers cannot be a CommandHandler');
// }
const resolvedArgs = await this.validateAndResolveArgs(argsOrPayload, handler.args);
await Promise.resolve(handler[Trait.execute](context!, resolvedArgs));
} else {
// TODO: Fix ts error
await Promise.resolve(handler(context, argsOrPayload));
@@ -69,6 +70,33 @@ export class Processor {
}
}
}
private validateAndResolveArgs = <T extends readonly ApplicationCommandOption[]>(args: ApplicationCommandOptionResult[], definition: T): Promise<ArgsFromOptions<T>> => {
// Zip the args and definition together
const zipped: [ApplicationCommandOption, ApplicationCommandOptionResult][] = args.map((arg, i) => [definition[i], arg]);
// Validate the args
const validated: Record<string, any> = {};
for (const [def, arg] of zipped) {
if (def.choices) {
// If the definition has choices, validate the arg against them
const choice = def.choices.find((choice: any) => choice.value === arg.value);
if (!choice) {
throw new Error(`Invalid choice for ${def.name}: expected one of ${def.choices.map((c: any) => c.value).join(', ')}, got ${arg.value}`);
}
validated[def.name] = choice.value;
} else {
// Otherwise just check the type
if (arg.value instanceof OptionTypeMap[def.type]) {
// TODO: Coerce the type if possible
throw new Error(`Invalid type for ${def.name}: expected ${def.type}, got ${typeof arg}`);
} else {
validated[def.name] = arg.value;
}
}
}
// TODO: Fix types so we don't need to cast here
return Promise.resolve(validated as ArgsFromOptions<T>);
};
[HandlerType.Events] = {
register: (event: string | string[], handler: Handler) => this.register(HandlerType.Events, event, handler),
@@ -84,11 +112,37 @@ export class Processor {
has: (event: string) => this.handlers[HandlerType.ChatCommands].has(event) ?? this.handlers[HandlerType.ChatCommands].get(event)?.length! > 0
};
[HandlerType.SlashCommands] = {
register: (event: string | string[], handler: Handler) => this.register(HandlerType.SlashCommands, event, handler),
unregister: (event: string | string[], handler?: Handler) => this.unregister(HandlerType.SlashCommands, event, handler),
execute: async (event: string, context: Context, args: any[]) => this.execute(HandlerType.SlashCommands, event, context, args),
has: (event: string) => this.handlers[HandlerType.SlashCommands].has(event) ?? this.handlers[HandlerType.SlashCommands].get(event)?.length! > 0
[HandlerType.ApplicationCommands] = {
register: (name: string | string[], type: ApplicationCommandType, handler: Handler) => {
const names = Array.isArray(name) ? name : [name];
// This is an application command so we need to register it with the API
// Ensure the handler is a CommandHandler
// TODO: Don't enforce this?
if (!Processor.isCommandHandler(handler)) {
throw new Error('Handler must be a CommandHandler');
}
// Ensure the command name is valid
// @see https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-naming
if (!names.every(/^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$/u.test.bind(/^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$/u))) {
throw new Error('Invalid application command name');
};
for (const n of names) {
// Register the command with the API
const command: Record<string, any> = handler.toJSON();
command.name = n;
command.description = handler.description;
command.type = type;
this.api.post(`/applications/${this.client.application_id}/commands`, command);
}
this.register(HandlerType.ApplicationCommands, names, handler)
},
unregister: (event: string | string[], handler?: Handler) => this.unregister(HandlerType.ApplicationCommands, event, handler),
execute: async (event: string, context: Context, args: any[]) => this.execute(HandlerType.ApplicationCommands, event, context, args),
has: (event: string) => this.handlers[HandlerType.ApplicationCommands].has(event) ?? this.handlers[HandlerType.ApplicationCommands].get(event)?.length! > 0,
};
[HandlerType.Interactions] = {
@@ -97,12 +151,12 @@ export class Processor {
execute: async (event: string, context: Context, args: any[]) => this.execute(HandlerType.Interactions, event, context, args),
has: (event: string) => this.handlers[HandlerType.Interactions].has(event) ?? this.handlers[HandlerType.Interactions].get(event)?.length! > 0
};
}
const isCommandHandler = (handler: Handler): handler is CommandHandler<readonly ApplicationCommandOption[]> => {
if (typeof handler === 'object') {
return 'args' in handler && Trait.execute in handler;
} else {
return false;
static isCommandHandler = (handler: Handler): handler is CommandHandler<readonly ApplicationCommandOption[]> => {
if (typeof handler === 'object') {
return 'args' in handler && Trait.execute in handler && handler instanceof CommandHandler;
} else {
return false;
}
}
}