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
+1 -1
View File
@@ -10,7 +10,7 @@ export { Guild } from './types/guild';
export { Role } from './types/role';
export { Member } from './types/member';
export { User } from './types/user';
export { Message, type MessagePayload } from './types/message';
export { Message, type MessagePayload, ComponentStyle, ComponentType } from './types/message';
export { Embed } from './types/embed';
export { Emoji } from './types/emoji';
// Other
+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
};
-2
View File
@@ -55,8 +55,6 @@ export type Payload = {
t: string | null;
};
export type InteractionPayload = Record<string, any>;
export enum InteractionResponseType {
Pong = 1,
Message = 4,
+5 -4
View File
@@ -2,8 +2,9 @@ import type { API } from "../services/api";
import type { Client } from "../services/client";
import { hydrate, hydrator, type Hydrateable, type Hydrated } from "../services/hydrator";
import { isNil, exists } from "../utils";
import { fromDiscord, InteractionResponseType, type Expectation, type InteractionPayload } from "./common";
import { fromDiscord, InteractionResponseType, type Expectation } from "./common";
import type { Guild } from "./guild";
import type { InteractionPayload } from "./handler";
import { type DiscordMessage, Message, type MessagePayload } from "./message";
/**
* Represents the context of a message in a Discord channel.
@@ -106,14 +107,14 @@ export class Context<D extends ContextData = ContextData> {
message = new Message().setContent(message);
}
if (exists(this.message)) {
if (exists(this.interaction)) {
return this.ack(InteractionResponseType.Message, message.toJSON());
} else if (exists(this.message)) {
if (reference) {
message.setReference(this.message)
}
return this.client.sendMessage(this.channel_id, message);
} else if (exists(this.interaction)) {
return this.ack(InteractionResponseType.Message, message.toJSON());
} else {
throw new Error('Cannot reply without a message or interaction payload');
}
+5 -3
View File
@@ -1,10 +1,11 @@
import { GatewayObject } from "./base";
import { Channel } from "./channel";
import { Trait } from "./common";
import { Emoji } from "./emoji";
import { Member } from "./member";
import { Role } from "./role";
export class Guild {
export class Guild extends GatewayObject {
id: string;
name: string;
description: string | null;
@@ -15,6 +16,7 @@ export class Guild {
// roles: Role[];
constructor(data: Guild) {
super();
this.id = data.id;
this.name = data.name;
this.description = data.description;
@@ -25,7 +27,7 @@ export class Guild {
// this.roles = data.roles;
}
public static [Trait.fromDiscord](data: DiscordGuild) {
public static [Trait.fromDiscord]<T = Guild>(data: DiscordGuild): T {
return new Guild({
id: data.id,
name: data.name,
@@ -35,7 +37,7 @@ export class Guild {
owner_id: data.owner_id,
// emojis: data.emojis,
// roles: data.roles,
});
}) as T;
}
}
+60 -1
View File
@@ -1,7 +1,66 @@
import { ApplicationCommandContext, ApplicationCommandOptionType, type ApplicationCommandOption } from "./applicationCommand";
import { Trait, type EventPayload } from "./common";
import type { Context } from "./context";
import type { User } from "./user";
import type { DiscordGuild } from "./guild";
import type { DiscordMessage } from "./message";
import type { DiscordUser, User } from "./user";
// TODO: Flesh out InteractionPayload type
export type InteractionPayload = {
id: string;
token: string;
type: number;
data?: InteractionData;
guild?: DiscordGuild;
guild_id: string;
// TODO: Add channel class
// channel?: DiscordChannel;
channel_id: string;
// TODO: Add member class
member?: Record<string, any> & { user: DiscordUser };
user?: DiscordUser
message?: DiscordMessage;
};
// TODO: Flesh out InteractionData type
export type InteractionData = InteractionCommpoentData | InteractionCommandData;
export type InteractionCommpoentData = {
custom_id: string;
component_type: number;
values?: any[];
resolved?: {
users?: Record<string, DiscordUser>;
members?: Record<string, DiscordUser>;
roles?: Record<string, any>;
channels?: Record<string, any>;
messages?: Record<string, any>;
attachments?: Record<string, any>;
};
};
export type InteractionCommandData = {
id: string;
name: string;
type: number;
resolved?: {
users?: Record<string, DiscordUser>;
members?: Record<string, DiscordUser>;
roles?: Record<string, any>;
channels?: Record<string, any>;
messages?: Record<string, any>;
attachments?: Record<string, any>;
}
options?: {
name: string;
type: ApplicationCommandOptionType;
value?: any;
options?: InteractionCommandData[];
focused?: boolean;
}[];
guild_id?: string;
target_id?: string;
}
export const OptionConstructorMap = {
[ApplicationCommandOptionType.String]: String,