Skip to content

Commit

Permalink
Added Debug Mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Slingexe authored Feb 12, 2025
1 parent a3968d9 commit f19c385
Show file tree
Hide file tree
Showing 14 changed files with 79 additions and 15 deletions.
3 changes: 3 additions & 0 deletions READEME-DOCKER.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ The guild the bot is in should now have all of your users set as channels and it
Type in the channels the bot created to send a message to hackmud
Change the channel the bot sends to by doing the same thing you would normally do with the chat box (%n00bz / %0000)

## Debug Mode
In the docker run command add `-e DEBUG=true -e LOG_SENSITIVE_INFO=true`

## Contributions
All contributions are greatly appriciated! I am not great at coding so expect lots of spaghetti code.

Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Copy (or rename) the example config "configex.json" to "config.json"
Copy the bot's discord token to "token" (Application > Bot > Token)
Copy the application's clientID to "clientId" (Application > OAuth > ClientID)
Copy the guildID to "guildId" (Turn on dev mode > Right Click guild > CopyID)
Download the dependencies `npm insall --omit=dev`
Run the BOT using `node index.js`

In hackmud run the command `chat_pass` and copy the result
Expand All @@ -38,6 +39,10 @@ The guild the bot is in should now have all of your users set as channels and it
Type in the channels the bot created to send a message to hackmud
Change the channel the bot sends to by doing the same thing you would normally do with the chat box (%n00bz / %0000)

## Debug Mode
Linux - `export DEBUG=true` and `export LOG_SENSITIVE_INFO=true`
Windows - `set DEBUG=true` and `set LOG_SENSITIVE_INFO=true`

## Contributions
All contributions are greatly appriciated! I am not great at coding so expect lots of spaghetti code.

Expand Down
16 changes: 16 additions & 0 deletions backend/debug/log.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const dbgenv = process.env.DEBUG;

async function log() {
if (dbgenv === 'true') {
for (let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
console.log("---- END ----")
return true
}
return false
}

module.exports = {
log
};
3 changes: 3 additions & 0 deletions backend/docker/dockerstartup.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const fs = require('fs')
const { readFile } = require('fs/promises');
const path = require('path');
const { log } = require('../debug/log.js');
const isDocker = require('is-docker')

const env = process.env
Expand Down Expand Up @@ -51,6 +52,7 @@ async function dockerstartup() {
config.mudtoken = env.MUDTOKEN
console.log(`Found MUDTOKEN`)
} else {console.log("env.MUDTOKEN not found")}


fs.writeFileSync(configPath, JSON.stringify(config, null, 4));

Expand All @@ -59,6 +61,7 @@ async function dockerstartup() {
} else {
console.log("Not running inside a dockers")
}
log("---- Docker Startup ----", "-- ENV --", `TOKEN: ${env.LOG_SENSITIVE_INFO === true ? env.TOKEN : "HIDDEN"}`, `CID: ${env.CLIENTID}`, `GID: ${env.GUILDID}`, `MUDTOKEN: ${env.LOG_SENSITIVE_INFO === true ? env.MUDTOKEN : "HIDDEN"}`, `OVERRIDE: ${env.OVERRIDE === true ? "True" : "False"}`, "-- PATHS --", configPath);
}

module.exports.dockerstartup = dockerstartup;
2 changes: 2 additions & 0 deletions backend/fetchNewMessages.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { EmbedBuilder } = require('discord.js')
const { loadConfigVar, loadChnlMap } = require('./loadvar.js');
const { log } = require('./debug/log.js');

// Full Hackmud-to-Discord color mapping //  = U+001B
const hackmudToDiscordColors = {
Expand Down Expand Up @@ -217,6 +218,7 @@ async function fetchNewMessages(client) {
})
// Update the last timestamp
lastTimestamp = NowToRubyTS()+1;
log("---- Fetched Messages ----", payload, result, lastTimestamp);
} else {
console.error('Hackmud API error:', result.msg || 'Unknown error');
}
Expand Down
5 changes: 4 additions & 1 deletion backend/loadvar.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const fs = require('fs');
const { readFile } = require('fs/promises');
const path = require('path');
const { log } = require('./debug/log.js');
const isDocker = require('is-docker')

