A powerful and extendable Discord bot, with it's own module system :3 thevoid.cafe/projects/voidy
at develop 2.0 kB view raw
1//=============================================== 2// Imports 3//=============================================== 4import { ModuleLoader } from "../loaders/ModuleLoader"; 5import type { Command } from "./types/Command"; 6import type { Button } from "./types/Button"; 7import type { Module } from "./types/Module"; 8import type { Event } from "./types/Event"; 9 10export type CacheMap<T = unknown> = Map<string, T>; 11 12//=============================================== 13// ModuleManager Implementation 14//=============================================== 15export class ModuleManager { 16 private cache = new Map<string, Map<string, unknown>>(); 17 18 // Module Loading 19 //============================== 20 async loadModules(path: string) { 21 const moduleLoader = new ModuleLoader(path); 22 const modules = (await moduleLoader.collect()).getJSON(); 23 24 for (const module of modules) { 25 await this.prepareModule(module); 26 } 27 } 28 29 async prepareModule(module: Module) { 30 for (const exp of module.exports) { 31 const loader = new exp.loader(exp.source); 32 const data = (await loader.collect()).getJSON(); 33 34 for (const item of data) { 35 this.set(loader.id, (item as any).id, item); 36 } 37 } 38 } 39 40 // Core API 41 //============================== 42 set<T>(type: string, id: string, value: T) { 43 if (!this.cache.has(type)) this.cache.set(type, new Map()); 44 (this.cache.get(type) as CacheMap<T>).set(id, value); 45 } 46 47 get<T>(type: string, id: string): T | undefined { 48 return (this.cache.get(type) as CacheMap<T>)?.get(id); 49 } 50 51 getAll<T>(type: string): CacheMap<T> { 52 return (this.cache.get(type) as CacheMap<T>) ?? new Map(); 53 } 54 55 // Typed Accessors 56 //============================== 57 get modules(): CacheMap<Module> { 58 return this.getAll<Module>("module"); 59 } 60 61 get commands(): CacheMap<Command> { 62 return this.getAll<Command>("command"); 63 } 64 65 get buttons(): CacheMap<Button> { 66 return this.getAll<Button>("button"); 67 } 68 69 get events(): CacheMap<Event> { 70 return this.getAll<Event>("event"); 71 } 72}