TravBot-v3/src/core/event.ts

42 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-12-15 01:44:28 +00:00
import {Client, ClientEvents, Constants} from "discord.js";
import Storage from "./storage";
import $ from "./lib";
2020-07-25 11:01:24 +00:00
2020-10-15 09:23:24 +00:00
interface EventOptions<K extends keyof ClientEvents> {
2020-12-15 01:44:28 +00:00
readonly on?: (...args: ClientEvents[K]) => void;
readonly once?: (...args: ClientEvents[K]) => void;
2020-07-25 11:01:24 +00:00
}
2020-10-15 09:23:24 +00:00
export default class Event<K extends keyof ClientEvents> {
2020-12-15 01:44:28 +00:00
private readonly on?: (...args: ClientEvents[K]) => void;
private readonly once?: (...args: ClientEvents[K]) => void;
2020-10-15 09:23:24 +00:00
2020-12-15 01:44:28 +00:00
constructor(options: EventOptions<K>) {
this.on = options.on;
this.once = options.once;
}
2020-10-15 09:23:24 +00:00
2020-12-15 01:44:28 +00:00
// For this function, I'm going to assume that the event is used with the correct arguments and that the event tag is checked in "storage.ts".
public attach(client: Client, event: K) {
if (this.on) client.on(event, this.on);
if (this.once) client.once(event, this.once);
}
2020-07-25 23:32:49 +00:00
}
2020-10-15 09:23:24 +00:00
export async function loadEvents(client: Client) {
2020-12-15 01:44:28 +00:00
for (const file of Storage.open("dist/events", (filename: string) =>
filename.endsWith(".js")
)) {
const header = file.substring(0, file.indexOf(".js"));
const event = (await import(`../events/${header}`)).default;
2020-10-15 09:23:24 +00:00
2020-12-15 01:44:28 +00:00
if ((Object.values(Constants.Events) as string[]).includes(header)) {
event.attach(client, header);
$.log(`Loading Event: ${header}`);
} else
$.warn(
`"${header}" is not a valid event type! Did you misspell it? (Note: If you fixed the issue, delete "dist" because the compiler won't automatically delete any extra files.)`
);
}
2020-10-15 09:23:24 +00:00
}