From 6501125b26f0a4a2b48f4955d3d9557046d5614f Mon Sep 17 00:00:00 2001 From: Cynthia Foxwell Date: Mon, 17 May 2021 16:35:18 -0600 Subject: [PATCH] event and timer helpers --- src/index.js | 4 ++++ src/lib/events.js | 43 +++++++++++++++++++++++++++++++++++++++++++ src/lib/timer.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 src/lib/events.js create mode 100644 src/lib/timer.js diff --git a/src/index.js b/src/index.js index c85f42c..e1abc9f 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,8 @@ const {resolve} = require("path"); const config = require("../config.json"); const Command = require("./lib/command.js"); const CommandDispatcher = require("./lib/commandDispatcher.js"); +const events = require("./lib/events.js"); +const timer = require("./lib/timer.js"); const bot = new Eris(config.token, { defaultImageFormat: "png", @@ -32,6 +34,8 @@ global.hf = { config, commands, registerCommand, + events, + timer, }; for (const file of fs.readdirSync(resolve(__dirname, "modules"))) { diff --git a/src/lib/events.js b/src/lib/events.js new file mode 100644 index 0000000..9dc15f4 --- /dev/null +++ b/src/lib/events.js @@ -0,0 +1,43 @@ +const logger = require("npmlog"); + +const eventTable = {}; + +function getTable() { + return eventTable; +} + +function add(event, identifier, callback) { + if (eventTable[event] == null) eventTable[event] = {}; + + if (eventTable[event][identifier] != null) { + hf.bot.off(event, eventTable[event][identifier]); + } + + function wrapper() { + try { + callback.apply(this, arguments); + } catch (error) { + logger.error( + "hf:event", + `Event "${event}:${identifier}" failed: ${error}` + ); + } + } + + eventTable[event][identifier] = wrapper; + hf.bot.on(event, wrapper); +} + +function remove(event, identifier) { + if (eventTable[event] == null) eventTable[event] = {}; + + if (eventTable[event][identifier] != null) { + hf.bot.off(event, eventTable[event][identifier]); + } +} + +module.exports = { + getTable, + add, + remove, +}; diff --git a/src/lib/timer.js b/src/lib/timer.js new file mode 100644 index 0000000..5d5bc95 --- /dev/null +++ b/src/lib/timer.js @@ -0,0 +1,35 @@ +const logger = require("npmlog"); + +const timerTable = {}; + +function getTable() { + return timerTable; +} + +function add(identifier, callback, delay) { + if (timerTable[identifier] != null) { + clearInterval(timerTable[identifier]); + } + + function wrapper() { + try { + callback(); + } catch (error) { + logger.error("hf:timer", `Timer "${identifier}" failed: ${error}`); + } + } + + timerTable[identifier] = setInterval(wrapper, delay); +} + +function remove(identifier) { + if (timerTable[identifier] != null) { + clearInterval(timerTable[identifier]); + } +} + +module.exports = { + getTable, + add, + remove, +};