From efb87df67c7666a574a802cd47cab06064cdc8a5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 3 Jul 2022 18:32:39 +0200 Subject: [PATCH] Add event loader --- src/events/loader.js | 36 ++++++++++++++++++++++++++++++++++++ src/index.js | 23 +++++++++++++++-------- 2 files changed, 51 insertions(+), 8 deletions(-) create mode 100644 src/events/loader.js diff --git a/src/events/loader.js b/src/events/loader.js new file mode 100644 index 0000000..0bb5032 --- /dev/null +++ b/src/events/loader.js @@ -0,0 +1,36 @@ +import { readdir } from 'fs/promises'; + +export default async client => { + const events_categories = (await readdir('./src/events')) + .filter(element => !element.endsWith('.js')); + + events_categories.forEach(async event_category => { + // Retrieve events + const events = await readdir(`./src/events/${event_category}`); + + // Load them into the client + Promise.all( + events.map(async event_file => { + const { once, default: execute } = await import( + `../events/${event_category}/${event_file}` + ); + + // Remove .js + let event_type = event_file.split('.'); + if (event_type.pop() !== 'js') { + throw `Unknown file in ${event_category}: ${event_file}`; + } + event_type = event_type.join('.'); + + if (once) { + return client.once(event_type, (...args) => { + execute(...args, client); + }); + } + return client.on(event_type, (...args) => { + execute(...args, client); + }); + }), + ); + }); +}; diff --git a/src/index.js b/src/index.js index 3324e65..ea180ed 100644 --- a/src/index.js +++ b/src/index.js @@ -1,23 +1,30 @@ import loadClient from './utils/client.js'; +import loadEvents from './events/loader.js'; const run = async () => { console.log('Starting Botanique...'); // Load .env if not in prod if (process.env.NODE_ENV !== 'production') { - const dotenv = await import('dotenv'); - dotenv.config({ path: './config/.env' }); + (await import('dotenv')).config({ path: './config/.env' }); } // Client Discord.JS - const client = await loadClient().catch(() => { - throw 'Client ❌'; - }); - if (client) { - console.log('Client ✅'); - } + const client = await loadClient() + .catch(() => { + throw 'Client ❌'; + }); + console.log('Client ✅'); + + await loadEvents(client) + .then(() => console.log('Events ✅')) + .catch(() => { + throw 'Events ❌'; + }); await client.login(client.config.token_discord); + + console.log(`Botanique "${client.user.username}" ${client.config.version} started!`); }; run().catch(error => console.error(error));