let configPath
Expand All @@ -18,7 +19,7 @@ if (isDocker() && !process.env.OVERRIDE) {
configPath = path.resolve(__dirname, './../config.json');
channelMappingsPath = path.resolve(__dirname, './../channelMappings.json');
}

log("---- LoadVar.js Config Paths ----", configPath, channelMappingsPath);

// Ensure config.json exists
if (!fs.existsSync(configPath)) {
Expand All @@ -37,6 +38,7 @@ async function loadConfigVar(key) {
try {
const configRaw = await readFile(configPath, 'utf8');
const config = JSON.parse(configRaw);
log(`LoadConfigVar was called, Input: ${key}, Output: ${config[key]}`);
return config[key] ?? null; // Return null if key doesn't exist
} catch (error) {
console.error(`Error loading config variable "${key}":`, error.message);
Expand All @@ -47,6 +49,7 @@ async function loadConfigVar(key) {
async function loadChnlMap() {
try {
const mapRaw = await readFile(channelMappingsPath, 'utf8');
log(`LoadChnlMap was called, Output: ${mapRaw}`);
return JSON.parse(mapRaw);
} catch (error) {
console.error("Error loading channel mappings:", error.message);
Expand Down
7 changes: 6 additions & 1 deletion commands/mud/client.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { SlashCommandBuilder, MessageFlags, ActivityType } = require('discord.js');
const { fetchNewMessages } = require('./../../backend/fetchNewMessages.js')
const { setChatPullInterval, clearChatPullInterval, getChatPullInterval } = require('./../../backend/pullInterval');
const { log } = require('./../../backend/debug/log.js');

module.exports = {
category: 'mud',
Expand All @@ -21,10 +22,12 @@ module.exports = {
const option = interaction.options.getSubcommand();
if (option === 'start') {
if (getChatPullInterval()) {
log("Someone tried to start the chat pull loop, but it's already running.");
await interaction.reply({content: 'Chat pull loop is already running.', flags: MessageFlags.Ephemeral });
return;
}


log("Chat pull loop started.");
await interaction.client.user.setStatus('online');
await interaction.client.user.setActivity({ type: ActivityType.Custom, name: "custom", state: "Listening for new messages..." });

Expand All @@ -35,13 +38,15 @@ module.exports = {
}
if (option === 'stop') {
if (getChatPullInterval()) {
log("Chat pull loop stopped.");
clearChatPullInterval();

await interaction.client.user.setStatus('idle');
await interaction.client.user.setActivity(' for new messages...', { type: ActivityType.Custom, name: "custom", state: "Bot Idle..." });

await interaction.reply({content: 'Chat pull loop has been stopped.', flags: MessageFlags.Ephemeral });
} else {
log("Someone tried to stop the chat pull loop, but it's not running.");
await interaction.reply({content: 'The chat pull loop is not running.', flags: MessageFlags.Ephemeral });
}
}
Expand Down
23 changes: 17 additions & 6 deletions commands/mud/settings.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const { SlashCommandBuilder, MessageFlags } = require('discord.js');
const { loadConfigVar, loadChnlMap } = require('./../../backend/loadvar.js');
const { log } = require('./../../backend/debug/log.js');
const fetch = require('node-fetch');
const fs = require('node:fs');
const path = require('path');
const { create } = require('node:domain');
const isDocker = require('is-docker')

const isDocker = require('is-docker');
let configPath
let mappingsPath
if (isDocker() && !process.env.OVERRIDE) {
Expand All @@ -20,6 +21,8 @@ if (isDocker() && !process.env.OVERRIDE) {
mappingsPath = path.resolve(__dirname, '../../channelMappings.json');
}

log("---- Settings.js Config Paths ----", configPath, mappingsPath);

async function createChannel(guild, name, categoryid) {
const discordChannelName = name;

Expand Down Expand Up @@ -130,12 +133,14 @@ module.exports = {
}

config.mudtoken = chatToken;
config.mudtokendate =
// config.mudtokendate =

fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
console.log('New mudtoken has been set:', chatToken)
console.log('New mudtoken has been set');
log("---- Settings.js - Auth ----", `New mudtoken has been set: ${env.LOG_SENSITIVE_INFO === 'true' ? chatToken : "HIDDEN"}`, payload, `${env.LOG_SENSITIVE_INFO === true ? result : "HIDDEN"}`, config, configPath);
await interaction.reply({content: `Config updated successfully! Token has been set.`, flags: MessageFlags.Ephemeral });
} else {
log("---- Settings.js - Auth ----", 'Failed to update mudtoken', payload, result);
console.error(result)
await interaction.reply({content: `Failed to update config. Server response: ${result.msg || 'Unknown error'}`, flags: MessageFlags.Ephemeral });
}
Expand Down Expand Up @@ -200,9 +205,11 @@ module.exports = {
}

fs.writeFileSync(mappingsPath, JSON.stringify(channelMapping, null, 4));


log("---- Settings.js - Setup ----", 'Sucessfully ran setup', `${env.LOG_SENSITIVE_INFO === true ? payload : "HIDDEN"}`, result, channelMapping, mappingsPath);
await interaction.reply({content: 'Server has been set up successfully, and user channels have been created or reused under the "chat" category.', flags: MessageFlags.Ephemeral });
} else {
log("---- Settings.js - Setup ----", 'Failed to run setup', `${env.LOG_SENSITIVE_INFO === true ? payload : "HIDDEN"}`, result);
console.error(result);
await interaction.reply({content: `Failed to run setup. Server response: ${result.msg || 'Unknown error'}`, flags: MessageFlags.Ephemeral });
}
Expand Down Expand Up @@ -234,7 +241,8 @@ module.exports = {
}

fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'utf-8');


log("---- Settings.js - Manage Users ----", 'Successfully updated settings', username, pullHistory, config, configPath);
await interaction.reply({content: `Successfully updated settings for user **${username}**. Pull history: **${pullHistory ? 'Enabled' : 'Disabled'}**`, flags: MessageFlags.Ephemeral });
} catch (error) {
console.error(error);
Expand All @@ -255,7 +263,9 @@ module.exports = {
}

fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'utf-8');
log("---- Settings.js - Color ----", 'Successfully updated setting', cmdcolorval, config, configPath);
} else {
log("---- Settings.js - Color ----", 'Invalid color value', cmdcolorval);
await interaction.reply({content: 'Invalid color value. Please use a single alphanumeric character or "reset"', flags: MessageFlags.Ephemeral });
}
}
Expand All @@ -267,6 +277,7 @@ module.exports = {
fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'utf-8');

await interaction.reply({content: `Successfully updated setting. Ping Detection: **${value ? 'Enabled' : 'Disabled'}**`, flags: MessageFlags.Ephemeral });
log("---- Settings.js - Ping Detection ----", 'Successfully updated setting', value, config, configPath);
} catch(error) {
console.error(error);
await interaction.reply({content: 'An error occurred while setting this option. Check console for details.', flags: MessageFlags.Ephemeral });
Expand Down
3 changes: 2 additions & 1 deletion commands/mud/tell.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { SlashCommandBuilder, MessageFlags } = require('discord.js');
const { loadConfigVar, loadChnlMap } = require('./../../backend/loadvar.js');
const fetch = require('node-fetch');
const { log } = require('./../../backend/debug/log.js');

module.exports = {
category: 'mud',
Expand Down Expand Up @@ -50,7 +51,7 @@ module.exports = {

const result = await response.json();
if (result.ok === true) {
console.log(`Message sent to ${tellusr} successfully. Message: ${tellmsg}`);
log(`---- tell.js ----`, `TellUsr: ${tellusr}`, `TellMsg: ${tellmsg}`, `ChannelName: ${channelName}`, `ChannelId: ${interaction.channelId}`, `Result: ${result.ok}`, `Msg: ${result.msg}`, channelMappings);
interaction.reply({content: `Message sent to ${tellusr} successfully. Message: ${tellmsg}`, flags: MessageFlags.Ephemeral });
} else {
console.log(`Failed to send message. Server response: ${result.msg || 'Unknown error'}`);
Expand Down
6 changes: 5 additions & 1 deletion deploy-commands.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// This script was taken from the discord.js documentation
// This script was taken from the discord.js documentation and modified by Slingo to fit the needs of the project.
const { log } = require('./backend/debug/log.js');

const isDocker = require('is-docker')
let configPath
if (isDocker() && !process.env.OVERRIDE) {
Expand All @@ -11,6 +13,8 @@ if (isDocker() && !process.env.OVERRIDE) {
} else {
configPath = path.resolve(__dirname, './../config.json');
}
log("---- deploy-commands.js Config Paths ----", configPath);

const { token, clientId, guildId } = require(configPath);

const { REST, Routes } = require('discord.js');
Expand Down
10 changes: 8 additions & 2 deletions events/messageCreate.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const { Events } = require('discord.js');
const { loadConfigVar, loadChnlMap } = require('./../backend/loadvar.js');
const { readFile } = require('fs/promises');
const fs = require('node:fs');
const path = require('path');
const { log } = require('./../backend/debug/log.js');

const isDocker = require('is-docker')
let configPath
if (isDocker() && !process.env.OVERRIDE) {
Expand All @@ -15,7 +16,7 @@ if (isDocker() && !process.env.OVERRIDE) {
} else {
configPath = path.resolve(__dirname, './../config.json');
}

log("---- messageCreate.js Config Paths ----", configPath);

module.exports = {
name: Events.MessageCreate,
Expand Down Expand Up @@ -45,8 +46,10 @@ module.exports = {

config.setchannel = channel;
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
log('---- messageCreate.js - Set Channel ----', `Set channel to ${channel}`, `ChannelName: ${channelName}`, `ChannelId: ${message.channel.id}`);
message.react('✅');
} catch (error) {
log('---- messageCreate.js - Set Channel ----', `Error setting channel to ${channel}`, `ChannelName: ${channelName}`, `ChannelId: ${message.channel.id}`, configPath);
console.log(error);
message.react('❌');
}
Expand Down Expand Up @@ -75,13 +78,16 @@ module.exports = {
});
const result = await response.json();
if (result.ok === true) {
log(`---- messageCreate.js - Send Message ----`, `${env.LOG_SENSITIVE_INFO === true ? payload : "HIDDEN"}`, result);
message.react('✅');
//console.log(`Message sent to ${setChannel} successfully. Message: ${finalMessage}`);
} else {
log(`---- messageCreate.js - Send Message ----`, `${env.LOG_SENSITIVE_INFO === true ? payload : "HIDDEN"}`, result);
message.react('❌');
console.log(`Failed to send message. Server response: ${result.msg || 'Unknown error'}`);
}
} catch (error) {
log(`---- messageCreate.js - Send Message ----`, `${env.LOG_SENSITIVE_INFO === true ? payload : "HIDDEN"}`, error);
message.react('❌');
console.log(error);
}
Expand Down
4 changes: 2 additions & 2 deletions events/ready.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ module.exports = {
const sPU = await loadConfigVar("pullusers");

if (sMT && sMT !== null) {
if (sCM && sCM !== {}) {
if (sPU && (sPU !== null || sPU !== [])) {
if (sCM && Object.keys(sCM).length !== 0) {
if (sPU && ( Array.isArray(sPU) && sPU.length > 0 )) {
let interval = setInterval(() => fetchNewMessages(client), 5000);
setChatPullInterval(interval);

Expand Down
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
const dbgenv = process.env.DEBUG;
const LSIenv = process.env.LOG_SENSITIVE_INFO;
console.log(`DEBUG LOGGING: ${dbgenv === 'true' ? "Enabled" : "Disabled"}`);
console.log(`LOG SENSITIVE INFO: ${LSIenv === 'true' ? "Enabled" : "Disabled"}`);

const { execSync } = require('child_process');
execSync('node -e "require(\'./backend/docker/dockerstartup.js\').dockerstartup().then(() => process.exit(0))"', { stdio: 'inherit' }); // since I can't use await here this is a workaround

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "hackmud-chat-client",
"version": "1.0.5",
"version": "1.0.6",
"description": "A discord bot that bridges the hackmud chat with discord!",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit f19c385

Please sign in to comment.