Hydrator is coming along

This commit is contained in:
Jaron
2024-11-13 13:34:43 -06:00
parent f419e82579
commit 5b1fa15e66
15 changed files with 174 additions and 110 deletions
+2 -1
View File
@@ -5,11 +5,12 @@ export { BaseHandler, type Handler } from './types/hander';
// Consumable types
export type { ClientConfig } from './types/common';
export type { Context } from './types/context';
export { Expectation } from './types/common';
// Consumable util classes
export { Guild } from './types/guild';
export { Role } from './types/role';
export { Member } from './types/member';
export { User } from './types/user';
export { Message } from './types/message';
export { Message, type MessagePayload } from './types/message';
export { Embed } from './types/embed';
export { Emoji } from './types/emoji';
+4 -3
View File
@@ -6,7 +6,7 @@ export class API {
constructor(private client: Client) {}
async request<T = any>(method: string, path: string, data?: any): Promise<T> {
const url = new URL(path, this.base_url).toString();
const url = `${this.base_url}${path.startsWith('/') ? '' : '/'}${path}`;
const headers = {
Authorization: `Bot ${this.client.token}`,
'Accept': 'application/json',
@@ -14,6 +14,7 @@ export class API {
};
console.log(`API Request: ${method} ${url}`);
console.log(`API Body: ${JSON.stringify(data, null, 4)}`);
const response = await fetch(url, {
method,
@@ -22,8 +23,8 @@ export class API {
});
if (!response.ok) {
console.error(`Failed to fetch: ${response.statusText} ${response.url} ${response.status}`);
console.error(response.json());
// console.error(`Failed to fetch: ${response.statusText} ${response.url} ${response.status}`);
console.log('Failed Request Response: ', await response.text());
throw new Error(`Failed to fetch: ${response.statusText}`);
}
+9 -9
View File
@@ -3,19 +3,19 @@ import { exists } from "../utils";
import type { API } from "./api";
import type { Processor } from "./processor";
export class ObjectCache<T> {
cache = new Map<string, Promise<T> | T>();
export class ObjectCache<T, K extends T> {
cache = new Map<string, Promise<K>>();
readonly type: string;
constructor(protected api: API, processor: Processor, type: string, private readonly factory: (...args: any[]) => Promise<T>, events: string[]) {
constructor(protected api: API, processor: Processor, type: string, private readonly factory: { fromDiscord: (data: any) => K } & (new (data: T) => T), events: string[]) {
this.type = type;
processor.events.register(events, async (_context: Context, e: Record<string, any>) => {
this.cache.set(e.id, factory(e));
this.cache.set(e.id, Promise.resolve(factory.fromDiscord(e)));
});
}
set(object_id: string, object: T): void {
this.cache.set(object_id, object);
set(object_id: string, object: K): void {
this.cache.set(object_id, Promise.resolve(object));
}
// update(object_id: string, object: Partial<T>): void {
@@ -29,14 +29,14 @@ export class ObjectCache<T> {
// }
// }
async fetch(object_id: string, ..._args: any[]): Promise<T> {
const req = this.api.get(`/${this.type}/${object_id}`).then((data) => this.factory(data));
async fetch(object_id: string, ..._args: any[]): Promise<K> {
const req = this.api.get(`/${this.type}/${object_id}`).then((data) => this.factory.fromDiscord(data));
this.cache.set(object_id, req);
req.catch(() => this.cache.delete(object_id));
return await req;
}
async get(object_id: string, ..._args: any[]): Promise<T> {
async get(object_id: string, ..._args: any[]): Promise<K> {
if (this.cache.has(object_id)) {
return await Promise.resolve(this.cache.get(object_id)!);
} else {
+7 -2
View File
@@ -1,13 +1,14 @@
import { API } from './api';
import { Gateway } from './gateway';
import { Processor } from './processor';
import { Intent, type ClientConfig } from '../types/common';
import { Expectation, Intent, type ClientConfig } from '../types/common';
import { exists, isNil } from '../utils/index';
import type { Handler } from '../types/hander';
import { DiscordMessage, Message } from '../types/message';
import { Guilds } from './guilds';
import { Users } from './users';
import { Messages } from './messages';
import { hydrator, type Hydrateable } from './hydrator';
export class Client {
readonly token: string;
@@ -65,12 +66,16 @@ export class Client {
}
}
hydrator = async<T extends Hydrateable, K extends Expectation[]>(data: T, expectations: K) => {
return hydrator<T, K>(data, expectations, this, this.api);
}
sendMessage = async (channel_id: string, message: Message | string) => {
if (typeof message === 'string') {
message = new Message().setContent(message);
}
return Message.hydrate(DiscordMessage.fromAPIResponse(await this.api.post(`/channels/${channel_id}/messages`, message.toJSON())), this, this.api);
return Message.fromDiscord(DiscordMessage.fromAPIResponse(await this.api.post(`/channels/${channel_id}/messages`, message.toJSON())));
}
chatCommands = {
+3 -5
View File
@@ -141,8 +141,7 @@ export class Gateway {
if (['MESSAGE_CREATE', 'MESSAGE_UPDATE'].includes(event_name)) {
// If the event is a message event, create a message object
const discord_message = DiscordMessage.fromAPIResponse(event_data);
const message = await Message.hydrate(discord_message, this.client, this.api);
const message = Message.fromDiscord(DiscordMessage.fromAPIResponse(event_data));
// And then generate the context
context = new Context(this.client, this.api, message);
}
@@ -165,7 +164,7 @@ export class Gateway {
return;
}
// Extract the author
const author = User.hydrate(DiscordUser.fromAPIResponse(payload.d.author));
const author = User.fromDiscord(DiscordUser.fromAPIResponse(payload.d.author));
// Store the author in the cache
this.client.users.set(author.id, author);
// Extract the content
@@ -186,9 +185,8 @@ export class Gateway {
// Extract the command name
// TODO: Case insensitive config?
const command = args.shift()!;
console.log('payload.d', payload.d)
// Create a new message object from the payload
const message = await Message.hydrate(DiscordMessage.fromAPIResponse(payload.d), this.client, this.api);
const message = Message.fromDiscord(DiscordMessage.fromAPIResponse(payload.d));
// Generate context
const context = new Context(this.client, this.api, message);
// Check if command exists
+2 -2
View File
@@ -3,8 +3,8 @@ import type { API } from "./api";
import { ObjectCache } from "./cache";
import type { Processor } from "./processor";
export class Guilds extends ObjectCache<Guild> {
export class Guilds extends ObjectCache<Guild, Guild> {
constructor (api: API, processor: Processor) {
super(api, processor, 'guilds', Guild.factory, ['GUILD_CREATE', 'GUILD_UPDATE']);
super(api, processor, 'guilds', Guild, ['GUILD_CREATE', 'GUILD_UPDATE']);
}
}
+45
View File
@@ -0,0 +1,45 @@
import { Expectation } from "../types/common";
import { Context, type HydratedContext } from "../types/context";
import { Message, type HydratedMessage } from "../types/message";
import { exists } from "../utils";
import type { API } from "./api";
import type { Client } from "./client";
export type GatewayObject = Message;
export type Hydrateable = Context | GatewayObject
export type Hydrated<T extends Hydrateable, K extends Array<Expectation>> =
T extends Message ? HydratedMessage<K> :
T extends Context ? HydratedContext<K> : never;
export async function hydrator<T extends Hydrateable, K extends Array<Expectation>>(data: T, expectations: K, client: Client, api: API): Promise<(data: unknown) => data is Hydrated<T, K>> {
let hydrated = true;
if (data instanceof Context) {
for (const expectation of expectations) {
if (expectation === Expectation.Guild && exists(data.guild_id)) {
let context = data as unknown as HydratedContext<[Expectation.Guild, ...Expectation[]]>;
context.guild = await client.guilds.get(data.guild_id);
} else {
hydrated = false;
break;
}
}
} else if (data instanceof Message) {
for (const expectation of expectations) {
if (expectation === Expectation.Message && exists(data.message_reference?.id)) {
let message = data as unknown as HydratedMessage<[Expectation.Message, ...Expectation[]]>;
message.reference = await client.messages.get(data.message_reference.channel_id, data.message_reference.id);
} else if (expectation === Expectation.Guild && exists(data.guild_id)) {
let message = data as unknown as HydratedMessage<[Expectation.Guild, ...Expectation[]]>;
message.guild = await client.guilds.get(data.guild_id);
} else {
hydrated = false;
break;
}
}
}
return function (data: unknown): data is Hydrated<T, K> {
return hydrated;
}
}
+6 -6
View File
@@ -1,22 +1,22 @@
import { Message } from "../types/message";
import { Message, type MessagePayload } from "../types/message";
import type { API } from "./api";
import { ObjectCache } from "./cache";
import type { Client } from "./client";
import type { Processor } from "./processor";
export class Messages extends ObjectCache<Message> {
export class Messages extends ObjectCache<Message, MessagePayload> {
constructor (protected client: Client, api: API, processor: Processor) {
super(api, processor, 'message', (data) => Message.factory(data, client, api), ['MESSAGE_CREATE', 'MESSAGE_UPDATE']);
super(api, processor, 'message', Message, ['MESSAGE_CREATE', 'MESSAGE_UPDATE']);
}
async fetch(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<Message> {
const req = this.api.get(`/channels/${channel_id}/messages/${message_id}`).then((data) => Message.factory(data, this.client, this.api, undefined, resolveReference));
async fetch(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<MessagePayload> {
const req = this.api.get(`/channels/${channel_id}/messages/${message_id}`).then((data) => Message.fromDiscord(data));
this.cache.set(message_id, req);
req.catch(() => this.cache.delete(message_id));
return await req;
}
async get(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<Message> {
async get(channel_id: string, message_id: string, resolveReference: boolean = true): Promise<MessagePayload> {
if (this.cache.has(message_id)) {
return await Promise.resolve(this.cache.get(message_id)!);
} else {
+3 -3
View File
@@ -1,10 +1,10 @@
import type { User } from "../types/user";
import { User } from "../types/user";
import type { API } from "./api";
import { ObjectCache } from "./cache";
import type { Processor } from "./processor";
export class Users extends ObjectCache<User> {
export class Users extends ObjectCache<User, User> {
constructor (api: API, processor: Processor) {
super(api, processor, 'users', []);
super(api, processor, 'users', User, []);
}
}
+8 -5
View File
@@ -1,13 +1,17 @@
import type { Client } from "../services/client";
import type { Context } from "./context";
import type { BaseHandler } from "./hander";
export type ClientConfig = {
token: string;
application_id: string;
prefix?: string;
intents?: Intent[];
}
export enum Expectation {
Guild = 'guild',
Channel = 'channel',
User = 'user',
Message = 'message',
}
export enum HandlerType {
Events = 'events',
ChatCommands = 'chat_commands',
@@ -15,7 +19,6 @@ export enum HandlerType {
Interactions = 'interactions'
}
export type EventPayload = any;
export type Primitive = string | number | boolean | null;
+18 -14
View File
@@ -1,7 +1,10 @@
import type { API } from "../services/api";
import type { Client } from "../services/client";
import { hydrator, type Hydrateable } from "../services/hydrator";
import { isNil } from "../utils";
import { DiscordMessage, Message } from "./message";
import type { Expectation } from "./common";
import type { Guild } from "./guild";
import { DiscordMessage, Message, type MessagePayload } from "./message";
/**
* Represents the context of a message in a Discord channel.
* Provides methods to interact with the message and the channel it was sent in.
@@ -20,13 +23,18 @@ import { DiscordMessage, Message } from "./message";
* @throws {Error} If the message ID is not provided.
* @throws {Error} If the channel ID is not provided.
*/
export type HydratedContext<T extends Array<Expectation>> = Context & {
guild: Extract<Expectation.Guild, T[number]> extends never ? undefined : Guild;
};
export class Context {
// Public properties
message_id: string;
channel_id: string;
guild_id?: string;
constructor(private client: Client, private api: API, public message: Message) {
constructor(private client: Client, private api: API, public message: MessagePayload) {
console.log('Context created: ', );
if (isNil(message.id)) {
throw new Error('Message ID is required to create a context');
@@ -42,25 +50,21 @@ export class Context {
this.guild_id = message.guild_id;
}
hydrator = <T extends Hydrateable, K extends Array<Expectation>>(data: T, expectations: K) => {
return hydrator<T, K>(data, expectations, this.client, this.api);
}
// get author() {
// return this.client.users.get(this.author_id);
// };
async fetchGuild() {
if (isNil(this.guild_id)) {
return Promise.resolve(null);
}
return this.client.guilds.get(this.guild_id);
}
/**
* Reply to the message that this command
* @param message The message to send to the channel
* @param reference If true the message will be a reference the the message that triggered the command
* @returns The message that was sent
*/
public reply = (message: Message | string, reference: boolean = true) => {
public reply = async (message: Message | string, reference: boolean = true): Promise<MessagePayload> => {
if (typeof message === 'string') {
message = new Message().setContent(message);
}
@@ -92,8 +96,8 @@ export class Context {
* @param {string} [message_id] - The ID of the message to delete. If not provided, the message ID of this context will be used.
* @returns {Promise<void>} A promise that resolves when the message is deleted.
*/
public deleteMessage = (message_id: string) => {
return this.api.delete(`/channels/${this.channel_id}/messages/${message_id ?? this.message_id}`);
public deleteMessage = (message_id: string): Promise<void> => {
return this.api.delete(`/channels/${this.channel_id}/messages/${message_id ?? this.message_id}`).then(() => {});
};
/**
@@ -108,6 +112,6 @@ export class Context {
if (content) {
clone.setContent(content);
}
return Message.hydrate(DiscordMessage.fromAPIResponse(await this.api.patch(`/channels/${clone.channel_id}/messages/${clone.id}`, clone)), this.client, this.api);
return Message.fromDiscord(DiscordMessage.fromAPIResponse(await this.api.patch(`/channels/${clone.channel_id}/messages/${clone.id}`, clone)));
};
}
+1 -7
View File
@@ -24,13 +24,7 @@ export class Guild {
// this.roles = data.roles;
}
public static async factory(data: any) {
return await Guild.hydrate(DiscordGuild.fromAPIResponse(data));
}
public static async hydrate(data: DiscordGuild) {
public static fromDiscord(data: DiscordGuild) {
return new Guild({
id: data.id,
name: data.name,
+48 -31
View File
@@ -1,7 +1,9 @@
import type { API } from '../services/api';
import type { Client } from '../services/client';
import { isNil } from '../utils';
import type { Expectation } from './common';
import { Embed } from './embed';
import type { Guild } from './guild';
import { DiscordUser, User } from './user';
export type Component = Partial<Button | SelectMenu> & {
@@ -81,6 +83,27 @@ export enum ComponentType {
ChannelSelect
}
export type HydratedMessage<T extends Array<Expectation>> = MessagePayload & {
// channel: Extract<Expectation.Channel, T[number]> extends never ? undefined : Channel;
reference: Extract<Expectation.Message, T[number]> extends never ? undefined : MessagePayload;
guild: Extract<Expectation.Guild, T[number]> extends never ? undefined : Guild;
}
export type MessagePayload = Message & {
id: string;
author: User;
channel_id: string;
content: string;
embeds: Embed[];
components: Component[];
message_reference?: {
id: string;
channel_id: string;
guild_id?: string;
};
timestamp: Date;
};
export class Message {
id?: string;
author?: User;
@@ -89,8 +112,12 @@ export class Message {
public content: string;
public embeds: Embed[] = [];
public components: Component[] = [];
public reference?: Message;
timestamp: Date;
public message_reference?: {
id: string;
channel_id: string;
guild_id?: string;
};
timestamp?: Date;
constructor(data?: Partial<Message>) {
this.id = data?.id;
@@ -98,31 +125,18 @@ export class Message {
this.channel_id = data?.channel_id;
this.guild_id = data?.guild_id;
this.content = data?.content ?? '';
this.reference = data?.reference;
this.timestamp = data?.timestamp ?? new Date();
this.timestamp = data?.timestamp;
}
public static factory = async (data: any, client: Client, api: API, resolveReference: boolean = true): Promise<Message> => {
return Message.hydrate(DiscordMessage.fromAPIResponse(data), client, api, resolveReference);
}
public static hydrate = async (discord_message: DiscordMessage, client: Client, api: API, resolveReference: boolean = true): Promise<Message> => {
let reference: Message | undefined;
if (discord_message.message_reference && resolveReference) {
const { channel_id, message_id } = discord_message.message_reference;
reference = await client.messages.get(channel_id, message_id, false);
}
public static fromDiscord(data: DiscordMessage): MessagePayload {
return new Message({
id: discord_message.id,
author: User.hydrate(discord_message.author),
channel_id: discord_message.channel_id,
guild_id: discord_message?.guild_id,
content: discord_message.content,
reference,
timestamp: new Date(discord_message.timestamp)
});
id: data.id,
author: User.fromDiscord(data.author),
channel_id: data.channel_id,
guild_id: data.guild_id,
content: data.content,
timestamp: new Date(data.timestamp)
}) as MessagePayload;
}
public static button(config: Button): Component {
@@ -178,7 +192,11 @@ export class Message {
ref = message;
}
this.reference = ref;
this.message_reference = {
id: ref.id!,
channel_id: ref.channel_id!,
guild_id: ref.guild_id
};
return this;
};
@@ -187,12 +205,11 @@ export class Message {
content: this.content,
embeds: this.embeds,
components: this.components,
message_reference: {
message_id: this.reference?.id,
channel_id: this.reference?.channel_id,
guild_id: this.reference?.guild_id,
fail_if_not_exists: false
}
message_reference: this.message_reference ? {
message_id: this.message_reference.id,
channel_id: this.message_reference.channel_id,
guild_id: this.message_reference.guild_id
} : undefined
};
};
}
+1 -5
View File
@@ -30,11 +30,7 @@ export class User {
this.email = data.email;
}
public static async factory(data: DiscordUser) {
return User.hydrate(DiscordUser.fromAPIResponse(data));
}
public static hydrate(data: DiscordUser) {
public static fromDiscord(data: DiscordUser): User {
return new User({
id: data.id,
username: data.username,
+17 -17
View File
@@ -1,4 +1,4 @@
import { Client, type Context, Intent } from '../src/index';
import { Client, type Context, Expectation, Intent, type MessagePayload } from '../src/index';
const client = new Client({
token: process.env.BOT_TOKEN!,
@@ -21,33 +21,33 @@ client.chatCommands.register('ping', async (context: Context, args: any[]) => {
});
client.chatCommands.register('here', async (context: Context, _args: any[]) => {
const guild = await context.fetchGuild();
if (guild !== null) {
await context.reply(`You are in ${guild.name}`, true);
const guild = (await context.hydrator(context, [Expectation.Guild]))(context);
if (guild) {
await context.reply(`You are in ${context.guild.name}`, true);
} else {
await context.reply('This is not a server!', true);
}
});
client.chatCommands.register('quote', async (context: Context, _args: any[]) => {
const referenced = context.message.reference;
const { message, hydrator } = context;
const reference = (await hydrator(message, [Expectation.Message]))(message);
let reply = null;
if (referenced === null || referenced === undefined) {
reply = await context.reply('No message to quote', true);
return;
} else {
reply = await context.reply(`> "${referenced.content}"\n> — ${referenced.author?.display_name ?? referenced.author?.username}`, true);
let reply: MessagePayload;
if (reference) {
reply = await context.reply(`> "${message.reference.content}"\n> — ${message.reference.author.display_name ?? message.reference.author.username}`, true);
// Save to quote database
// TODO
} else {
reply = await context.reply('No message to quote', true);
}
if (reply?.id) {
const message_id = reply.id;
setTimeout(() => {
context.deleteMessage(message_id);
}, 3000);
}
// Wait 3 seconds then delete the quote
setTimeout(() => {
context.deleteMessage(reply.id);
}, 3000);
});
client.connect();