Added simple component interaction support

This commit is contained in:
2025-01-02 03:10:54 -06:00
parent fc7f6548a4
commit 202255d4ff
9 changed files with 220 additions and 45 deletions
+7 -5
View File
@@ -1,7 +1,7 @@
import { API } from './api';
import { Gateway } from './connectors/gateway';
import { Processor } from './processor';
import { Expectation, Intent, type ClientConfig } from '../types/common';
import { Expectation, HandlerType, Intent, type ClientConfig } from '../types/common';
import { exists, isNil } from '../utils/index';
import { type DiscordMessage, Message } from '../types/message';
import { Guilds } from './caches/guilds';
@@ -23,8 +23,9 @@ export class Client {
guilds: Guilds;
users: Users;
messages: Messages;
chatCommands: Processor['chat_commands'];
applicationCommands: Processor['application_commands'];
chatCommands: Processor[HandlerType.ChatCommands];
applicationCommands: Processor[HandlerType.ApplicationCommands];
interactions: Processor[HandlerType.Interactions];
constructor(config: ClientConfig) {
// Validate the configuration
@@ -43,8 +44,9 @@ export class Client {
this.users = new Users(this.api, this.processor);
this.messages = new Messages(this, this.api, this.processor);
// Save references to command and event handlers
this.chatCommands = this.processor.chat_commands;
this.applicationCommands = this.processor.application_commands;
this.chatCommands = this.processor[HandlerType.ChatCommands];
this.applicationCommands = this.processor[HandlerType.ApplicationCommands];
this.interactions = this.processor[HandlerType.Interactions];
}
private static validateConfig(config: ClientConfig) {
+35 -10
View File
@@ -1,6 +1,6 @@
import { WebSocket, type Data } from 'ws';
import type { Client } from "../client";
import { fromDiscord, HandlerType, type InteractionPayload, type Payload } from "../../types/common";
import { fromDiscord, HandlerType, type Payload } from "../../types/common";
import { exists, isNil, isObject, log } from "../../utils";
import type { API } from "../api";
import type { Processor } from '../processor';
@@ -9,6 +9,7 @@ import { type DiscordMessage, Message } from '../../types/message';
import { DiscordUser, User } from '../../types/user';
import { Guild } from '../../types/guild';
import type { Emitter } from '../bus';
import type { InteractionCommandData, InteractionCommpoentData, InteractionPayload } from '../../types/handler';
export class Gateway {
private socket: WebSocket | null = null;
@@ -228,29 +229,39 @@ export class Gateway {
}
if (payload.d.type === 2) {
this.handleShashInteraction(payload as Payload & { d: InteractionPayload });
this.handleShashInteraction(payload as Payload & { d: InteractionPayload & { data: InteractionCommandData } });
} else if (payload.d.type === 3) {
this.handleChatInteraction(payload as Payload & { d: InteractionPayload & { data: InteractionCommpoentData } });
} else {
// this.handleChatInteraction(payload);
}
};
private handleShashInteraction = (payload: Payload & { d: InteractionPayload }) => {
console.log('handleShashInteraction')
private handleShashInteraction = (payload: Payload & { d: InteractionPayload & { data: InteractionCommandData } }) => {
if (isNil(payload.d.data)) {
throw new Error('Invalid INTERACTION_CREATE data received');
}
const command = payload.d.data.name;
const args = payload.d.data.options;
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);
if (payload.d.guild) {
const guild = Guild.fromDiscord(payload.d.guild);
this.client.guilds.set(guild.id, guild);
}
if (payload.d.data.member) {
const member = User[fromDiscord](payload.d.data.member.user);
if (payload.d.member) {
const member = User.fromDiscord(payload.d.member?.user);
this.client.users.set(member.id, member);
}
if (payload.d.user) {
const user = User.fromDiscord(payload.d.user);
this.client.users.set(user.id, user);
}
// TODO: Fix when channel class is implemented
// if (payload.d.data.channel) {
// const channel = Channel[fromDiscord](payload.d.data.channel);
@@ -258,13 +269,27 @@ export class Gateway {
// }
if (this.processor.application_commands.has(command)) {
this.processor.application_commands.execute(command, context, args);
this.processor.application_commands.execute(command, context, args?.map(arg => arg.value));
} else {
// TODO: Custom unknown command handler
context.reply(`Unknown command: ${command}`);
}
};
private handleChatInteraction = (payload: Payload & { d: InteractionPayload & { data: InteractionCommpoentData } }) => {
const context = new Context(this.client, this.api, { interaction: payload.d });
if (exists(payload.d.data)) {
if (this.processor[HandlerType.Interactions].has(payload.d.data.custom_id)) {
this.processor[HandlerType.Interactions].execute(payload.d.data.custom_id, context, payload.d.data);
} else {
context.reply(`Unknown interaction: \`${payload.d.data.custom_id}\``);
}
} else {
context.reply('Invalid interaction data received');
}
};
async connect() {
// Fetch the Discord gateway URL
const response = await this.api.request('GET', '/gateway/bot');
+9 -15
View File
@@ -1,7 +1,7 @@
import type { Client } from "./client";
import type { Context } from "../types/context";
import { HandlerType, Trait, type EventPayload } from "../types/common";
import { CommandHandler, type Handler, type ArgsFromOptions, OptionConstructorMap } from "../types/handler";
import { CommandHandler, type Handler, type ArgsFromOptions, OptionConstructorMap, type InteractionData } from "../types/handler";
import type { API } from "./api";
import { ApplicationCommandOptionType, ApplicationCommandType, type ApplicationCommandOption } from "../types/applicationCommand";
import type { Emitter } from "./bus";
@@ -51,7 +51,8 @@ export class Processor {
};
public async execute(type: HandlerType.Events, event: string, context: Context | null, payload: EventPayload): Promise<void>
public async execute(type: Omit<HandlerType, HandlerType.Events>, event: string, context: Context, args: any[]): Promise<void>
public async execute(type: HandlerType.Interactions, event: string, context: Context | null, payload: InteractionData): Promise<void>
public async execute(type: Omit<HandlerType, HandlerType.Events | HandlerType.Interactions>, event: string, context: Context, args: any[]): Promise<void>
public async execute(type: HandlerType, event: string, context: Context | null, argsOrPayload: any[] | EventPayload) {
const handlers = this.handlers[type].get(event);
@@ -62,16 +63,9 @@ export class Processor {
if (type === HandlerType.Events) {
throw new Error('Event handlers cannot be a CommandHandler');
}
const formattedArgs = (() => {
if (type === HandlerType.ChatCommands) {
// TODO: Fix type narrowing here
// @ts-ignore - Haven't figured out how to type narrow this yet
return argsOrPayload.map((arg, i) => ({ name: handler.args[i].name, value: arg }));
} else {
return argsOrPayload;
}
})();
const resolvedArgs = await this.validateAndResolveArgs(formattedArgs, handler.args);
// Validate and resolve the args
const resolvedArgs = await this.validateAndResolveArgs(argsOrPayload, handler.args);
// Execute the handler
await Promise.resolve(handler[Trait.execute](context!, resolvedArgs));
} else {
// TODO: Fix ts error
@@ -82,9 +76,9 @@ export class Processor {
}
}
private validateAndResolveArgs = async <T extends readonly ApplicationCommandOption[]>(args: { value: any }[], definition: T): Promise<ArgsFromOptions<T>> => {
private validateAndResolveArgs = async <T extends readonly ApplicationCommandOption[]>(args: any[], definition: T): Promise<ArgsFromOptions<T>> => {
// Zip the args and definition together
const zipped: [ApplicationCommandOption, any][] = args.map((arg, i) => [definition[i], arg?.value ?? null]);
const zipped: [ApplicationCommandOption, any][] = args.map((arg, i) => [definition[i], arg]);
// Validate the args
const validated: Record<string, any> = {};
// TODO: Attempt some type coresion/resolution here (mostly for text commands)
@@ -182,7 +176,7 @@ export class Processor {
[HandlerType.Interactions] = {
register: (event: string | string[], handler: Handler) => this.register(HandlerType.Interactions, event, handler),
unregister: (event: string | string[], handler?: Handler) => this.unregister(HandlerType.Interactions, event, handler),
execute: async (event: string, context: Context, args: any[]) => this.execute(HandlerType.Interactions, event, context, args),
execute: async (event: string, context: Context, args: InteractionData) => this.execute(HandlerType.Interactions, event, context, args),
has: (event: string) => this.handlers[HandlerType.Interactions].has(event) ?? this.handlers[HandlerType.Interactions].get(event)?.length! > 0
};