Skip to content

Commit

Permalink
Switch to ESM syntax with named imports
Browse files Browse the repository at this point in the history
  • Loading branch information
brandoningli committed Sep 3, 2023
1 parent 28a7ab7 commit d501691
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 83 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,6 @@
"prettier": {},
"engines": {
"node": ">=16.6.0"
}
}
},
"type": "module"
}
8 changes: 4 additions & 4 deletions src/CustomDiscordWebhookTransport.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
const DiscordWebhookTransport = require("@typicalninja21/discord-winston");
const utils = require("./utils.js");
import DiscordWebhookTransport from "@typicalninja21/discord-winston";
import { logger } from "./utils.js";

// prettier-ignore
module.exports = class CustomDiscordWebhookTransport extends DiscordWebhookTransport {
export default class CustomDiscordWebhookTransport extends DiscordWebhookTransport {
log(info, callback) {
try {
if (info.postToDiscord == false) return callback();
this.postToWebhook(info);
return callback();
} catch (e) {
utils.logger.error(`Error occurred trying to log to Discord: ${e.stack}`, {
logger.error(`Error occurred trying to log to Discord: ${e.stack}`, {
postToDiscord: false,
});
}
Expand Down
12 changes: 6 additions & 6 deletions src/configManager.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const utils = require("./utils.js");
const fs = require("fs");
import { logger } from './utils.js'
import fs from 'fs';

let config;

Expand All @@ -18,16 +18,16 @@ function initConfig() {

function loadConfig() {
try {
module.exports.config = JSON.parse(
config = JSON.parse(
fs.readFileSync("../config.json", { encoding: "utf8", flag: "r" })
);
} catch (error) {
utils.logger.log(
logger.log(
"warn",
`config.json not found. Generating new configuration file...`
);
module.exports.config = initConfig();
config = initConfig();
}
}

module.exports = { loadConfig, defaultConfig, initConfig, config };
export { loadConfig, defaultConfig, initConfig, config };
75 changes: 38 additions & 37 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,28 @@
*/

// dependencies
require("dotenv").config({
import dotenv from 'dotenv';
dotenv.config({
path: process.argv.includes("--testing") ? "../.env.testing" : "../.env",
});
import djs from 'discord.js';
const {
Client,
Intents,
GatewayIntentBits,
Partials,
ChannelType,
ActivityType,
} = require("discord.js");
const winston = require("winston");
const winstonDiscord = require("./CustomDiscordWebhookTransport.js");
const winstonRotateFile = require("winston-daily-rotate-file");
const utils = require("./utils.js");
const configManager = require("./configManager");
const pluginManager = require("./pluginManager.js");
} = djs;
import winston from "winston";
import winstonDiscord from "./CustomDiscordWebhookTransport.js";
import winstonRotateFile from "winston-daily-rotate-file";
import { logger, setLogger, plugins, reply } from "./utils.js";
import { loadConfig, defaultConfig, initConfig, config } from "./configManager.js";
import pluginManager from "./pluginManager.js";
const consoleLogLevel = process.env.CONSOLE_LOG_LEVEL ?? "warn";

utils.logger = winston.createLogger({
setLogger(winston.createLogger({
transports: [
new winston.transports.Console({
level: consoleLogLevel,
Expand Down Expand Up @@ -80,31 +82,30 @@ utils.logger = winston.createLogger({
),
}),
],
});
}));

// Deal with just generating a config
if (process.argv.includes("--reset-config")) {
utils.logger.warn("Resetting to default configuration.");
configManager.initConfig();
utils.logger.log("debug", "Configuration reset. Exiting.");
logger.warn("Resetting to default configuration.");
initConfig();
logger.log("debug", "Configuration reset. Exiting.");
process.exit(0);
}

// Just log the default config
if (process.argv.includes("--show-default-config")) {
utils.logger.warn(
`DEFAULT CONFIG:\n${JSON.stringify(configManager.defaultConfig, null, 2)}`
logger.warn(
`DEFAULT CONFIG:\n${JSON.stringify(defaultConfig, null, 2)}`
);
utils.logger.log("debug", "Exiting.");
logger.log("debug", "Exiting.");
process.exit(0);
}

// config must be loaded after the logger is initialized
configManager.loadConfig();

loadConfig();
if (
"discordLogging" in configManager.config &&
(configManager.config.discordLogging.active ?? true)
"discordLogging" in config &&
(config.discordLogging.active ?? true)
) {
// Logger setup
const webhookRegex = new RegExp(
Expand All @@ -113,15 +114,15 @@ if (
);
const webhookParts = webhookRegex.exec(process.env.WINSTON_DISCORD_WEBHOOK);
if (!webhookParts) {
utils.logger.warn(
logger.warn(
"Invalid Discord Webhook provided. Not enabling Discord logging."
);
} else {
utils.logger.add(
logger.add(
new winstonDiscord({
id: webhookParts[1],
token: webhookParts[2],
level: configManager.config.discordLogging.level || "warn",
level: config.discordLogging.level || "warn",
format: winston.format.combine(
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
Expand Down Expand Up @@ -153,20 +154,20 @@ bot.on("ready", async () => {
// when loaded (ready event)
let desc;
let type;
if (!("activity" in configManager.config)) {
if (!("activity" in config)) {
desc = "nil";
type = "PLAYING";
} else {
desc = configManager.config.activity.description || "nil";
type = (configManager.config.activity.type || "PLAYING").toUpperCase();
desc = config.activity.description || "nil";
type = (config.activity.type || "PLAYING").toUpperCase();
}
bot.user.setActivity(desc, {
type: type,
});
pluginManager.load();
utils.logger.log("debug", "Starting Crons...");
logger.log("debug", "Starting Crons...");
pluginManager.startCrons();
utils.logger.log("debug", `${bot.user.username} is ready...`);
logger.log("debug", `${bot.user.username} is ready...`);
console.info(`${bot.user.username} is ready...`);
});

Expand All @@ -177,30 +178,30 @@ bot.on("messageCreate", async (message) => {
}

// Send message on to plugins
for (plugin of Object.values(utils.plugins.message)) {
for (const plugin of Object.values(plugins.message)) {
await plugin.processMessage(bot, message);
}

if (message.channel.type === "DM" && message.author.id != bot.user.id) {
//TODO
utils.reply({ content: "Hello!" }, message);
reply({ content: "Hello!" }, message);
return;
}

// if it is a command
if (message.content.charAt(0) === (configManager.config.prefix || "$")) {
if (message.content.charAt(0) === (config.prefix || "$")) {
// Send command on to plugins
const command = message.content.split(/\s/)[0].toLowerCase().slice(1);
const args = message.content
.substring(message.content.split(/\s/)[0].length)
.slice(1);
for (plugin of Object.values(utils.plugins.command)) {
for (const plugin of Object.values(plugins.command)) {
if (plugin.COMMANDS.includes(command)) {
await plugin.processCommand(command, args, bot, message);
return;
}
}
utils.logger.log("debug", `No handler found for command ${command}`);
logger.log("debug", `No handler found for command ${command}`);
return;
}
});
Expand All @@ -215,15 +216,15 @@ bot.on("messageReactionAdd", async (reaction, user) => {
await reaction.message.fetch();
}
} catch (error) {
utils.logger.error(
logger.error(
`Something went wrong when fetching the message: ${error}`
);
// Return as `reaction.message.author` may be undefined/null
return;
}
}

for (plugin of Object.values(utils.plugins.reaction)) {
for (const plugin of Object.values(plugins.reaction)) {
await plugin.processReaction(bot, reaction, user, true);
}
});
Expand All @@ -235,15 +236,15 @@ bot.on("messageReactionRemove", async (reaction, user) => {
try {
await reaction.fetch();
} catch (error) {
utils.logger.error(
logger.error(
`Something went wrong when fetching the message: ${error}`
);
// Return as `reaction.message.author` may be undefined/null
return;
}
}

for (plugin of Object.values(utils.plugins.reaction)) {
for (const plugin of Object.values(plugins.reaction)) {
await plugin.processReaction(bot, reaction, user, false);
}
});
Expand Down
51 changes: 26 additions & 25 deletions src/pluginManager.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const glob = require("glob");
const utils = require("./utils.js");
const configManager = require("./configManager.js");
import glob from 'glob';
import { logger, plugins } from './utils.js';
import { config } from './configManager.js'
const PLUGIN_FILES = "../plugins/*/main.js";

/**
Expand All @@ -10,16 +10,16 @@ const PLUGIN_FILES = "../plugins/*/main.js";
function load(bot) {
//TODO Integrate with Config to only load enabled plugins

utils.logger.log("debug", "Loading Plugins...");
logger.log("debug", "Loading Plugins...");

if (!("plugins" in configManager.config)) {
utils.logger.warn(
if (!("plugins" in config)) {
logger.warn(
"No plugin configuration found. Not attempting to load any plugins."
);
return;
}

glob.sync(PLUGIN_FILES).forEach((file) => {
glob.sync(PLUGIN_FILES).forEach(async (file) => {
let dash = file.split("/");
if (dash.length !== 4) {
return;
Expand All @@ -30,65 +30,66 @@ function load(bot) {
return;
}

let module = require(file);
let fullModule = await import(file);
let module = fullModule?.default;
let key = module.SLUG;
let loaded = false;

if (!(key in configManager.config.plugins)) {
utils.logger.log(
if (!(key in config.plugins)) {
logger.log(
"debug",
`Not loading Plugin "${module.NAME}", as it's not enabled in the config.`
);
return;
}

if (module?.processCommand) {
utils.plugins.command[key] = module;
plugins.command[key] = module;
loaded = true;
utils.logger.log("debug", `Loaded "${module.NAME}" as a Command Plugin`);
logger.log("debug", `Loaded "${module.NAME}" as a Command Plugin`);
}

if (module?.processMessage) {
utils.plugins.message[key] = module;
plugins.message[key] = module;
loaded = true;
utils.logger.log("debug", `Loaded "${module.NAME}" as a Message Plugin`);
logger.log("debug", `Loaded "${module.NAME}" as a Message Plugin`);
}

if (module?.processReaction) {
utils.plugins.reaction[key] = module;
plugins.reaction[key] = module;
loaded = true;
utils.logger.log("debug", `Loaded "${module.NAME}" as a Reaction Plugin`);
logger.log("debug", `Loaded "${module.NAME}" as a Reaction Plugin`);
}

if (module?.startCron) {
utils.plugins.cron[key] = module;
plugins.cron[key] = module;
loaded = true;
utils.logger.log("debug", `Loaded "${module.NAME}" as a Cron Plugin`);
logger.log("debug", `Loaded "${module.NAME}" as a Cron Plugin`);
}

if (loaded && module?.onLoad) {
utils.logger.log("debug", `Running "${module.NAME}" onLoad function...`);
logger.log("debug", `Running "${module.NAME}" onLoad function...`);
module.onLoad(bot);
}
});

utils.logger.log("debug", "All Plugins Loaded");
for (const [pluginType, list] of Object.entries(utils.plugins)) {
logger.log("debug", "All Plugins Loaded");
for (const [pluginType, list] of Object.entries(plugins)) {
const pluginNames = Object.values(list).map((p) => `"${p.NAME}"`);
utils.logger.log(
logger.log(
"debug",
`${pluginType} plugins: ${pluginNames.join(", ")}`
);
}
}

function startCrons() {
for (const plugin in utils.plugins.cron) {
utils.plugins.cron[plugin].startCron();
for (const plugin in plugins.cron) {
plugins.cron[plugin].startCron();
}
}

module.exports = {
export default {
load,
startCrons,
};
Loading

0 comments on commit d501691

Please sign in to comment.