Initial update to try and fix #1

This commit is contained in:
Logan Cusano
2023-03-26 15:03:35 -04:00
parent 403b533a33
commit b296da629b
14 changed files with 225 additions and 120 deletions

View File

@@ -3,17 +3,44 @@ var express = require('express');
var path = require('path'); var path = require('path');
var cookieParser = require('cookie-parser'); var cookieParser = require('cookie-parser');
var logger = require('morgan'); var logger = require('morgan');
var http = require('http');
require('dotenv').config();
const fs = require('fs');
const { DebugBuilder } = require("./utilities/debugBuilder");
const deployCommands = require('./utilities/deployCommands');
var indexRouter = require('./routes/index'); var indexRouter = require('./routes/index');
var botRouter = require('./routes/bot'); var botRouter = require('./routes/bot');
var clientRouter = require('./routes/client'); var clientRouter = require('./routes/client');
var radioRouter = require('./routes/radio'); var radioRouter = require('./routes/radio');
const log = new DebugBuilder("client", "app");
const {
Client,
Events,
Collection,
GatewayIntentBits,
MessageActionRow,
MessageButton
} = require('discord.js');
var app = express(); var app = express();
var discordToken = process.env.TOKEN;
var port = libUtils.normalizePort(process.env.HTTP_PORT || '3000');
const discordClient = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates
]
});
// view engine setup // view engine setup
app.set('views', path.join(__dirname, 'views')); app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); app.set('view engine', 'ejs');
app.set('port', port);
app.use(logger('dev')); app.use(logger('dev'));
app.use(express.json()); app.use(express.json());
@@ -21,10 +48,14 @@ app.use(express.urlencoded({ extended: false }));
app.use(cookieParser()); app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
// Default route
app.use('/', indexRouter); app.use('/', indexRouter);
// Discord bot control route // Discord bot control route
app.use('/bot', botRouter); app.use('/bot', (res, req, next) => {
req.discordClient = discordClient; // Add the discord client to bot requests to be used downstream
next()
}, botRouter);
// Local client control route // Local client control route
app.use("/client", clientRouter); app.use("/client", clientRouter);
@@ -33,12 +64,12 @@ app.use("/client", clientRouter);
app.use("/radio", radioRouter); app.use("/radio", radioRouter);
// catch 404 and forward to error handler // catch 404 and forward to error handler
app.use(function(req, res, next) { app.use((req, res, next) => {
next(createError(404)); next(createError(404));
}); });
// error handler // error handler
app.use(function(err, req, res, next) { app.use((err, req, res, next) => {
// set locals, only providing error in development // set locals, only providing error in development
res.locals.message = err.message; res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {}; res.locals.error = req.app.get('env') === 'development' ? err : {};
@@ -48,4 +79,62 @@ app.use(function(err, req, res, next) {
res.render('error'); res.render('error');
}); });
module.exports = app; /**
* Start the HTTP background server
*/
async function runHTTPServer() {
var server = http.createServer(app);
server.listen(port);
server.on('error', libUtils.onError);
server.on('listening', () => {
log.INFO("HTTP server started!");
})
}
// Discord bot config
// Setup commands for the Discord bot
discordClient.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
//const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
log.DEBUG("Importing command: ", command.data.name);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
discordClient.commands.set(command.data.name, command);
}
// Run when the bot is ready
discordClient.on('ready', () => {
log.DEBUG(`Discord server up and running with client: ${discordClient.user.tag}`);
log.INFO(`Logged in as ${discordClient.user.tag}!`);
// Deploy slash commands
log.DEBUG("Deploying slash commands");
deployCommands.deploy(discordClient.user.id, discordClient.guilds.cache.map(guild => guild.id));
log.DEBUG(`Starting HTTP Server`);
runHTTPServer();
});
// Setup any additional event handlers
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
discordClient.once(event.name, (...args) => event.execute(...args));
} else {
discordClient.on(event.name, (...args) => event.execute(...args));
}
}
discordClient.login(discordToken); //Load Client Discord Token

View File

