From 6b2aae8dfbab9998abf535ec15e2b41b0c5f94a0 Mon Sep 17 00:00:00 2001 From: "Ean Milligan (Bastion)" Date: Thu, 5 May 2022 02:49:06 -0400 Subject: [PATCH] Update to use Log4Deno dep --- deps.ts | 2 + mod.ts | 32 ++++++++-------- src/api.ts | 53 +++++++++++++------------- src/commands/apiCmd.ts | 16 +++++--- src/commands/apiCmd/allowBlock.ts | 24 +++++++----- src/commands/apiCmd/apiHelp.ts | 12 ++++-- src/commands/apiCmd/deleteGuild.ts | 16 +++++--- src/commands/apiCmd/status.ts | 20 ++++++---- src/commands/emoji.ts | 18 +++++---- src/commands/help.ts | 14 ++++--- src/commands/info.ts | 14 ++++--- src/commands/ping.ts | 14 ++++--- src/commands/privacy.ts | 14 ++++--- src/commands/report.ts | 18 +++++---- src/commands/rip.ts | 14 ++++--- src/commands/roll.ts | 24 +++++++----- src/commands/roll/getModifiers.ts | 20 ++++++---- src/commands/rollHelp.ts | 14 ++++--- src/commands/stats.ts | 18 +++++---- src/commands/version.ts | 14 ++++--- src/intervals.ts | 11 +++--- src/solver.ts | 49 ++++++++++++------------ src/utils.enums.ts | 13 ------- src/utils.ts | 60 +----------------------------- 24 files changed, 256 insertions(+), 248 deletions(-) delete mode 100644 src/utils.enums.ts diff --git a/deps.ts b/deps.ts index 78b6f5d..668c0d2 100644 --- a/deps.ts +++ b/deps.ts @@ -16,3 +16,5 @@ export { Client } from "https://deno.land/x/mysql@v2.10.2/mod.ts"; export { Status, STATUS_TEXT } from "https://deno.land/std@0.137.0/http/http_status.ts"; export { nanoid } from "https://deno.land/x/nanoid@v3.0.0/mod.ts"; + +export { LogTypes as LT, initLog, log } from "https://raw.githubusercontent.com/Burn-E99/Log4Deno/V1.1.0/mod.ts"; diff --git a/mod.ts b/mod.ts index cb7c33b..7c55cf6 100644 --- a/mod.ts +++ b/mod.ts @@ -13,15 +13,17 @@ import { sendMessage, cache, botId, DiscordActivityTypes, DiscordenoGuild, DiscordenoMessage, + + // Log4Deno deps + LT, initLog, log } from "./deps.ts"; import api from "./src/api.ts"; import commands from "./src/commands/_index.ts"; import intervals from "./src/intervals.ts"; import utils from "./src/utils.ts"; -import { LogTypes as LT } from "./src/utils.enums.ts"; // Initialize logging client with folder to use for logs, needs --allow-write set on Deno startup -utils.initLog("logs"); +initLog("logs", DEBUG); // Start up the Discord Bot startBot({ @@ -29,7 +31,7 @@ startBot({ intents: [Intents.GuildMessages, Intents.DirectMessages, Intents.Guilds], eventHandlers: { ready: () => { - utils.log(LT.INFO, `${config.name} Logged in!`); + log(LT.INFO, `${config.name} Logged in!`); editBotStatus({ activities: [{ name: "Booting up . . .", @@ -41,7 +43,7 @@ startBot({ // Interval to rotate the status text every 30 seconds to show off more commands setInterval(async () => { - utils.log(LT.LOG, "Changing bot status"); + log(LT.LOG, "Changing bot status"); try { // Wrapped in try-catch due to hard crash possible editBotStatus({ @@ -53,20 +55,20 @@ startBot({ status: "online" }); } catch (e) { - utils.log(LT.ERROR, `Failed to update status: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to update status: ${JSON.stringify(e)}`); } }, 30000); // Interval to update bot list stats every 24 hours - LOCALMODE ? utils.log(LT.INFO, "updateListStatistics not running") : setInterval(() => { - utils.log(LT.LOG, "Updating all bot lists statistics"); + LOCALMODE ? log(LT.INFO, "updateListStatistics not running") : setInterval(() => { + log(LT.LOG, "Updating all bot lists statistics"); intervals.updateListStatistics(botId, cache.guilds.size); }, 86400000); // setTimeout added to make sure the startup message does not error out setTimeout(() => { LOCALMODE && editBotNickname(config.devServer, `LOCAL - ${config.name}`); - LOCALMODE ? utils.log(LT.INFO, "updateListStatistics not running") : intervals.updateListStatistics(botId, cache.guilds.size); + LOCALMODE ? log(LT.INFO, "updateListStatistics not running") : intervals.updateListStatistics(botId, cache.guilds.size); editBotStatus({ activities: [{ name: "Booting Complete", @@ -76,23 +78,23 @@ startBot({ status: "online" }); sendMessage(config.logChannel, `${config.name} has started, running version ${config.version}.`).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`); }); }, 1000); }, guildCreate: (guild: DiscordenoGuild) => { - utils.log(LT.LOG, `Handling joining guild ${JSON.stringify(guild)}`); + log(LT.LOG, `Handling joining guild ${JSON.stringify(guild)}`); sendMessage(config.logChannel, `New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`); }); }, guildDelete: (guild: DiscordenoGuild) => { - utils.log(LT.LOG, `Handling leaving guild ${JSON.stringify(guild)}`); + log(LT.LOG, `Handling leaving guild ${JSON.stringify(guild)}`); sendMessage(config.logChannel, `I have been removed from: ${guild.name} (id: ${guild.id}).`).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`); }); }, - debug: dmsg => utils.log(LT.LOG, `Debug Message | ${JSON.stringify(dmsg)}`), + debug: dmsg => log(LT.LOG, `Debug Message | ${JSON.stringify(dmsg)}`), messageCreate: (message: DiscordenoMessage) => { // Ignore all other bots if (message.isBot) return; @@ -100,7 +102,7 @@ startBot({ // Ignore all messages that are not commands if (message.content.indexOf(config.prefix) !== 0) return; - utils.log(LT.LOG, `Handling message ${JSON.stringify(message)}`); + log(LT.LOG, `Handling message ${JSON.stringify(message)}`); // Split into standard command + args format const args = message.content.slice(config.prefix.length).trim().split(/[ \n]+/g); diff --git a/src/api.ts b/src/api.ts index 4d666a4..4918e92 100644 --- a/src/api.ts +++ b/src/api.ts @@ -13,13 +13,14 @@ import { Status, STATUS_TEXT, // nanoid deps - nanoid + nanoid, + + // Log4Deno deps + LT, log } from "../deps.ts"; import { dbClient, queries } from "./db.ts"; import solver from "./solver.ts"; -import { LogTypes as LT } from "./utils.enums.ts"; -import utils from "./utils.ts"; import { generateApiKeyEmail, generateApiDeleteEmail, generateDMFailed } from "./constantCmds.ts"; @@ -30,7 +31,7 @@ import config from "../config.ts"; // start initializes and runs the entire API for the bot const start = async (): Promise => { const server = Deno.listen({ port: config.api.port }); - utils.log(LT.INFO, `HTTP api running at: http://localhost:${config.api.port}/`); + log(LT.INFO, `HTTP api running at: http://localhost:${config.api.port}/`); // rateLimitTime holds all users with the last time they started a rate limit timer const rateLimitTime = new Map(); @@ -43,7 +44,7 @@ const start = async (): Promise => { const httpConn = Deno.serveHttp(conn); for await (const requestEvent of httpConn) { const request = requestEvent.request; - utils.log(LT.LOG, `Handling request: ${JSON.stringify(request)}`); + log(LT.LOG, `Handling request: ${JSON.stringify(request)}`); // Check if user is authenticated to be using this API let authenticated = false; let rateLimited = false; @@ -96,7 +97,7 @@ const start = async (): Promise => { const query = new Map(); if (tempQ !== undefined) { tempQ.split("&").forEach((e: string) => { - utils.log(LT.LOG, `Breaking down request query: ${request} ${e}`); + log(LT.LOG, `Breaking down request query: ${request} ${e}`); const [option, params] = e.split("="); query.set(option.toLowerCase(), params); }); @@ -118,7 +119,7 @@ const start = async (): Promise => { // Insert new key/user pair into the db await dbClient.execute("INSERT INTO all_keys(userid,apiKey) values(?,?)", [apiUserid, newKey]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -149,7 +150,7 @@ const start = async (): Promise => { // Get all channels userid has authorized const dbAllowedChannelQuery = await dbClient.query("SELECT * FROM allowed_channels WHERE userid = ?", [apiUserid]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -216,7 +217,7 @@ const start = async (): Promise => { // Always log API rolls for abuse detection dbClient.execute(queries.insertRollLogCmd(1, 1), [originalCommand, "EmptyInput", null]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); }); break; } @@ -227,7 +228,7 @@ const start = async (): Promise => { // Always log API rolls for abuse detection dbClient.execute(queries.insertRollLogCmd(1, 1), [originalCommand, "BadOrder", null]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); }); break; } @@ -248,7 +249,7 @@ const start = async (): Promise => { // Always log API rolls for abuse detection dbClient.execute(queries.insertRollLogCmd(1, 1), [originalCommand, returnmsg.errorCode, null]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); }); break; } else { @@ -278,7 +279,7 @@ const start = async (): Promise => { // Always log API rolls for abuse detection dbClient.execute(queries.insertRollLogCmd(1, 1), [originalCommand, "NoGMsSent", null]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); }); break; } @@ -286,7 +287,7 @@ const start = async (): Promise => { // Make a new return line to be sent to the roller let normalText = `${apiPrefix}<@${query.get("user")}>${returnmsg.line1}\nResults have been messaged to the following GMs: `; gms.forEach(e => { - utils.log(LT.LOG, `Appending GM ${e} to roll text`); + log(LT.LOG, `Appending GM ${e} to roll text`); normalText += `<@${e}> `; }); @@ -320,7 +321,7 @@ const start = async (): Promise => { // And message the full details to each of the GMs, alerting roller of every GM that could not be messaged gms.forEach(async e => { - utils.log(LT.LOG, `Messaging GM ${e} roll results`); + log(LT.LOG, `Messaging GM ${e} roll results`); // Attempt to DM the GMs and send a warning if it could not DM a GM await sendDirectMessage(BigInt(e), newMessage).catch(async () => { const failedSend = generateDMFailed(e); @@ -341,7 +342,7 @@ const start = async (): Promise => { // Always log API rolls for abuse detection dbClient.execute(queries.insertRollLogCmd(1, 0), [originalCommand, returnText, ((typeof m === "object") ? m.id : null)]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); }); // Handle closing the request out @@ -386,7 +387,7 @@ const start = async (): Promise => { // If enabled, log rolls so we can verify the bots math dbClient.execute(queries.insertRollLogCmd(1, 0), [originalCommand, returnText, ((typeof m === "object") ? m.id : null)]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); }); // Handle closing the request out @@ -399,7 +400,7 @@ const start = async (): Promise => { } } catch (err) { // Handle any errors we missed - utils.log(LT.ERROR, `Unhandled Error: ${JSON.stringify(err)}`); + log(LT.ERROR, `Unhandled Error: ${JSON.stringify(err)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); } } else { @@ -428,7 +429,7 @@ const start = async (): Promise => { // Insert new user/channel pair into the db await dbClient.execute("INSERT INTO allowed_channels(userid,channelid) values(?,?)", [apiUserid, BigInt(query.get("channel") || "0")]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -487,7 +488,7 @@ const start = async (): Promise => { // Execute the DB modification await dbClient.execute("UPDATE all_keys SET ?? = ? WHERE userid = ?", [key, value, apiUserid]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -527,7 +528,7 @@ const start = async (): Promise => { // Execute the DB modification await dbClient.execute("UPDATE allowed_channels SET banned = ? WHERE userid = ? AND channelid = ?", [value, apiUserid, BigInt(query.get("channel") || "0")]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -567,7 +568,7 @@ const start = async (): Promise => { // Update the requested entry await dbClient.execute("UPDATE allowed_channels SET active = ? WHERE userid = ? AND channelid = ?", [value, apiUserid, BigInt(query.get("channel") || "0")]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -607,7 +608,7 @@ const start = async (): Promise => { let erroredOut = false; await dbClient.execute("DELETE FROM allowed_channels WHERE userid = ?", [apiUserid]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -616,7 +617,7 @@ const start = async (): Promise => { } await dbClient.execute("DELETE FROM all_keys WHERE userid = ?", [apiUserid]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -639,7 +640,7 @@ const start = async (): Promise => { // Execute the DB modification await dbClient.execute("UPDATE all_keys SET deleteCode = ? WHERE userid = ?", [deleteCode, apiUserid]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); @@ -693,7 +694,7 @@ const start = async (): Promise => { const query = new Map(); if (tempQ !== undefined) { tempQ.split("&").forEach((e: string) => { - utils.log(LT.LOG, `Parsing request query #2 ${request} ${e}`); + log(LT.LOG, `Parsing request query #2 ${request} ${e}`); const [option, params] = e.split("="); query.set(option.toLowerCase(), params); }); @@ -714,7 +715,7 @@ const start = async (): Promise => { // Insert new key/user pair into the db await dbClient.execute("INSERT INTO all_keys(userid,apiKey,email) values(?,?,?)", [BigInt(query.get("user") || "0"), newKey, (query.get("email") || "").toLowerCase()]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`); requestEvent.respondWith(new Response(STATUS_TEXT.get(Status.InternalServerError), { status: Status.InternalServerError })); erroredOut = true; }); diff --git a/src/commands/apiCmd.ts b/src/commands/apiCmd.ts index cfc9070..4eefcae 100644 --- a/src/commands/apiCmd.ts +++ b/src/commands/apiCmd.ts @@ -1,14 +1,18 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage, hasGuildPermissions } from "../../deps.ts"; +import { + // Discordeno deps + DiscordenoMessage, hasGuildPermissions, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import apiCommands from "./apiCmd/_apiIndex.ts"; -import utils from "../utils.ts"; import { constantCmds } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const api = async (message: DiscordenoMessage, args: string[]) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("api");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); // Local apiArg in lowercase @@ -17,7 +21,7 @@ export const api = async (message: DiscordenoMessage, args: string[]) => { // Alert users who DM the bot that this command is for guilds only if (message.guildId === 0n) { message.send(constantCmds.apiGuildOnly).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); return; } @@ -49,7 +53,7 @@ export const api = async (message: DiscordenoMessage, args: string[]) => { } } else { message.send(constantCmds.apiPermError).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); } }; diff --git a/src/commands/apiCmd/allowBlock.ts b/src/commands/apiCmd/allowBlock.ts index adf3c55..1ae3df4 100644 --- a/src/commands/apiCmd/allowBlock.ts +++ b/src/commands/apiCmd/allowBlock.ts @@ -1,14 +1,18 @@ import { dbClient } from "../../db.ts"; -import { DiscordenoMessage } from "../../../deps.ts"; -import utils from "../../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../../deps.ts"; import { generateApiFailed, generateApiSuccess } from "../../constantCmds.ts"; -import { LogTypes as LT } from "../../utils.enums.ts"; export const allowBlock = async (message: DiscordenoMessage, apiArg: string) => { const guildQuery = await dbClient.query(`SELECT guildid FROM allowed_guilds WHERE guildid = ?`, [message.guildId]).catch(e0 => { - utils.log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e0)}`); + log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e0)}`); message.send(generateApiFailed(apiArg)).catch(e1 => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); }); return; }); @@ -16,24 +20,24 @@ export const allowBlock = async (message: DiscordenoMessage, apiArg: string) => if (guildQuery.length === 0) { // Since guild is not in our DB, add it in await dbClient.execute(`INSERT INTO allowed_guilds(guildid,active) values(?,?)`, [BigInt(message.guildId), ((apiArg === "allow" || apiArg === "enable") ? 1 : 0)]).catch(e0 => { - utils.log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e0)}`); + log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e0)}`); message.send(generateApiFailed(apiArg)).catch(e1 => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); }); return; }); } else { // Since guild is in our DB, update it await dbClient.execute(`UPDATE allowed_guilds SET active = ? WHERE guildid = ?`, [((apiArg === "allow" || apiArg === "enable") ? 1 : 0), BigInt(message.guildId)]).catch(e0 => { - utils.log(LT.ERROR, `Failed to update DB: ${JSON.stringify(e0)}`); + log(LT.ERROR, `Failed to update DB: ${JSON.stringify(e0)}`); message.send(generateApiFailed(apiArg)).catch(e1 => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); }); return; }); } // We won't get here if there's any errors, so we know it has bee successful, so report as such message.send(generateApiSuccess(apiArg)).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/apiCmd/apiHelp.ts b/src/commands/apiCmd/apiHelp.ts index bdf6f0b..3bd6009 100644 --- a/src/commands/apiCmd/apiHelp.ts +++ b/src/commands/apiCmd/apiHelp.ts @@ -1,10 +1,14 @@ -import { DiscordenoMessage } from "../../../deps.ts"; -import utils from "../../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../../deps.ts"; import { constantCmds } from "../../constantCmds.ts"; -import { LogTypes as LT } from "../../utils.enums.ts"; export const help = (message: DiscordenoMessage) => { message.send(constantCmds.apiHelp).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/apiCmd/deleteGuild.ts b/src/commands/apiCmd/deleteGuild.ts index 3d54fc6..c72cf8b 100644 --- a/src/commands/apiCmd/deleteGuild.ts +++ b/src/commands/apiCmd/deleteGuild.ts @@ -1,20 +1,24 @@ import { dbClient } from "../../db.ts"; -import { DiscordenoMessage } from "../../../deps.ts"; -import utils from "../../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../../deps.ts"; import { constantCmds } from "../../constantCmds.ts"; -import { LogTypes as LT } from "../../utils.enums.ts"; export const deleteGuild = async (message: DiscordenoMessage) => { await dbClient.execute(`DELETE FROM allowed_guilds WHERE guildid = ?`, [message.guildId]).catch(e0 => { - utils.log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e0)}`); + log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e0)}`); message.send(constantCmds.apiDeleteFail).catch(e1 => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); }); return; }); // We won't get here if there's any errors, so we know it has bee successful, so report as such message.send(constantCmds.apiRemoveGuild).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/apiCmd/status.ts b/src/commands/apiCmd/status.ts index 553d536..fd33ee1 100644 --- a/src/commands/apiCmd/status.ts +++ b/src/commands/apiCmd/status.ts @@ -1,15 +1,19 @@ import { dbClient } from "../../db.ts"; -import { DiscordenoMessage } from "../../../deps.ts"; -import utils from "../../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../../deps.ts"; import { constantCmds, generateApiStatus } from "../../constantCmds.ts"; -import { LogTypes as LT } from "../../utils.enums.ts"; export const status = async (message: DiscordenoMessage) => { // Get status of guild from the db const guildQuery = await dbClient.query(`SELECT active, banned FROM allowed_guilds WHERE guildid = ?`, [message.guildId]).catch(e0 => { - utils.log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e0)}`); + log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e0)}`); message.send(constantCmds.apiStatusFail).catch(e1 => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e1)}`); }); return; }); @@ -19,17 +23,17 @@ export const status = async (message: DiscordenoMessage) => { // Check if guild is banned from using API and return appropriate message if (guildQuery[0].banned) { message.send(generateApiStatus(true, false)).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); } else { message.send(generateApiStatus(false, guildQuery[0].active)).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); } } else { // Guild is not in DB, therefore they are blocked message.send(generateApiStatus(false, false)).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); } }; diff --git a/src/commands/emoji.ts b/src/commands/emoji.ts index 46f99aa..049dde1 100644 --- a/src/commands/emoji.ts +++ b/src/commands/emoji.ts @@ -1,8 +1,12 @@ import config from "../../config.ts"; import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { EmojiConf } from "../mod.d.ts"; const allEmojiAliases: string[] = []; @@ -16,22 +20,22 @@ export const emoji = (message: DiscordenoMessage, command: string) => { if (allEmojiAliases.indexOf(command)) { // Start looping thru the possible emojis config.emojis.some((emoji: EmojiConf) => { - utils.log(LT.LOG, `Checking if command was emoji ${JSON.stringify(emoji)}`); + log(LT.LOG, `Checking if command was emoji ${JSON.stringify(emoji)}`); // If a match gets found if (emoji.aliases.indexOf(command || "") > -1) { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("emojis");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); // Send the needed emoji1 message.send(`<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}>`).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); // And attempt to delete if needed if (emoji.deleteSender) { message.delete().catch(e => { - utils.log(LT.WARN, `Failed to delete message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.WARN, `Failed to delete message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); } return true; diff --git a/src/commands/help.ts b/src/commands/help.ts index 2229528..858ee64 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -1,16 +1,20 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { constantCmds } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const help = (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("help");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); message.send(constantCmds.help).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/info.ts b/src/commands/info.ts index 53615d3..5cb34ed 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -1,16 +1,20 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { constantCmds } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const info = (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("info");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); message.send(constantCmds.info).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/ping.ts b/src/commands/ping.ts index bdb0bb5..01de28b 100644 --- a/src/commands/ping.ts +++ b/src/commands/ping.ts @@ -1,13 +1,17 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { generatePing } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const ping = async (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("ping");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); // Calculates ping between sending a message and editing it, giving a nice round-trip latency. @@ -15,6 +19,6 @@ export const ping = async (message: DiscordenoMessage) => { const m = await message.send(generatePing(-1)); m.edit(generatePing(m.timestamp - message.timestamp)); } catch (e) { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); } }; diff --git a/src/commands/privacy.ts b/src/commands/privacy.ts index 344a2a4..7548249 100644 --- a/src/commands/privacy.ts +++ b/src/commands/privacy.ts @@ -1,16 +1,20 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { constantCmds } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const privacy = (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("privacy");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); message.send(constantCmds.privacy).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/report.ts b/src/commands/report.ts index cbadbbe..4d6778b 100644 --- a/src/commands/report.ts +++ b/src/commands/report.ts @@ -1,26 +1,30 @@ import config from "../../config.ts"; import { dbClient } from "../db.ts"; -import { DiscordenoMessage, sendMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, sendMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { constantCmds, generateReport } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const report = (message: DiscordenoMessage, args: string[]) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("report");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); if (args.join(" ")) { sendMessage(config.reportChannel, generateReport(args.join(" "))).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); message.send(constantCmds.report).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); } else { message.send(constantCmds.reportFail).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); } }; diff --git a/src/commands/rip.ts b/src/commands/rip.ts index 7b27f7d..6502198 100644 --- a/src/commands/rip.ts +++ b/src/commands/rip.ts @@ -1,16 +1,20 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { constantCmds } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const rip = (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("rip");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); message.send(constantCmds.rip).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/roll.ts b/src/commands/roll.ts index 31c1af4..9e1ebf2 100644 --- a/src/commands/roll.ts +++ b/src/commands/roll.ts @@ -1,23 +1,27 @@ import config from "../../config.ts"; import { DEVMODE } from "../../flags.ts"; import { dbClient, queries } from "../db.ts"; -import { DiscordenoMessage, sendDirectMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, sendDirectMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import solver from "../solver.ts"; import { constantCmds, generateDMFailed } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; import rollFuncs from "./roll/_rollIndex.ts"; export const roll = async (message: DiscordenoMessage, args: string[], command: string) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("roll");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); // If DEVMODE is on, only allow this command to be used in the devServer if (DEVMODE && message.guildId !== config.devServer) { message.send(constantCmds.indev).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); return; } @@ -50,7 +54,7 @@ export const roll = async (message: DiscordenoMessage, args: string[], command: if (DEVMODE && config.logRolls) { // If enabled, log rolls so we can verify the bots math dbClient.execute(queries.insertRollLogCmd(0, 1), [originalCommand, returnmsg.errorCode, m.id]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); }); } return; @@ -72,7 +76,7 @@ export const roll = async (message: DiscordenoMessage, args: string[], command: // And message the full details to each of the GMs, alerting roller of every GM that could not be messaged modifiers.gms.forEach(async e => { - utils.log(LT.LOG, `Messaging GM ${e}`); + log(LT.LOG, `Messaging GM ${e}`); // If its too big, collapse it into a .txt file and send that instead. const b = await new Blob([returnText as BlobPart], { "type": "text" }); @@ -103,7 +107,7 @@ export const roll = async (message: DiscordenoMessage, args: string[], command: if (DEVMODE && config.logRolls) { // If enabled, log rolls so we can verify the bots math dbClient.execute(queries.insertRollLogCmd(0, 0), [originalCommand, returnText, m.id]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); }); } } else { @@ -136,11 +140,11 @@ export const roll = async (message: DiscordenoMessage, args: string[], command: if (DEVMODE && config.logRolls) { // If enabled, log rolls so we can verify the bots math dbClient.execute(queries.insertRollLogCmd(0, 0), [originalCommand, returnText, m.id]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); }); } } } catch (e) { - utils.log(LT.ERROR, `Undandled Error: ${JSON.stringify(e)}`); + log(LT.ERROR, `Undandled Error: ${JSON.stringify(e)}`); } }; diff --git a/src/commands/roll/getModifiers.ts b/src/commands/roll/getModifiers.ts index 29eeb9c..1fc6d7c 100644 --- a/src/commands/roll/getModifiers.ts +++ b/src/commands/roll/getModifiers.ts @@ -1,10 +1,14 @@ import config from "../../../config.ts"; import { DEVMODE } from "../../../flags.ts"; import { dbClient, queries } from "../../db.ts"; -import { DiscordenoMessage } from "../../../deps.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../../deps.ts"; import { generateRollError } from "../../constantCmds.ts"; -import utils from "../../utils.ts"; -import { LogTypes as LT } from "../../utils.enums.ts"; import { RollModifiers } from "../../mod.d.ts"; export const getModifiers = (m: DiscordenoMessage, args: string[], command: string, originalCommand: string): RollModifiers => { @@ -22,7 +26,7 @@ export const getModifiers = (m: DiscordenoMessage, args: string[], command: stri // Check if any of the args are command flags and pull those out into the modifiers object for (let i = 0; i < args.length; i++) { - utils.log(LT.LOG, `Checking ${command}${args.join(" ")} for command modifiers ${i}`); + log(LT.LOG, `Checking ${command}${args.join(" ")} for command modifiers ${i}`); switch (args[i].toLowerCase()) { case "-nd": modifiers.noDetails = true; @@ -53,7 +57,7 @@ export const getModifiers = (m: DiscordenoMessage, args: string[], command: stri // -gm is a little more complex, as we must get all of the GMs that need to be DMd while (((i + 1) < args.length) && args[i + 1].startsWith("<@")) { - utils.log(LT.LOG, `Finding all GMs, checking args ${JSON.stringify(args)}`); + log(LT.LOG, `Finding all GMs, checking args ${JSON.stringify(args)}`); // Keep looping thru the rest of the args until one does not start with the discord mention code modifiers.gms.push(args[i + 1].replace(/[!]/g, "")); args.splice((i + 1), 1); @@ -65,7 +69,7 @@ export const getModifiers = (m: DiscordenoMessage, args: string[], command: stri if (DEVMODE && config.logRolls) { // If enabled, log rolls so we can verify the bots math dbClient.execute(queries.insertRollLogCmd(0, 1), [originalCommand, "NoGMsFound", m.id]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); }); } return modifiers; @@ -86,7 +90,7 @@ export const getModifiers = (m: DiscordenoMessage, args: string[], command: stri if (DEVMODE && config.logRolls) { // If enabled, log rolls so we can verify the bots math dbClient.execute(queries.insertRollLogCmd(0, 1), [originalCommand, "NoOrderFound", m.id]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); }); } return modifiers; @@ -109,7 +113,7 @@ export const getModifiers = (m: DiscordenoMessage, args: string[], command: stri if (DEVMODE && config.logRolls) { // If enabled, log rolls so we can verify the bots math dbClient.execute(queries.insertRollLogCmd(0, 1), [originalCommand, "MaxAndNominal", m.id]).catch(e => { - utils.log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to insert into DB: ${JSON.stringify(e)}`); }); } return modifiers; diff --git a/src/commands/rollHelp.ts b/src/commands/rollHelp.ts index 5406098..6adc211 100644 --- a/src/commands/rollHelp.ts +++ b/src/commands/rollHelp.ts @@ -1,16 +1,20 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { constantCmds } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const rollHelp = (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("rollhelp");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); message.send(constantCmds.rollHelp).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/stats.ts b/src/commands/stats.ts index 2917961..7427e09 100644 --- a/src/commands/stats.ts +++ b/src/commands/stats.ts @@ -1,21 +1,25 @@ import { dbClient } from "../db.ts"; -import { cache, cacheHandlers, DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + cache, cacheHandlers, DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { generateStats } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const stats = async (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("stats");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); // Calculate how many times commands have been run const rollQuery = await dbClient.query(`SELECT count FROM command_cnt WHERE command = "roll";`).catch(e => { - utils.log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e)}`); }); const totalQuery = await dbClient.query(`SELECT SUM(count) as count FROM command_cnt;`).catch(e => { - utils.log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to query DB: ${JSON.stringify(e)}`); }); const rolls = BigInt(rollQuery[0].count); const total = BigInt(totalQuery[0].count); @@ -24,6 +28,6 @@ export const stats = async (message: DiscordenoMessage) => { const cachedChannels = await cacheHandlers.size("channels"); const cachedMembers = await cacheHandlers.size("members"); message.send(generateStats(cachedGuilds + cache.dispatchedGuildIds.size, cachedChannels + cache.dispatchedChannelIds.size, cachedMembers, rolls, total - rolls)).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/commands/version.ts b/src/commands/version.ts index 0b98f59..5b9221d 100644 --- a/src/commands/version.ts +++ b/src/commands/version.ts @@ -1,16 +1,20 @@ import { dbClient } from "../db.ts"; -import { DiscordenoMessage } from "../../deps.ts"; -import utils from "../utils.ts"; +import { + // Discordeno deps + DiscordenoMessage, + + // Log4Deno deps + LT, log +} from "../../deps.ts"; import { constantCmds } from "../constantCmds.ts"; -import { LogTypes as LT } from "../utils.enums.ts"; export const version = (message: DiscordenoMessage) => { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("version");`).catch(e => { - utils.log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); message.send(constantCmds.version).catch(e => { - utils.log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); + log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); }; diff --git a/src/intervals.ts b/src/intervals.ts index 6361347..2bcd9a4 100644 --- a/src/intervals.ts +++ b/src/intervals.ts @@ -6,10 +6,11 @@ import { // Discordeno deps - cache, cacheHandlers + cache, cacheHandlers, + + // Log4Deno deps + LT, log } from "../deps.ts"; -import { LogTypes as LT } from "./utils.enums.ts"; -import utils from "./utils.ts"; import config from "../config.ts"; @@ -41,7 +42,7 @@ const getRandomStatus = async (): Promise => { // Sends the current server count to all bot list sites we are listed on const updateListStatistics = (botID: bigint, serverCount: number): void => { config.botLists.forEach(async e => { - utils.log(LT.LOG, `Updating statistics for ${JSON.stringify(e)}`) + log(LT.LOG, `Updating statistics for ${JSON.stringify(e)}`) if (e.enabled) { const tempHeaders = new Headers(); tempHeaders.append(e.headers[0].header, e.headers[0].value); @@ -52,7 +53,7 @@ const updateListStatistics = (botID: bigint, serverCount: number): void => { "headers": tempHeaders, "body": JSON.stringify(e.body).replace('"?{server_count}"', serverCount.toString()) // ?{server_count} needs the "" removed from around it aswell to make sure its sent as a number }); - utils.log(LT.INFO, `Posted server count to ${e.name}. Results: ${JSON.stringify(response)}`); + log(LT.INFO, `Posted server count to ${e.name}. Results: ${JSON.stringify(response)}`); } }); }; diff --git a/src/solver.ts b/src/solver.ts index 271d45c..513e2ef 100644 --- a/src/solver.ts +++ b/src/solver.ts @@ -4,10 +4,13 @@ * December 21, 2020 */ +import { + // Log4Deno deps + LT, log +} from "../deps.ts"; + import config from "../config.ts"; import { RollSet, SolvedStep, SolvedRoll, ReturnData } from "./solver.d.ts"; -import { LogTypes as LT } from "./utils.enums.ts"; -import utils from "./utils.ts"; // MAXLOOPS determines how long the bot will attempt a roll // Default is 5000000 (5 million), which results in at most a 10 second delay before the bot calls the roll infinite or too complex @@ -62,7 +65,7 @@ const compareOrigidx = (a: RollSet, b: RollSet): number => { const escapeCharacters = (str: string, esc: string): string => { // Loop thru each esc char one at a time for (let i = 0; i < esc.length; i++) { - utils.log(LT.LOG, `Escaping character ${esc[i]} | ${str}, ${esc}`); + log(LT.LOG, `Escaping character ${esc[i]} | ${str}, ${esc}`); // Create a new regex to look for that char that needs replaced and escape it const temprgx = new RegExp(`[${esc[i]}]`, "g"); str = str.replace(temprgx, `\\${esc[i]}`); @@ -164,7 +167,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Loop until all remaining args are parsed while (remains.length > 0) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Parsing remains ${remains}`); + log(LT.LOG, `Handling roll ${rollStr} | Parsing remains ${remains}`); // Find the next number in the remains to be able to cut out the rule name let afterSepIdx = remains.search(/\d/); if (afterSepIdx < 0) { @@ -220,7 +223,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Configure CritScore for all numbers greater than or equal to tNum (this could happen multiple times, but why) rollConf.critScore.on = true; for (let i = tNum; i <= rollConf.dieSize; i++) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Parsing cs> ${i}`); + log(LT.LOG, `Handling roll ${rollStr} | Parsing cs> ${i}`); rollConf.critScore.range.push(i); } break; @@ -228,7 +231,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Configure CritScore for all numbers less than or equal to tNum (this could happen multiple times, but why) rollConf.critScore.on = true; for (let i = 0; i <= tNum; i++) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Parsing cs< ${i}`); + log(LT.LOG, `Handling roll ${rollStr} | Parsing cs< ${i}`); rollConf.critScore.range.push(i); } break; @@ -242,7 +245,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Configure CritFail for all numbers greater than or equal to tNum (this could happen multiple times, but why) rollConf.critFail.on = true; for (let i = tNum; i <= rollConf.dieSize; i++) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Parsing cf> ${i}`); + log(LT.LOG, `Handling roll ${rollStr} | Parsing cf> ${i}`); rollConf.critFail.range.push(i); } break; @@ -250,7 +253,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Configure CritFail for all numbers less than or equal to tNum (this could happen multiple times, but why) rollConf.critFail.on = true; for (let i = 0; i <= tNum; i++) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Parsing cf< ${i}`); + log(LT.LOG, `Handling roll ${rollStr} | Parsing cf< ${i}`); rollConf.critFail.range.push(i); } break; @@ -278,7 +281,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Since only one drop or keep option can be active, count how many are active to throw the right error let dkdkCnt = 0; [rollConf.drop.on, rollConf.keep.on, rollConf.dropHigh.on, rollConf.keepLow.on].forEach(e => { - utils.log(LT.LOG, `Handling roll ${rollStr} | Checking if drop/keep is on ${e}`); + log(LT.LOG, `Handling roll ${rollStr} | Checking if drop/keep is on ${e}`); if (e) { dkdkCnt++; } @@ -343,7 +346,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Initial rolling, not handling reroll or exploding here for (let i = 0; i < rollConf.dieCount; i++) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Initial rolling ${i} of ${JSON.stringify(rollConf)}`); + log(LT.LOG, `Handling roll ${rollStr} | Initial rolling ${i} of ${JSON.stringify(rollConf)}`); // If loopCount gets too high, stop trying to calculate infinity if (loopCount > MAXLOOPS) { throw new Error("MaxLoopsExceeded"); @@ -377,7 +380,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // If needed, handle rerolling and exploding dice now if (rollConf.reroll.on || rollConf.exploding) { for (let i = 0; i < rollSet.length; i++) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Handling rerolling and exploding ${JSON.stringify(rollSet[i])}`); + log(LT.LOG, `Handling roll ${rollStr} | Handling rerolling and exploding ${JSON.stringify(rollSet[i])}`); // If loopCount gets too high, stop trying to calculate infinity if (loopCount > MAXLOOPS) { throw new Error("MaxLoopsExceeded"); @@ -444,7 +447,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol let rerollCount = 0; if (rollConf.reroll.on) { for (let i = 0; i < rollSet.length; i++) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Setting originalIdx on ${JSON.stringify(rollSet[i])}`); + log(LT.LOG, `Handling roll ${rollStr} | Setting originalIdx on ${JSON.stringify(rollSet[i])}`); rollSet[i].origidx = i; if (rollSet[i].rerolled) { @@ -493,7 +496,7 @@ const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolean): Rol // Now its time to drop all dice needed let i = 0; while (dropCount > 0 && i < rollSet.length) { - utils.log(LT.LOG, `Handling roll ${rollStr} | Dropping dice ${dropCount} ${JSON.stringify(rollSet[i])}`); + log(LT.LOG, `Handling roll ${rollStr} | Dropping dice ${dropCount} ${JSON.stringify(rollSet[i])}`); // Skip all rolls that were rerolled if (!rollSet[i].rerolled) { rollSet[i].dropped = true; @@ -522,7 +525,7 @@ const formatRoll = (rollConf: string, maximiseRoll: boolean, nominalRoll: boolea // Loop thru all parts of the roll to document everything that was done to create the total roll tempRollSet.forEach(e => { - utils.log(LT.LOG, `Formatting roll ${rollConf} | ${JSON.stringify(e)}`); + log(LT.LOG, `Formatting roll ${rollConf} | ${JSON.stringify(e)}`); let preFormat = ""; let postFormat = ""; @@ -588,7 +591,7 @@ const fullSolver = (conf: (string | number | SolvedStep)[], wrapDetails: boolean // Evaluate all parenthesis while (conf.indexOf("(") > -1) { - utils.log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Looking for (`); + log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Looking for (`); // Get first open parenthesis const openParen = conf.indexOf("("); let closeParen = -1; @@ -596,7 +599,7 @@ const fullSolver = (conf: (string | number | SolvedStep)[], wrapDetails: boolean // Using nextParen to count the opening/closing parens, find the matching paren to openParen above for (let i = openParen; i < conf.length; i++) { - utils.log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Looking for matching ) openIdx: ${openParen} checking: ${i}`); + log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Looking for matching ) openIdx: ${openParen} checking: ${i}`); // If we hit an open, add one (this includes the openParen we start with), if we hit a close, subtract one if (conf[i] === "(") { nextParen++; @@ -639,10 +642,10 @@ const fullSolver = (conf: (string | number | SolvedStep)[], wrapDetails: boolean // Evaluate all EMMDAS by looping thru each teir of operators (exponential is the higehest teir, addition/subtraction the lowest) const allCurOps = [["^"], ["*", "/", "%"], ["+", "-"]]; allCurOps.forEach(curOps => { - utils.log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Evaluating ${JSON.stringify(curOps)}`); + log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Evaluating ${JSON.stringify(curOps)}`); // Iterate thru all operators/operands in the conf for (let i = 0; i < conf.length; i++) { - utils.log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Evaluating ${JSON.stringify(curOps)} | Checking ${JSON.stringify(conf[i])}`); + log(LT.LOG, `Evaluating roll ${JSON.stringify(conf)} | Evaluating ${JSON.stringify(curOps)} | Checking ${JSON.stringify(conf[i])}`); // Check if the current index is in the active teir of operators if (curOps.indexOf(conf[i].toString()) > -1) { // Grab the operands from before and after the operator @@ -773,7 +776,7 @@ const parseRoll = (fullCmd: string, localPrefix: string, localPostfix: string, m // Loop thru all roll/math ops for (let i = 0; i < sepRolls.length; i++) { - utils.log(LT.LOG, `Parsing roll ${fullCmd} | Working ${sepRolls[i]}`); + log(LT.LOG, `Parsing roll ${fullCmd} | Working ${sepRolls[i]}`); // Split the current iteration on the command postfix to separate the operation to be parsed and the text formatting after the opertaion const [tempConf, tempFormat] = sepRolls[i].split(localPostfix); @@ -783,7 +786,7 @@ const parseRoll = (fullCmd: string, localPrefix: string, localPostfix: string, m // Verify there are equal numbers of opening and closing parenthesis by adding 1 for opening parens and subtracting 1 for closing parens let parenCnt = 0; mathConf.forEach(e => { - utils.log(LT.LOG, `Parsing roll ${fullCmd} | Checking parenthesis balance ${e}`); + log(LT.LOG, `Parsing roll ${fullCmd} | Checking parenthesis balance ${e}`); if (e === "(") { parenCnt++; } else if (e === ")") { @@ -798,7 +801,7 @@ const parseRoll = (fullCmd: string, localPrefix: string, localPostfix: string, m // Evaluate all rolls into stepSolve format and all numbers into floats for (let i = 0; i < mathConf.length; i++) { - utils.log(LT.LOG, `Parsing roll ${fullCmd} | Evaluating rolls into mathable items ${JSON.stringify(mathConf[i])}`); + log(LT.LOG, `Parsing roll ${fullCmd} | Evaluating rolls into mathable items ${JSON.stringify(mathConf[i])}`); if (mathConf[i].toString().length === 0) { // If its an empty string, get it out of here mathConf.splice(i, 1); @@ -894,7 +897,7 @@ const parseRoll = (fullCmd: string, localPrefix: string, localPostfix: string, m // Fill out all of the details and results now tempReturnData.forEach(e => { - utils.log(LT.LOG, `Parsing roll ${fullCmd} | Making return text ${JSON.stringify(e)}`); + log(LT.LOG, `Parsing roll ${fullCmd} | Making return text ${JSON.stringify(e)}`); let preFormat = ""; let postFormat = ""; @@ -1013,7 +1016,7 @@ const parseRoll = (fullCmd: string, localPrefix: string, localPostfix: string, m errorMsg = "Error: Roll became undefined, one or more operands are not a roll or a number, check input"; break; default: - utils.log(LT.ERROR, `Undangled Error: ${errorName}, ${errorDetails}`); + log(LT.ERROR, `Undangled Error: ${errorName}, ${errorDetails}`); errorMsg = `Unhandled Error: ${solverError.message}\nCheck input and try again, if issue persists, please use \`${config.prefix}report\` to alert the devs of the issue`; break; } diff --git a/src/utils.enums.ts b/src/utils.enums.ts deleted file mode 100644 index 4e87094..0000000 --- a/src/utils.enums.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* The Artificer was built in memory of Babka - * With love, Ean - * - * December 21, 2020 - */ - -// enum for all possible console.log types -export enum LogTypes { - LOG = "log", - INFO = "info", - WARN = "warn", - ERROR = "error" -} \ No newline at end of file diff --git a/src/utils.ts b/src/utils.ts index 75bb93f..270c4d9 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -6,20 +6,9 @@ import { // Discordeno deps - sendMessage, - - // nanoid deps - nanoid + sendMessage } from "../deps.ts"; -import { DEBUG } from "../flags.ts"; -import { LogTypes } from "./utils.enums.ts"; - -// Constant initialized at runtime for consistent file names -let startDate: string; -let logFolder: string; -let initialized = false; - // ask(prompt) returns string // ask prompts the user at command line for message const ask = async (question: string, stdin = Deno.stdin, stdout = Deno.stdout): Promise => { @@ -104,49 +93,4 @@ const cmdPrompt = async (logChannel: bigint, botName: string): Promise => } }; -// initLog() returns nothing -// Handles ensuring the required directory structure is created -const initLog = (name: string): void => { - // Initialize the file name - startDate = new Date().toISOString().split("T")[0]; - logFolder = name; - const startupMessage = ` ---------------------------------------------------------------------------------------------------- ----------------------------------------- LOGGING STARTED ----------------------------------------- ------------------------------------- ${new Date().toISOString()} ------------------------------------- ----------------------------------------------------------------------------------------------------`; - - // Make all required folders if they are missing - const folders = ["combined", "traces"]; - Object.values(LogTypes).forEach(level => { - folders.push(level) - }); - - // Make each folder if its missing and insert the startup message - folders.forEach(level => { - Deno.mkdirSync(`./${logFolder}/${level}`, { recursive: true }); - Deno.writeTextFileSync(`./${logFolder}/${level}/${startDate}.log`, `${startupMessage}\n`, {append: true}); - }); - initialized = true; -}; - -// log(level, message) returns nothing -// Handles sending messages to console.log and sending a copy of the log to a file for review on crashes -const log = async (level: LogTypes, message: string, error = new Error()): Promise => { - const msgId = await nanoid(10); - const formattedMsg = `${new Date().toISOString()} | ${msgId} | ${level.padEnd(5)} | ${message}`; - const traceMsg = `${error.stack}` - // Default functionality of logging to console - if (level !== LogTypes.LOG || DEBUG) { - console[level](formattedMsg); - } - - // Logging to files for permanent info - if (initialized) { - await Deno.writeTextFile(`./${logFolder}/${level}/${startDate}.log`, `${formattedMsg}\n`, {append: true}); - await Deno.writeTextFile(`./${logFolder}/combined/${startDate}.log`, `${formattedMsg}\n`, {append: true}); - await Deno.writeTextFile(`./${logFolder}/traces/${startDate}.log`, `${formattedMsg}\n${traceMsg}\n\n`, {append: true}); - } -}; - -export default { cmdPrompt, initLog, log }; +export default { cmdPrompt };