Skip to content

Commit

Permalink
Add log controller, start work on log levels #13, add ability to swit…
Browse files Browse the repository at this point in the history
…ch between pokes and messages #16, add stuff that needs documented #20
  • Loading branch information
Brandyn committed Feb 18, 2024
1 parent 2893602 commit ac500c5
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 43 deletions.
9 changes: 7 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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);
});
}

Expand Down
16 changes: 11 additions & 5 deletions src/actions/teamspeakClientConnected.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/database.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const config = require("./config");
const sqlite3 = require("sqlite3").verbose();
const log = require("./log");

class Database {
constructor() {
Expand Down Expand Up @@ -148,7 +149,7 @@ class Database {
VALUES ('${discordID}','${tsID}')`,
(err) => {
if (err) {
console.log(err);
log.error(err);
reject(err);
}
resolve();
Expand Down
48 changes: 25 additions & 23 deletions src/discord.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const config = require("./config");
const log = require("./log");
const {
Client,
Collection,
Expand All @@ -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 }
);
}
}
Expand All @@ -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();
});
Expand All @@ -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);
});
});
}

Expand All @@ -103,7 +105,7 @@ class Discord {
{ body: devJsonCommands }
);

console.log(
log.system(
`Successfully reloaded ${data.length} dev application (/) commands.`
);

Expand All @@ -112,7 +114,7 @@ class Discord {
{ body: jsonCommands }
);

console.log(
log.debug(
`Successfully reloaded ${data2.length} public application (/) commands.`
);
}
Expand Down
26 changes: 19 additions & 7 deletions src/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand All @@ -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) {
Expand All @@ -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}`);
});
81 changes: 81 additions & 0 deletions src/log.js
Original file line number Diff line number Diff line change
@@ -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());
24 changes: 19 additions & 5 deletions src/teamspeak.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const {
TextMessageTargetMode,
} = require("ts3-nodejs-library");
const config = require("./config");
const log = require("./log");
/*
TODO: FIX THIS ON SERVER EDIT
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
});
Expand Down

0 comments on commit ac500c5

Please sign in to comment.