From ecdc75354637a62892f19a2b5e1ecedfebfdfbde Mon Sep 17 00:00:00 2001 From: Brandyn Date: Sun, 18 Feb 2024 08:03:45 -0600 Subject: [PATCH] Add log controller, start work on log levels #13, add ability to switch between pokes and messages #16, add stuff that needs documented #20 --- index.js | 9 ++- src/actions/teamspeakClientConnected.js | 16 +++-- src/database.js | 3 +- src/discord.js | 48 ++++++++------- src/express.js | 26 +++++--- src/log.js | 81 +++++++++++++++++++++++++ src/teamspeak.js | 24 ++++++-- 7 files changed, 164 insertions(+), 43 deletions(-) create mode 100644 src/log.js diff --git a/index.js b/index.js index 97ca6bd..7093f68 100644 --- a/index.js +++ b/index.js @@ -5,6 +5,7 @@ const discord = require("./src/discord"); const _ = require("lodash"); const teamspeakClientConnected = require("./src/actions/teamspeakClientConnected"); const synchroniseUser = require("./src/actions/synchronizeUser"); +const log = require("./src/log"); // Initialize Connections to Servers async function initialize() { @@ -17,8 +18,12 @@ async function initialize() { }); discord.client.on("guildMemberUpdate", (member) => { - console.log("Guild Member Update"); - synchroniseUser(member.guild.members.cache.get(member.id)); + log.info("Discord User Updated - $discordName - $discordId", { + discordName: member.user.username, + discordId: member.id, + }); + r; + synchroniseUser(member); }); } diff --git a/src/actions/teamspeakClientConnected.js b/src/actions/teamspeakClientConnected.js index a93b403..3cb489d 100644 --- a/src/actions/teamspeakClientConnected.js +++ b/src/actions/teamspeakClientConnected.js @@ -5,6 +5,12 @@ const db = require("../database"); const synchronizeUser = require("./synchronizeUser"); const discord = require("../discord"); +function contactUser(tsid, message) { + config.teamspeak.usePokes + ? teamspeak.sendPokeToClient(tsid, message) + : teamspeak.sendMessageToClient(tsid, message); +} + module.exports = async function (event) { return new Promise(async (resolve, reject) => { var tsid = event.client.propcache.clientUniqueIdentifier; @@ -18,25 +24,25 @@ module.exports = async function (event) { } } else { if (!config.discord.useOAuth) { - await teamspeak.sendMessageToClient( + await contactUser( event.client, config.teamspeak.welcomeMessageText ? config.teamspeak.welcomeMessageText : "Hello! You seem to be new here. Please connect your discord account by logging in with the link below." ); - await teamspeak.sendMessageToClient( + await contactUser( event.client, `Please use the /register command in the ${config.discord.commandChannelName} channel in discord with the following teamspeak-id` ); - await teamspeak.sendMessageToClient(event.client, `${tsid}`); + await contactUser(event.client, `${tsid}`); } else { - await teamspeak.sendMessageToClient( + await contactUser( event.client, config.teamspeak.welcomeMessageText ? config.teamspeak.welcomeMessageText : "Hello! You seem to be new here. Please connect your discord account by logging in with the link below." ); - await teamspeak.sendMessageToClient( + await contactUser( event.client, `${ config.web.clientBaseUrl diff --git a/src/database.js b/src/database.js index 8d47b2c..6fefc16 100644 --- a/src/database.js +++ b/src/database.js @@ -1,5 +1,6 @@ const config = require("./config"); const sqlite3 = require("sqlite3").verbose(); +const log = require("./log"); class Database { constructor() { @@ -148,7 +149,7 @@ class Database { VALUES ('${discordID}','${tsID}')`, (err) => { if (err) { - console.log(err); + log.error(err); reject(err); } resolve(); diff --git a/src/discord.js b/src/discord.js index 8772765..49102a8 100644 --- a/src/discord.js +++ b/src/discord.js @@ -1,4 +1,5 @@ const config = require("./config"); +const log = require("./log"); const { Client, Collection, @@ -25,8 +26,9 @@ class Discord { if ("data" in command && "execute" in command) { this.client.commands.set(command.data.name, command); } else { - console.log( - `[WARNING] The command ${command} is missing a required "data" or "execute" property.` + log.debug( + `[WARNING] The command $command is missing a required "data" or "execute" property.`, + { command: command } ); } } @@ -37,7 +39,7 @@ class Discord { this.client.login(config.discord.token); this.client.on("ready", () => { this.client.intents; - console.log("Discord Bot Connected"); + log.system("Discord Bot Connected"); this.regsiterCommands(); resolve(); }); @@ -58,29 +60,29 @@ class Discord { } }); - // this.client.on(Events.Debug, (message) => { - // console.log(message); - // }); + this.client.on(Events.Debug, (message) => { + log.debug(message); + }); - // this.client.on(Events.Error, (message) => { - // console.log(message); - // }); + this.client.on(Events.Error, (message) => { + log.error(message); + }); - // this.client.on(Events.Warn, (message) => { - // console.log(message); - // }); + this.client.on(Events.Warn, (message) => { + log.debug(message); + }); - // this.client.on(Events.GuildUnavailable, (message) => { - // console.log(message); - // }); + this.client.on(Events.GuildUnavailable, (message) => { + log.error(message); + }); - // this.client.on(Events.GuildRoleUpdate, (message) => { - // console.log(message); - // }); + this.client.on(Events.GuildRoleUpdate, (message) => { + log.verbose(message); + }); - // this.client.on(Events.Raw, (message) => { - // console.log(message); - // }); + this.client.on(Events.Raw, (message) => { + log.verbose(message); + }); }); } @@ -103,7 +105,7 @@ class Discord { { body: devJsonCommands } ); - console.log( + log.system( `Successfully reloaded ${data.length} dev application (/) commands.` ); @@ -112,7 +114,7 @@ class Discord { { body: jsonCommands } ); - console.log( + log.debug( `Successfully reloaded ${data2.length} public application (/) commands.` ); } diff --git a/src/express.js b/src/express.js index 0f33758..d4d22bb 100644 --- a/src/express.js +++ b/src/express.js @@ -9,6 +9,7 @@ const db = require("./database"); const discord = require("./discord"); const synchronizeUser = require("./actions/synchronizeUser"); const config = require("./config"); +const log = require("./log"); const app = express(); const port = config.web.port; @@ -82,9 +83,9 @@ app.get( let guild = discord.client.guilds.cache.get(config.discord.guild); let member; guild.members.fetch({ withPresences: true }).then((fetchedMembers) => { - const totalOnline = fetchedMembers.filter( - (member) => member.presence?.status === "online" - ); + // const totalOnline = fetchedMembers.filter( + // (member) => member.presence?.status === "online" + // ); member = fetchedMembers.get(json.id); if (member) { synchronizeUser( @@ -93,11 +94,22 @@ app.get( .members.cache.get(json.id), tsid ); - } else console.log("The user didn't exist>!?!?"); - // Now you have a collection with all online member objects in the totalOnline variable + } else + log.error( + "Could not register from OAuth discord ID did not exist in the discord server - $discordId - $tsid", + { + tsid: req.cookies.tsid, + discordId: json.id, + } + ); }); } else { - console.log("Missing an ID, ", req.cookies.tsid, json.id); + log.error( + "Could not register from OAuth did not recieve tsid - $discordId", + { + discordId: json.id, + } + ); } if (config.web.clientBaseUrl) { @@ -118,5 +130,5 @@ app.get( ); app.listen(port, () => { - console.log(`OAuth Login listening at http://localhost:${port}`); + log.system(`OAuth Login listening at http://localhost:${port}`); }); diff --git a/src/log.js b/src/log.js new file mode 100644 index 0000000..a433a94 --- /dev/null +++ b/src/log.js @@ -0,0 +1,81 @@ +const config = require("config.json"); +const fs = require("fs"); +const _ = require("lodash"); + +class log { + LOG_LEVEL = { + SYSTEM: 0, + ERROR: 1, + WARN: 3, + INFO: 7, + DEBUG: 15, + VERBOSE: 31, + }; + + LOG_STR = _.invert(this.LOG_LEVEL); + + constructor() { + this.log = console.log; + } + + addLog(level, message, data) { + if (config.logLevel & level) return; + this.logConsole(level, message, data); + } + + getTimeStamp() { + return new Date().toISOString(); + } + + compileMessage(message, data) { + if (data) { + _.keysIn(data).forEach((key) => { + let data = + data[key] instanceof Object ? JSON.stringify(data[key]) : data[key]; + message = message.replace(`\$${key}`, `${key}: ${data}`); + }); + } + return message; + } + + createLogString(level, message, data) { + return `${this.getTimeStamp()} - [${ + this.LOG_STR[level] + }] - ${this.compileMessage(message, data)}`; + } + + logConsole(level, message, data) { + console.log(this.createLogString(level, message, data)); + } + + logFile(level, message, data) { + if (config.logging.file === undefined) return; + fs.appendFileSync( + config.logging.file, + this.createLogString(level, message, data), + data + ); + } + + system(message, data) { + this.addLog(this.LOG_LEVEL.SYSTEM, message, data); + } + + error(message, data) { + this.addLog(this.LOG_LEVEL.ERROR, message, data); + } + + info(message, data) { + this.addLog(this.LOG_LEVEL.INFO, message, data); + } + + debug(message, data) { + this.addLog(this.LOG_LEVEL.DEBUG, message, data); + } + + verbose(message, data) { + this.addLog(this.LOG_LEVEL.VERBOSE, message, data); + } +} + +module.exports = Object.freeze(new log()); diff --git a/src/teamspeak.js b/src/teamspeak.js index 06f88d8..7a1bfb2 100644 --- a/src/teamspeak.js +++ b/src/teamspeak.js @@ -4,6 +4,7 @@ const { TextMessageTargetMode, } = require("ts3-nodejs-library"); const config = require("./config"); +const log = require("./log"); /* TODO: FIX THIS ON SERVER EDIT @@ -31,16 +32,16 @@ class TS { }); this.client.on("error", (e) => { - console.log("error", e); + log.error("error", e); }); this.client.on("ready", () => { - console.log("Teamspeak Bot Connected"); + log.system("Teamspeak Bot Connected"); if (config.teamspeak.virtualServerId === undefined) { - console.log( + log.error( "No virtual server id specified, please choose one in the config file from the list below" ); - console.log(this.client.serverList()); + log.error(this.client.serverList()); } this.client.useBySid(config.teamspeak.virtualServerId); @@ -69,13 +70,26 @@ class TS { }); } + async sendPokeToClient(client, message) { + return new Promise((resolve) => { + if (client.propcache.clientType === 0) { + this.client.sendPokeToClient( + client, + TextMessageTargetMode.CLIENT, + message + ); + } + resolve(); + }); + } + async getGroupByName(name) { return new Promise(async (resolve, reject) => { try { let group = await this.client.getServerGroupByName(name); resolve(group); } catch (ex) { - console.log("Could not lookup group!", ex); + log.error("Could not lookup group!", ex); reject(ex); } });