@@ -1,11 +1,11 @@
// Debug // Debug
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js"; const { DebugBuilder } = require("../utilities/debugBuilder.js");
const log = new ModuleDebugBuilder("bot", "join"); const log = new DebugBuilder("client-bot", "join");
// Modules // Modules
import { joinVoiceChannel, VoiceConnectionStatus } from "@discordjs/voice"; const { joinVoiceChannel, VoiceConnectionStatus } = require("@discordjs/voice");
import {replyToInteraction} from "../utilities/messageHandler.js"; const {replyToInteraction} = require("../utilities/messageHandler.js");
import {createAudioInstance} from "../controllers/audioController.js"; const {createAudioInstance} = require("../controllers/audioController.js");
import OpusEncoderPkg from "@discordjs/opus"; const OpusEncoderPkg = require("@discordjs/opus");
// Declare the encoder (module is incompatible modern import method) // Declare the encoder (module is incompatible modern import method)
const { OpusEncoder } = OpusEncoderPkg; const { OpusEncoder } = OpusEncoderPkg;
@@ -20,7 +20,7 @@ const encoder = new OpusEncoder(48000, 2);
* @param guild The guild object to be used to create a voice adapter * @param guild The guild object to be used to create a voice adapter
* @param {function} callback The callback that will be needed if this function is run with a Guild ID instead of an interaction * @param {function} callback The callback that will be needed if this function is run with a Guild ID instead of an interaction
*/ */
export default async function join({interaction= undefined, guildID= undefined, channelID = undefined, guildObj = undefined, callback = undefined}){ exports.join = async function join({interaction= undefined, guildID= undefined, channelID = undefined, guildObj = undefined, callback = undefined}){
if (interaction){ if (interaction){
const voiceChannel = interaction.options.getChannel('voicechannel'); const voiceChannel = interaction.options.getChannel('voicechannel');
channelID = voiceChannel.id; channelID = voiceChannel.id;

View File

@@ -1,8 +1,8 @@
import {getVoiceConnection} from "@discordjs/voice"; const {getVoiceConnection} = require("@discordjs/voice");
import {replyToInteraction} from "../utilities/messageHandler.js"; const {replyToInteraction} = require("../utilities/messageHandler.js");
// Debug // Debug
//import debugBuilder from "../utilities/moduleDebugBuilder.js"; const { DebugBuilder } = require("../utilities/debugBuilder.js");
//const log = new debugBuilder("bot", "leave"); const log = new DebugBuilder("client-bot", "leave");
/** /**
* If in a voice channel for the specified guild, leave * If in a voice channel for the specified guild, leave
@@ -11,7 +11,7 @@ import {replyToInteraction} from "../utilities/messageHandler.js";
* @param guildID * @param guildID
* @param callback * @param callback
*/ */
export default async function leave({interaction = undefined, guildID= undefined, callback = undefined}) { exports.leave = async function leave({interaction = undefined, guildID= undefined, callback = undefined}) {
if(interaction) { if(interaction) {
guildID = interaction.guild.id; guildID = interaction.guild.id;
} }

View File

@@ -1,5 +1,5 @@
// Utilities // Utilities
import { replyToInteraction } from '../utilities/messageHandler.js'; const { replyToInteraction } = require('../utilities/messageHandler.js');
export default function ping(interaction) { export default function ping(interaction) {
return replyToInteraction(interaction, "Pong! I have Aids and now you do too!"); return replyToInteraction(interaction, "Pong! I have Aids and now you do too!");

View File

@@ -1,13 +1,13 @@
// Debug // Debug
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js"; const { DebugBuilder } = require("../utilities/debugBuilder.js");
const log = new ModuleDebugBuilder("bot", "status"); const log = new DebugBuilder("client-bot", "status");
// Modules // Modules
import {getVoiceConnection} from "@discordjs/voice"; const {getVoiceConnection} = require("@discordjs/voice");
// Utilities // Utilities
import { replyToInteraction } from '../utilities/messageHandler.js'; const { replyToInteraction } = require('../utilities/messageHandler.js');
export default async function status({interaction= undefined, guildID= undefined, callback = undefined}) { exports.status = async function status({interaction= undefined, guildID= undefined, callback = undefined}) {
//if (!interaction && !guildID) // Need error of sorts //if (!interaction && !guildID) // Need error of sorts
if (interaction){ if (interaction){
guildID = interaction.guild.id; guildID = interaction.guild.id;

View File

@@ -1,5 +1,4 @@
{ {
"TOKEN": "OTQzNzQyMDQwMjU1MTE1MzA0.Yg3eRA.ZxEbRr55xahjfaUmPY8pmS-RHTY",
"ApplicationID": "943742040255115304", "ApplicationID": "943742040255115304",
"GuildID": "367396189529833472", "GuildID": "367396189529833472",
"DeviceID": "5", "DeviceID": "5",

View File

@@ -1,12 +1,12 @@
// Config // Config
import { getDeviceID } from '../utilities/configHandler.js'; const { getDeviceID } = require('../utilities/configHandler.js');
// Modules // Modules
import alsaInstance from 'alsa-capture'; const alsaInstance = require('alsa-capture');
import { returnAlsaDeviceObject } from "../utilities/executeConsoleCommands.js"; const { returnAlsaDeviceObject } = require("../utilities/executeConsoleCommands.js");
// Debug // Debug
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js"; const { DebugBuilder } = require("../utilities/debugBuilder.js");
// Global Vars // Global Vars
const log = new ModuleDebugBuilder("bot", "audioController"); const log = new DebugBuilder("client-bot", "audioController");
/** /**
* Checks to make sure the selected audio device is available and returns the device object (PortAudio Device Info) * Checks to make sure the selected audio device is available and returns the device object (PortAudio Device Info)
@@ -16,7 +16,7 @@ const log = new ModuleDebugBuilder("bot", "audioController");
* @param deviceId The ID of the device being queried * @param deviceId The ID of the device being queried
* @returns {unknown} * @returns {unknown}
*/ */
export async function confirmAudioDevice({deviceName = undefined, deviceId = undefined}){ exports.confirmAudioDevice = async function confirmAudioDevice({deviceName = undefined, deviceId = undefined}){
const deviceList = await getAudioDevices(); const deviceList = await getAudioDevices();
if (!deviceName && !deviceId) throw new Error("No device given"); if (!deviceName && !deviceId) throw new Error("No device given");
if (deviceId) return deviceList.find(device => device.id === deviceId); if (deviceId) return deviceList.find(device => device.id === deviceId);
@@ -28,7 +28,7 @@ export async function confirmAudioDevice({deviceName = undefined, deviceId = und
* *
* @returns {unknown[]} * @returns {unknown[]}
*/ */
export async function getAudioDevices(){ exports.getAudioDevices = async function getAudioDevices(){
// Exec output contains both stderr and stdout outputs // Exec output contains both stderr and stdout outputs
const deviceList = await returnAlsaDeviceObject(); const deviceList = await returnAlsaDeviceObject();
log.DEBUG("Device list: ", deviceList); log.DEBUG("Device list: ", deviceList);
@@ -42,7 +42,7 @@ export async function getAudioDevices(){
* *
* @returns new portAudio.AudioIO * @returns new portAudio.AudioIO
*/ */
export async function createAudioInstance() { exports.createAudioInstance = async function createAudioInstance() {
const selectedDevice = await confirmAudioDevice({deviceId: getDeviceID()});//{deviceName: "VoiceMeeter VAIO3 Output (VB-Au"}); const selectedDevice = await confirmAudioDevice({deviceId: getDeviceID()});//{deviceName: "VoiceMeeter VAIO3 Output (VB-Au"});
log.DEBUG("Device selected from config: ", selectedDevice); log.DEBUG("Device selected from config: ", selectedDevice);
// Create an instance of AudioIO with outOptions (defaults are as below), which will return a WritableStream // Create an instance of AudioIO with outOptions (defaults are as below), which will return a WritableStream

View File

@@ -5,33 +5,29 @@ const log = new DebugBuilder("client", "clientController");
const path = require('path'); const path = require('path');
const fork = require('child_process').fork; const fork = require('child_process').fork;
const discordBotPath = path.resolve('discord-bot/app.js'); const discordBotPath = path.resolve('discord-bot/app.js');
// Commands
let botChildProcess, tempRes; const ping = require('../commands/ping.js');
const join = require('../commands/join.js');
const leave = require('../commands/leave.js');
const status = require('../commands/status.js');
/** /**
* Bot Process Object Builder * Get an object of client guilds
* * @returns
* This construnctor is used to easily pass commands to the bot process
*/ */
class BPOB { function getGuilds() {
/** return client.guilds.cache.map(guild => guild.id)
* Build an object to be passed to the bot process
* @param command The command to be run ("Status", "Join", "Leave", "ChgPreSet")
* @param parameters Depending on the command being run, there parameters required in order to be run
*/
constructor(command = "Status"||"Join"||"Leave"||"ChgPreSet", parameters = []||undefined) {
this.cmd = command;
if (parameters) this.params = parameters;
}
} }
/** /**
* Get Status of the discord process * Get Status of the discord process
*/ */
exports.getStatus = (req, res) => { exports.getStatus = (req, res) => {
if (!botChildProcess) return res.sendStatus(200); status({guildID: guildID, callback: (statusObj) => {
botChildProcess.send(new BPOB("Status")); log.DEBUG("Status Object string: ", statusObj);
tempRes = res; if (!statusObj.voiceConnection) return req.sendStatus(201);
return req.sendStatus(202);
}});
} }
/** /**
@@ -43,45 +39,16 @@ exports.joinServer = (req, res) => {
if (!channelID || !presetName) return res.status(400).json({'message': "Channel ID or Preset Name not present in the request"}); if (!channelID || !presetName) return res.status(400).json({'message': "Channel ID or Preset Name not present in the request"});
// Start the bot // Start the bot
botChildProcess = fork(discordBotPath); join({guildID: guildID, guildObj: client.guilds.cache.get(guildID), channelID: channelID, callback: () => {
return req.sendStatus(202);
// Handle bot responses }});
botChildProcess.on('message', (msg) => {
log.DEBUG('Child response: ', msg);
if (msg.msg === "INIT READY") {
// Discord bot has started and is ready.
botChildProcess.send(new BPOB("Join", {"channelID": channelID, "presetName": presetName}))
tempRes = res;
}
switch (msg.cmd){
case "Status":
if (msg.msg === "VDISCONN") tempRes.sendStatus(201); // VDISCONN == Voice DISCONNected
else tempRes.sendStatus(202);
tempRes = undefined;
return;
case "Join":
tempRes.sendStatus(202);
tempRes = undefined;
return;
case "Leave":
tempRes.sendStatus(202);
tempRes = undefined;
botChildProcess.kill();
botChildProcess = undefined;
return;
case "ChgPreSet":
tempRes.sendStatus(200);
tempRes = undefined;
return;
}
})
} }
/** /**
* Leaves the server if it's in one * Leaves the server if it's in one
*/ */
exports.leaveServer = (req, res) => { exports.leaveServer = (req, res) => {
if (!botChildProcess) return res.sendStatus(200) leave({guildID: guildID, callback: (response) => {
botChildProcess.send(new BPOB("Leave")); return req.sendStatus(202);
tempRes = res; }});
} }

View File

@@ -1,9 +0,0 @@
// Debug
import ModuleDebugBuilder from "./moduleDebugBuilder.js";
const log = new ModuleDebugBuilder("bot", "messageHandler");
export function replyToInteraction(interaction, message){
interaction.reply({ content: message, fetchReply: true })
.then((message) => log.DEBUG(`Reply sent with content ${message.content}`))
.catch((err) => log.ERROR(err));
}

View File

@@ -8,11 +8,20 @@
"dependencies": { "dependencies": {
"convert-units": "^2.3.4", "convert-units": "^2.3.4",
"cookie-parser": "~1.4.4", "cookie-parser": "~1.4.4",
"debug": "~2.6.9", "debug": "^4.3.4",
"ejs": "~2.6.1", "ejs": "~2.6.1",
"express": "~4.16.1", "express": "~4.16.1",
"http-errors": "~1.6.3", "http-errors": "~1.6.3",
"morgan": "~1.9.1", "morgan": "~1.9.1",
"replace-in-file": "~6.3.5" "replace-in-file": "~6.3.5",
"@discordjs/builders": "^1.4.0",
"@discordjs/opus": "^0.9.0",
"@discordjs/rest": "^1.4.0",
"@discordjs/voice": "^0.14.0",
"@mapbox/node-pre-gyp": "^1.0.10",
"discord.js": "^14.7.1",
"node-gyp": "^9.3.0",
"libsodium-wrappers": "^0.7.10",
"alsa-capture": "0.3.0"
} }
} }

View File

@@ -1,23 +1,15 @@
// Debug // Debug
import ModuleDebugBuilder from "./moduleDebugBuilder.js"; const { DebugBuilder } = require("../utilities/debugBuilder.js");
const log = new ModuleDebugBuilder("bot", "configHandler"); const log = new DebugBuilder("client-bot", "configController");
// Modules // Modules
import { readFileSync } from 'fs'; const { readFileSync } = require('fs');
import path from "path"; const path = require("path");
export function getConfig() { exports.getConfig = function getConfig() {
return JSON.parse(readFileSync(path.resolve("discord-bot/config/botConfig.json"))); return JSON.parse(readFileSync(path.resolve("discord-bot/config/botConfig.json")));
} }
export function getTOKEN() { exports.getGuildID = function getGuildID() {
const parsedJSON = getConfig();
const token = parsedJSON.TOKEN;
log.DEBUG("Discord API Token: ", token)
return token;
}
export function getGuildID() {
const parsedJSON = getConfig(); const parsedJSON = getConfig();
const guildID = parsedJSON.GuildID; const guildID = parsedJSON.GuildID;
@@ -25,7 +17,7 @@ export function getGuildID() {
return guildID; return guildID;
} }
export function getApplicationID() { exports.getApplicationID = function getApplicationID() {
const parsedJSON = getConfig(); const parsedJSON = getConfig();
const appID = parsedJSON.ApplicationID; const appID = parsedJSON.ApplicationID;
@@ -33,7 +25,7 @@ export function getApplicationID() {
return appID; return appID;
} }
export function getDeviceID(){ exports.getDeviceID = function getDeviceID(){
const parsedJSON = getConfig(); const parsedJSON = getConfig();
const deviceID = parseInt(parsedJSON.DeviceID); const deviceID = parseInt(parsedJSON.DeviceID);
@@ -41,7 +33,7 @@ export function getDeviceID(){
return deviceID; return deviceID;
} }
export function getDeviceName(){ exports.getDeviceName = function getDeviceName(){
const parsedJSON = getConfig(); const parsedJSON = getConfig();
const deviceName = parsedJSON.DeviceName; const deviceName = parsedJSON.DeviceName;

View File

@@ -0,0 +1,49 @@
const { REST, Routes } = require('discord.js');
require('dotenv').config();
const token = process.env.TOKEN;
//const clientId = process.env.clientId;
//const guildId = process.env.guildId;
const fs = require('node:fs');
const path = require('node:path');
const { DebugBuilder } = require("./debugBuilder");
const log = new DebugBuilder("client", "deployCommands");
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.resolve(__dirname, '../commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
exports.deploy = (clientId, guildIDs) => {
log.DEBUG("Deploying commands for: ", guildIDs);
if (Array.isArray(guildIDs)) guildIDs = [guildIDs];
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`${path.resolve(commandsPath, file)}`);
commands.push(command.data.toJSON());
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(token);
// and deploy your commands!
for (const guildId of guildIDs){
(async () => {
try {
log.DEBUG(`Started refreshing ${commands.length} application (/) commands for guild ID: ${guildId}.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
log.DEBUG(`Successfully reloaded ${data.length} application (/) commands for guild ID: ${guildId}.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
log.ERROR("ERROR Deploying commands: ", error, "Body from error: ", commands);
}
})()
}
};

View File

@@ -1,14 +1,14 @@
// Modules // Modules
import { promisify } from 'util'; const { promisify } = require('util');
import { exec } from "child_process"; const { exec } = require("child_process");
// Debug // Debug
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js"; const { DebugBuilder } = require("../utilities/debugBuilder.js");
// Global Vars // Global Vars
const log = new ModuleDebugBuilder("bot", "executeConsoleCommand"); const log = new DebugBuilder("client-bot", "executeConsoleCommands");
const execCommand = promisify(exec); const execCommand = promisify(exec);
export default async function executeAsyncConsoleCommand(consoleCommand) { exports.executeAsyncConsoleCommand = async function executeAsyncConsoleCommand(consoleCommand) {
// Check to see if the command is a real command // Check to see if the command is a real command
// TODO needs to be improved // TODO needs to be improved
const acceptableCommands = [ "arecord -L" ]; const acceptableCommands = [ "arecord -L" ];
@@ -27,7 +27,7 @@ export default async function executeAsyncConsoleCommand(consoleCommand) {
return output; return output;
} }
export async function returnAlsaDeviceObject() { exports.returnAlsaDeviceObject = async function returnAlsaDeviceObject() {
const listAlsaDevicesCommand = "arecord -L"; const listAlsaDevicesCommand = "arecord -L";
const commandResponse = await executeAsyncConsoleCommand(listAlsaDevicesCommand); const commandResponse = await executeAsyncConsoleCommand(listAlsaDevicesCommand);
const brokenCommand = String(commandResponse).split('\n'); const brokenCommand = String(commandResponse).split('\n');

View File

@@ -0,0 +1,9 @@
// Debug
const { DebugBuilder } = require("../utilities/debugBuilder.js");
const log = new DebugBuilder("client-bot", "messageHandler");
exports.replyToInteraction = async function replyToInteraction(interaction, message){
interaction.reply({ content: message, fetchReply: true })
.then((message) => log.DEBUG(`Reply sent with content ${message.content}`))
.catch((err) => log.ERROR(err));
}