UNPKG

modernirc

Version:

IRC library for creating modern IRC bots

80 lines (74 loc) 2.47 kB
/** * Module initialization wrapper */ import process from 'node:process' import path from 'node:path' import { EventEmitter } from 'node:events' /** * Loads a module from its name * @param moduleName {string} Module name * @param options {object} Full object of module options * @returns {Promise<null | * | void>} */ function loadModule(moduleName, options) { return import(path.join(process.cwd(), 'modules', moduleName, 'index.js')) .catch(() => { return import(moduleName) }) .catch(() => { options.logger.error(`module ${moduleName} errored: not found`) }) .then(async (_mod) => { if (typeof _mod?.init !== 'function') { options.logger.warning(`module ${moduleName} ignored: no init`) return null } return _mod }) } /** * Pass through the modules declared in the bot options and try to initialize them * @param bot {object} Bot object * @param options {object} Bot options * @returns {Promise<*[]>} */ export async function loadModules(bot, options) { await Promise.all( Object.keys(options.modules) .map(async (modname) => { try { if (!options.modules[modname].enabled) { options.logger.warning(`module ${modname} ignored: not enabled`) } else { const _mod = await loadModule(modname, options) if (_mod) { const _ee = new EventEmitter() const runner = await _mod.init(bot, { ...options.modules[modname], name: modname, logger: options.logger.child(modname), }, _ee) options.logger.info(`module ${modname} loaded: ok`) bot.loadedModules.push({ name: modname, moduleOptions: options.modules[modname], runner, emitter: _ee, }) } } } catch (err) { options.logger.error(`module ${modname} errored: ${err.message}`) } }) ) for (let i = 0; i < bot.loadedModules.length; i++) { const lm = bot.loadedModules[i] lm.emitter.on('bubble', (moduleName, ...args) => { const target = bot.loadedModules.find((m) => m.name === moduleName) if (target && target.moduleOptions.bubbleListeners?.includes(lm.name) && typeof target.runner.onBubbleEvent === 'function') { target.runner.onBubbleEvent(lm.name, ...args) } }) } }