feature/implement-bot-into-client-core #2
@@ -1 +1,8 @@
|
||||
DEBUG="client:*";
|
||||
DEBUG="client:*"
|
||||
TOKEN=""
|
||||
# Bot Config
|
||||
APPLICATION_ID=""
|
||||
GUILD_ID=""
|
||||
# Audio Config
|
||||
AUDIO_DEVICE_ID="1"
|
||||
AUDIO_DEVICE_NAME="VoiceMeeter VAIO3 Output (VB-Au"
|
||||
128
Client/app.js
128
Client/app.js
@@ -3,17 +3,45 @@ var express = require('express');
|
||||
var path = require('path');
|
||||
var cookieParser = require('cookie-parser');
|
||||
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');
|
||||
const { checkIn } = require("./controllers/clientController");
|
||||
|
||||
var indexRouter = require('./routes/index');
|
||||
var indexRouter = require('./routes/index');
|
||||
var botRouter = require('./routes/bot');
|
||||
var clientRouter = require('./routes/client');
|
||||
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 discordToken = process.env.TOKEN;
|
||||
var port = process.env.HTTP_PORT || '3010';
|
||||
|
||||
const discordClient = new Client({
|
||||
intents: [
|
||||
GatewayIntentBits.Guilds,
|
||||
GatewayIntentBits.GuildMessages,
|
||||
GatewayIntentBits.MessageContent,
|
||||
GatewayIntentBits.GuildVoiceStates
|
||||
]
|
||||
});
|
||||
|
||||
// view engine setup
|
||||
app.set('views', path.join(__dirname, 'views'));
|
||||
app.set('view engine', 'ejs');
|
||||
app.set('port', port);
|
||||
|
||||
app.use(logger('dev'));
|
||||
app.use(express.json());
|
||||
@@ -21,10 +49,14 @@ app.use(express.urlencoded({ extended: false }));
|
||||
app.use(cookieParser());
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
// Default route
|
||||
app.use('/', indexRouter);
|
||||
|
||||
// Discord bot control route
|
||||
app.use('/bot', botRouter);
|
||||
app.use('/bot', (req, res, next) => {
|
||||
req.discordClient = discordClient; // Add the discord client to bot requests to be used downstream
|
||||
next();
|
||||
}, botRouter);
|
||||
|
||||
// Local client control route
|
||||
app.use("/client", clientRouter);
|
||||
@@ -33,12 +65,12 @@ app.use("/client", clientRouter);
|
||||
app.use("/radio", radioRouter);
|
||||
|
||||
// catch 404 and forward to error handler
|
||||
app.use(function(req, res, next) {
|
||||
app.use((req, res, next) => {
|
||||
next(createError(404));
|
||||
});
|
||||
|
||||
// error handler
|
||||
app.use(function(err, req, res, next) {
|
||||
app.use((err, req, res, next) => {
|
||||
// set locals, only providing error in development
|
||||
res.locals.message = err.message;
|
||||
res.locals.error = req.app.get('env') === 'development' ? err : {};
|
||||
@@ -48,4 +80,90 @@ app.use(function(err, req, res, next) {
|
||||
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', (error) => {
|
||||
if (error.syscall !== 'listen') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
var bind = typeof port === 'string'
|
||||
? 'Pipe ' + port
|
||||
: 'Port ' + port;
|
||||
|
||||
// handle specific listen errors with friendly messages
|
||||
switch (error.code) {
|
||||
case 'EACCES':
|
||||
log.ERROR(bind + ' requires elevated privileges');
|
||||
process.exit(1);
|
||||
break;
|
||||
case 'EADDRINUSE':
|
||||
log.ERROR(bind + ' is already in use');
|
||||
process.exit(1);
|
||||
break;
|
||||
default:
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
|
||||
log.DEBUG("Checking in with the master server")
|
||||
checkIn();
|
||||
});
|
||||
|
||||
// Setup any additional event handlers
|
||||
const eventsPath = path.join(__dirname, 'events');
|
||||
if (fs.existsSync(eventsPath)) {
|
||||
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
|
||||
if (eventFiles.length > 0) {
|
||||
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
|
||||
17
Client/commands/join.js
Normal file
17
Client/commands/join.js
Normal file
@@ -0,0 +1,17 @@
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder");
|
||||
const log = new DebugBuilder("client", "ping");
|
||||
// Modules
|
||||
const { SlashCommandBuilder } = require('discord.js');
|
||||
const { join } = require("../controllers/commandController")
|
||||
|
||||
module.exports = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('join')
|
||||
.setDescription('Join a voice channel'),
|
||||
example: "join",
|
||||
isPrivileged: false,
|
||||
async execute(interaction) {
|
||||
await join({ interaction: interaction });
|
||||
}
|
||||
}
|
||||
17
Client/commands/leave.js
Normal file
17
Client/commands/leave.js
Normal file
@@ -0,0 +1,17 @@
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("client", "leave");
|
||||
// Modules
|
||||
const { SlashCommandBuilder } = require('discord.js');
|
||||
const { leave } = require("../controllers/commandController")
|
||||
|
||||
module.exports = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('leave')
|
||||
.setDescription('Leave a voice channel'),
|
||||
example: "leave",
|
||||
isPrivileged: false,
|
||||
async execute(interaction) {
|
||||
await leave({ interaction: interaction })
|
||||
}
|
||||
}
|
||||
28
Client/commands/ping.js
Normal file
28
Client/commands/ping.js
Normal file
@@ -0,0 +1,28 @@
|
||||
// Utilities
|
||||
const { replyToInteraction } = require('../utilities/messageHandler.js');
|
||||
const { SlashCommandBuilder } = require('discord.js');
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder");
|
||||
const log = new DebugBuilder("client", "ping");
|
||||
|
||||
module.exports = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('ping')
|
||||
.setDescription('Replies with your input!'),
|
||||
/*
|
||||
.addStringOption(option =>
|
||||
option.setName('input')
|
||||
.setDescription('The input to echo back')
|
||||
.setRequired(false)
|
||||
.addChoices()),
|
||||
*/
|
||||
example: "ping",
|
||||
isPrivileged: false,
|
||||
async execute(interaction) {
|
||||
try{
|
||||
await replyToInteraction(interaction, "Pong! I have Aids and now you do too!"); // TODO - Add insults as the response to this command
|
||||
}catch(err){
|
||||
log.ERROR(err)
|
||||
//await interaction.reply(err.toString());
|
||||
}
|
||||
}
|
||||
};
|
||||
19
Client/commands/status.js
Normal file
19
Client/commands/status.js
Normal file
@@ -0,0 +1,19 @@
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("client", "status");
|
||||
// Modules
|
||||
const { status } = require('../controllers/commandController');
|
||||
// Utilities
|
||||
|
||||
const { SlashCommandBuilder } = require('discord.js');
|
||||
|
||||
module.exports = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('status')
|
||||
.setDescription('Check the status of the bot'),
|
||||
example: "status",
|
||||
isPrivileged: false,
|
||||
async execute(interaction) {
|
||||
await status({ interaction: interaction });
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ exports.clientConfig = {
|
||||
"id": 13,
|
||||
"name": "boilin balls in the hall",
|
||||
"ip": "172.16.100.150",
|
||||
"port": 3001,
|
||||
"port": 3010,
|
||||
"location": "the house",
|
||||
"nearbySystems": ["Westchester Cty. Simulcast"],
|
||||
"online": true
|
||||
@@ -12,7 +12,7 @@ exports.clientConfig = {
|
||||
|
||||
// Configuration for the connection to the server
|
||||
exports.serverConfig = {
|
||||
"ip": "127.0.0.1",
|
||||
"ip": "172.16.100.108",
|
||||
"hostname": "localhost",
|
||||
"port": 3000
|
||||
}
|
||||
|
||||
88
Client/controllers/audioController.js
Normal file
88
Client/controllers/audioController.js
Normal file
@@ -0,0 +1,88 @@
|
||||
// Config
|
||||
const { getDeviceID } = require('../utilities/configHandler.js');
|
||||
// Modules
|
||||
const portAudio = require('naudiodon');
|
||||
const { returnAlsaDeviceObject } = require("../utilities/executeConsoleCommands.js");
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
// Global Vars
|
||||
const log = new DebugBuilder("client", "audioController");
|
||||
|
||||
/**
|
||||
* Checks to make sure the selected audio device is available and returns the device object (PortAudio Device Info)
|
||||
* At least one option must be supplied, it will prefer ID to device name
|
||||
*
|
||||
* @param deviceName The name of the device being queried
|
||||
* @param deviceId The ID of the device being queried
|
||||
* @returns {unknown}
|
||||
*/
|
||||
async function confirmAudioDevice({deviceName = undefined, deviceId = undefined}){
|
||||
const deviceList = await getAudioDevices();
|
||||
if (!deviceName && !deviceId) throw new Error("No device given");
|
||||
let confirmedDevice;
|
||||
if (deviceId) confirmedDevice = deviceList.find(device => device.id === deviceId);
|
||||
if (deviceName) confirmedDevice = deviceList.find(device => device.name === deviceName);
|
||||
|
||||
log.DEBUG("Confirmed Audio Device: ", confirmedDevice);
|
||||
|
||||
return confirmedDevice;
|
||||
}
|
||||
exports.confirmAudioDevice = confirmAudioDevice;
|
||||
|
||||
/**
|
||||
* Return a list of the audio devices connected with input channels
|
||||
*
|
||||
* @returns {unknown[]}
|
||||
*/
|
||||
async function getAudioDevices(){
|
||||
// Exec output contains both stderr and stdout outputs
|
||||
//const deviceList = await returnAlsaDeviceObject();
|
||||
const deviceList = portAudio.getDevices().map((device) => {
|
||||
if (device.maxInputChannels > 2) {
|
||||
return device;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
log.VERBOSE("Device List: ", deviceList);
|
||||
return deviceList;
|
||||
}
|
||||
exports.getAudioDevices = getAudioDevices;
|
||||
|
||||
/**
|
||||
* Create and return the audio instance from the saved settings
|
||||
* TODO Allow the client to save and load these settings dynamically
|
||||
*
|
||||
* @returns new portAudio.AudioIO
|
||||
*/
|
||||
async function createAudioInstance() {
|
||||
const selectedDevice = await confirmAudioDevice({deviceId: getDeviceID()});//{deviceName: "VoiceMeeter VAIO3 Output (VB-Au"});
|
||||
log.DEBUG("Device selected from config: ", selectedDevice);
|
||||
// Create an instance of AudioIO with outOptions (defaults are as below), which will return a WritableStream
|
||||
|
||||
return new portAudio.AudioIO({
|
||||
inOptions: {
|
||||
channelCount: 2,
|
||||
sampleFormat: portAudio.SampleFormat16Bit,
|
||||
sampleRate: 48000,
|
||||
deviceId: selectedDevice.id, // Use -1 or omit the deviceId to select the default device
|
||||
closeOnError: false, // Close the stream if an audio error is detected, if set false then just log the error
|
||||
framesPerBuffer: 20, //(48000 / 1000) * 20, //(48000 * 16 * 2) / 1000 * 20 // (48000 * (16 / 8) * 2) / 60 / 1000 * 20 //0.025 * 48000 / 2
|
||||
highwaterMark: 3840,
|
||||
},
|
||||
});
|
||||
/*
|
||||
return new alsaInstance({
|
||||
channels: 2,
|
||||
format: "U8",
|
||||
rate: 48000,
|
||||
device: selectedDevice.name ?? "default", // Omit the deviceId to select the default device
|
||||
periodSize: 100, //(48000 / 1000) * 20, //(48000 * 16 * 2) / 1000 * 20 // (48000 * (16 / 8) * 2) / 60 / 1000 * 20 //0.025 * 48000 / 2
|
||||
periodTime: undefined,
|
||||
// highwaterMark: 3840
|
||||
});
|
||||
*/
|
||||
|
||||
}
|
||||
exports.createAudioInstance = createAudioInstance;
|
||||
@@ -2,86 +2,97 @@
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("client", "clientController");
|
||||
// Modules
|
||||
const path = require('path');
|
||||
const fork = require('child_process').fork;
|
||||
const discordBotPath = path.resolve('discord-bot/app.js');
|
||||
|
||||
let botChildProcess, tempRes;
|
||||
const { status, join, leave } = require("./commandController")
|
||||
|
||||
/**
|
||||
* Bot Process Object Builder
|
||||
*
|
||||
* This construnctor is used to easily pass commands to the bot process
|
||||
* Get an object of client guilds
|
||||
* @param req The express request which includes the discord client
|
||||
* @returns
|
||||
*/
|
||||
class BPOB {
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
function getGuilds(req) {
|
||||
return req.discordClient.guilds.cache.map(guild => guild.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an object of the channels in a guild
|
||||
* @param {*} guildId The Guild ID to check the channels of
|
||||
* @param {*} req The request object to use to check the discord client
|
||||
*/
|
||||
function getChannels(guildId, req) {
|
||||
const guild = req.discordClient.guilds.find(guildId);
|
||||
log.DEBUG("Found Guild channels with guild", guild.channels, guild);
|
||||
return guild.channels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check to see if a given guild has a given channel
|
||||
* @param {*} guildId The guild ID to check if the channel exists
|
||||
* @param {*} channelId The channel ID to check if exists in the guild
|
||||
* @param {*} req The express request param to use the discord client
|
||||
* @returns {true|false}
|
||||
*/
|
||||
function checkIfGuildHasChannel(guildId, channelId, req){
|
||||
const guildChannels = getChannels(guildId, req)
|
||||
const checkedChannel = guildChannels.find(c => c.id === channelId);
|
||||
if (!checkedChannel) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function getGuildFromChannel(channelId, req){
|
||||
const channel = req.discordClient.channels.cache.get(channelId);
|
||||
|
||||
if (!channel) return new Error("Error getting channel from client");
|
||||
|
||||
if (channel.guild) return channel.guild;
|
||||
|
||||
return new Error("No Guild found with the given ID");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Status of the discord process
|
||||
*/
|
||||
exports.getStatus = (req, res) => {
|
||||
if (!botChildProcess) return res.sendStatus(200);
|
||||
botChildProcess.send(new BPOB("Status"));
|
||||
tempRes = res;
|
||||
log.INFO("Getting the status of the bot");
|
||||
guildIds = getGuilds(req);
|
||||
log.DEBUG("Guild IDs: ", guildIds);
|
||||
var guildStatuses = []
|
||||
for (const guildId of guildIds){
|
||||
status({guildID: guildId, callback: (statusObj) => {
|
||||
log.DEBUG("Status Object string: ", statusObj);
|
||||
guildStatuses.push(statusObj);
|
||||
}});
|
||||
}
|
||||
return res.status(200).json(guildStatuses);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the bot and join the server and preset specified
|
||||
*/
|
||||
exports.joinServer = (req, res) => {
|
||||
const channelID = req.body.channelID;
|
||||
const channelId = req.body.channelID;
|
||||
const presetName = req.body.presetName;
|
||||
const guildObj = getGuildFromChannel(channelId, req);
|
||||
|
||||
if (!channelID || !presetName) return res.status(400).json({'message': "Channel ID or Preset Name not present in the request"});
|
||||
// Start the bot
|
||||
botChildProcess = fork(discordBotPath);
|
||||
|
||||
// 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;
|
||||
}
|
||||
})
|
||||
if (!channelId || !presetName || !guildObj) return res.status(400).json({'message': "Request does not have all components to proceed"});
|
||||
|
||||
// join the sever
|
||||
join({guildID: guildObj.id, guildObj: guildObj, channelID: channelId, callback: () => {
|
||||
return res.sendStatus(202);
|
||||
}});
|
||||
}
|
||||
|
||||
/**
|
||||
* Leaves the server if it's in one
|
||||
*/
|
||||
exports.leaveServer = (req, res) => {
|
||||
if (!botChildProcess) return res.sendStatus(200)
|
||||
botChildProcess.send(new BPOB("Leave"));
|
||||
tempRes = res;
|
||||
log.INFO("Leaving the server");
|
||||
const guildIds = getGuilds(req);
|
||||
log.DEBUG("Guild IDs: ", guildIds);
|
||||
for (const guildId of guildIds){
|
||||
leave({guildID: guildId, callback: (response) => {
|
||||
log.DEBUG("Response from leaving server on guild ID", guildId, response);
|
||||
}});
|
||||
}
|
||||
return res.sendStatus(202);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
// Debug
|
||||
// const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
// const log = new DebugBuilder("client", "clientController");
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("client", "clientController");
|
||||
// Configs
|
||||
const config = require("../config/clientConfig");
|
||||
const modes = require("../config/modes");
|
||||
// Modules
|
||||
const { executeAsyncConsoleCommand } = require("../utilities/executeConsoleCommands.js");
|
||||
// Utilities
|
||||
const updateConfig = require("../utilities/updateConfig");
|
||||
const updatePreset = require("../utilities/updatePresets");
|
||||
@@ -29,6 +31,35 @@ function checkBodyForPresetFields(req, res, callback) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
async function checkLocalIP() {
|
||||
let ipAddr;
|
||||
if (process.platform === "win32") {
|
||||
// Windows
|
||||
var networkConfig = await executeAsyncConsoleCommand("ipconfig");
|
||||
log.DEBUG('Network Config: ', networkConfig);
|
||||
var networkConfigLines = networkConfig.split("\n").filter(line => {
|
||||
if (!line.includes(":")) return false;
|
||||
|
||||
line = line.split(":");
|
||||
|
||||
if (!line.length === 2) return false;
|
||||
|
||||
return true;
|
||||
}).map(line => {
|
||||
line = line.split(':', 1);
|
||||
line[0] = String(line[0]).replace("/\./g", "").trim();
|
||||
line[1] = String(line[1].replace(/[\r|\n]/g, ""))
|
||||
return line;
|
||||
});
|
||||
log.DEBUG("Parsed IP Config Results: ", networkConfigLines);
|
||||
return networkConfigLines['IPv4 Address'];
|
||||
}
|
||||
else {
|
||||
// Linux
|
||||
var networkConfig = await executeAsyncConsoleCommand("ip addr");
|
||||
}
|
||||
}
|
||||
|
||||
/** Check in with the server
|
||||
* If the bot has a saved ID, check in with the server to update any information or just check back in
|
||||
* If the bot does not have a saved ID, it will attempt to request a new ID from the server
|
||||
@@ -40,6 +71,7 @@ exports.checkIn = async () => {
|
||||
// ID was not found in the config, creating a new node
|
||||
reqOptions = new requests.requestOptions("/nodes/newNode", "POST");
|
||||
delete config.clientConfig.id;
|
||||
config.clientConfig.ip = checkLocalIP();
|
||||
requests.sendHttpRequest(reqOptions, JSON.stringify(config.clientConfig), (responseObject) => {
|
||||
// Update the client's ID if the server accepted it
|
||||
if (responseObject.statusCode === 202) {
|
||||
|
||||
163
Client/controllers/commandController.js
Normal file
163
Client/controllers/commandController.js
Normal file
@@ -0,0 +1,163 @@
|
||||
require('dotenv').config();
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("client", "commandController");
|
||||
// Modules
|
||||
const { joinVoiceChannel, VoiceConnectionStatus, getVoiceConnection, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require("@discordjs/voice");
|
||||
const { OpusEncoder } = require("@discordjs/opus");
|
||||
const { calcRmsSync } = require("../utilities/rmsCalculator.js");
|
||||
// Utilities
|
||||
const {replyToInteraction} = require("../utilities/messageHandler.js");
|
||||
const {createAudioInstance} = require("../controllers/audioController.js");
|
||||
const { all } = require('../routes/index.js');
|
||||
|
||||
// Declare the encoder
|
||||
const encoder = new OpusEncoder(48000, 2);
|
||||
const noiseGateOpen = process.env.AUDIO_NOISE_GATE_OPEN ?? 100;
|
||||
|
||||
/**
|
||||
* Join the specified voice channel
|
||||
*
|
||||
* @param interaction Message interaction from discord
|
||||
* @param {string||any} guildID The specified Guild ID if this function is run from the client instead of from an interaction in Discord
|
||||
* @param {string||any} channelID The channel ID to join
|
||||
* @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
|
||||
*/
|
||||
exports.join = async function join({interaction= undefined, guildID= undefined, channelID = undefined, guildObj = undefined, callback = undefined}){
|
||||
if (interaction){
|
||||
const voiceChannel = interaction.options.getChannel('voicechannel');
|
||||
channelID = voiceChannel.id;
|
||||
guildID = interaction.guildId;
|
||||
guildObj = interaction.guild;
|
||||
if (interaction) replyToInteraction(interaction, `Ok, Joining ${voiceChannel.name}`);
|
||||
}
|
||||
log.DEBUG("Channel ID: ", channelID)
|
||||
log.DEBUG("Guild ID: ", guildID)
|
||||
|
||||
const vcConnectionObj = {
|
||||
channelId: channelID,
|
||||
guildId: guildID,
|
||||
adapterCreator: guildObj.voiceAdapterCreator,
|
||||
selfMute: false,
|
||||
selfDeaf: false,
|
||||
};
|
||||
|
||||
// Join the voice channel
|
||||
const voiceConnection = await joinVoiceChannel(vcConnectionObj);
|
||||
|
||||
// Create the audio stream instance
|
||||
const audioInstance = await createAudioInstance();
|
||||
log.VERBOSE("Audio Instance: ", audioInstance);
|
||||
|
||||
// Play audio data when it's received from the stream
|
||||
audioInstance.on('data', buffer => {
|
||||
buffer = Buffer.from(buffer);
|
||||
//log.VERBOSE("Audio buffer: ", buffer);
|
||||
// Check intensity of audio and only play when audio is present (no white noise/static)
|
||||
volume = Math.trunc(calcRmsSync(buffer, buffer.length));
|
||||
|
||||
if (parseInt(volume) > parseInt(noiseGateOpen)) {
|
||||
//log.VERBOSE("Noisegate and buffer volume: ", (parseInt(volume) > parseInt(noiseGateOpen)), noiseGateOpen, volume);
|
||||
const encodedBuffer = encoder.encode(buffer);
|
||||
voiceConnection.playOpusPacket(encodedBuffer);
|
||||
}
|
||||
});
|
||||
|
||||
audioInstance.start();
|
||||
|
||||
// Handle state changes in the voice connection
|
||||
voiceConnection.on('stateChange', async (oldState, newState) => {
|
||||
//log.VERBOSE("VoiceConnection state Changed from state: ", oldState, "\n\nto state: ", newState);
|
||||
log.DEBUG("VoiceConnection state Changed from: ", oldState.status, "to: ", newState.status);
|
||||
|
||||
// Ready -> Connecting
|
||||
if (oldState.status === VoiceConnectionStatus.Ready && newState.status === VoiceConnectionStatus.Connecting) {
|
||||
log.DEBUG("Configuring Network");
|
||||
voiceConnection.configureNetworking();
|
||||
return;
|
||||
}
|
||||
|
||||
// Ready -> Disconnected
|
||||
if (oldState.status === VoiceConnectionStatus.Ready && newState.status === VoiceConnectionStatus.Disconnected) {
|
||||
log.DEBUG("Attempting to reconnect the voice connection");
|
||||
voiceConnection = joinVoiceChannel(vcConnectionObj);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ready
|
||||
if (newState.status === VoiceConnectionStatus.Ready){
|
||||
log.DEBUG("Bot connected to voice channel");
|
||||
return;
|
||||
}
|
||||
|
||||
// Destroyed
|
||||
if (newState.status === VoiceConnectionStatus.Destroyed){
|
||||
log.DEBUG("Quitting audio instance");
|
||||
audioInstance.quit();
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
voiceConnection.on('error', async (error) => {
|
||||
log.ERROR("Voice Connection Error: ", error);
|
||||
})
|
||||
|
||||
if (guildID && callback) return callback();
|
||||
else return;
|
||||
}
|
||||
|
||||
/**
|
||||
* If in a voice channel for the specified guild, leave
|
||||
*
|
||||
* @param interaction Message interaction from discord
|
||||
* @param guildID
|
||||
* @param callback
|
||||
*/
|
||||
exports.leave = async function leave({interaction = undefined, guildID= undefined, callback = undefined}) {
|
||||
if(interaction) {
|
||||
guildID = interaction.guild.id;
|
||||
}
|
||||
const voiceConnection = getVoiceConnection(guildID);
|
||||
|
||||
let response;
|
||||
if (!voiceConnection){
|
||||
response = "Not in a voice channel."
|
||||
if (interaction) return replyToInteraction(interaction, response);
|
||||
else callback(response);
|
||||
}
|
||||
voiceConnection.destroy();
|
||||
|
||||
response = "Goodbye"
|
||||
if (interaction) return replyToInteraction(interaction, response);
|
||||
else callback(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the voice status of the bots
|
||||
* @param {*} param0
|
||||
* @returns
|
||||
*/
|
||||
exports.status = async function status({interaction= undefined, guildID= undefined, callback = undefined}) {
|
||||
//if (!interaction && !guildID) // Need error of sorts
|
||||
if (interaction){
|
||||
guildID = interaction.guild.id;
|
||||
}
|
||||
const voiceConnection = getVoiceConnection(guildID);
|
||||
|
||||
const statusObj = {
|
||||
"guildID": guildID,
|
||||
"voiceConnection": typeof g !== 'undefined' ? true : false // True if there is a voice connection, false if undefined
|
||||
}
|
||||
|
||||
log.DEBUG('Status Object: ', statusObj);
|
||||
|
||||
// get the status and return it accordingly (message reply / module)
|
||||
|
||||
if (interaction) {
|
||||
return replyToInteraction(interaction, "Pong! I have Aids and now you do too!");
|
||||
}
|
||||
else {
|
||||
callback(statusObj);
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// Debug
|
||||
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js";
|
||||
const log = new ModuleDebugBuilder("bot", "join");
|
||||
// Modules
|
||||
import { joinVoiceChannel, VoiceConnectionStatus } from "@discordjs/voice";
|
||||
import {replyToInteraction} from "../utilities/messageHandler.js";
|
||||
import {createAudioInstance} from "../controllers/audioController.js";
|
||||
import OpusEncoderPkg from "@discordjs/opus";
|
||||
|
||||
// Declare the encoder (module is incompatible modern import method)
|
||||
const { OpusEncoder } = OpusEncoderPkg;
|
||||
const encoder = new OpusEncoder(48000, 2);
|
||||
|
||||
/**
|
||||
* Join the specified voice channel
|
||||
*
|
||||
* @param interaction Message interaction from discord
|
||||
* @param {string||any} guildID The specified Guild ID if this function is run from the client instead of from an interaction in Discord
|
||||
* @param {string||any} channelID The channel ID to join
|
||||
* @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
|
||||
*/
|
||||
export default async function join({interaction= undefined, guildID= undefined, channelID = undefined, guildObj = undefined, callback = undefined}){
|
||||
if (interaction){
|
||||
const voiceChannel = interaction.options.getChannel('voicechannel');
|
||||
channelID = voiceChannel.id;
|
||||
guildID = interaction.guildId;
|
||||
guildObj = interaction.guild;
|
||||
if (interaction) replyToInteraction(interaction, `Ok, Joining ${voiceChannel.name}`);
|
||||
}
|
||||
log.DEBUG("Channel ID: ", channelID)
|
||||
log.DEBUG("Guild ID: ", guildID)
|
||||
|
||||
const voiceConnection = joinVoiceChannel({
|
||||
channelId: channelID,
|
||||
guildId: guildID,
|
||||
adapterCreator: guildObj.voiceAdapterCreator,
|
||||
selfMute: false,
|
||||
selfDeaf: false,
|
||||
});
|
||||
|
||||
const audioInstance = await createAudioInstance();
|
||||
|
||||
audioInstance.on('audio', (buffer) => {
|
||||
buffer = Buffer.from(buffer);
|
||||
log.DEBUG("Audio buffer: ", buffer);
|
||||
const encoded = encoder.encode(buffer);
|
||||
// TODO Add a function here to check the volume of either buffer and only play audio to discord when there is audio to be played
|
||||
voiceConnection.playOpusPacket(encoded);
|
||||
})
|
||||
|
||||
// Exit the audio handler when the bot disconnects
|
||||
voiceConnection.on(VoiceConnectionStatus.Destroyed, () => {
|
||||
audioInstance.quit();
|
||||
})
|
||||
|
||||
if (guildID && callback) callback();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import {getVoiceConnection} from "@discordjs/voice";
|
||||
import {replyToInteraction} from "../utilities/messageHandler.js";
|
||||
// Debug
|
||||
//import debugBuilder from "../utilities/moduleDebugBuilder.js";
|
||||
//const log = new debugBuilder("bot", "leave");
|
||||
|
||||
/**
|
||||
* If in a voice channel for the specified guild, leave
|
||||
*
|
||||
* @param interaction Message interaction from discord
|
||||
* @param guildID
|
||||
* @param callback
|
||||
*/
|
||||
export default async function leave({interaction = undefined, guildID= undefined, callback = undefined}) {
|
||||
if(interaction) {
|
||||
guildID = interaction.guild.id;
|
||||
}
|
||||
const voiceConnection = getVoiceConnection(guildID);
|
||||
|
||||
let response;
|
||||
if (!voiceConnection){
|
||||
response = "Not in a voice channel."
|
||||
if (interaction) return replyToInteraction(interaction, response);
|
||||
else callback(response);
|
||||
}
|
||||
voiceConnection.destroy();
|
||||
|
||||
response = "Goodbye"
|
||||
if (interaction) return replyToInteraction(interaction, response);
|
||||
else callback(response);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Utilities
|
||||
import { replyToInteraction } from '../utilities/messageHandler.js';
|
||||
|
||||
export default function ping(interaction) {
|
||||
return replyToInteraction(interaction, "Pong! I have Aids and now you do too!");
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// Debug
|
||||
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js";
|
||||
const log = new ModuleDebugBuilder("bot", "status");
|
||||
// Modules
|
||||
import {getVoiceConnection} from "@discordjs/voice";
|
||||
// Utilities
|
||||
import { replyToInteraction } from '../utilities/messageHandler.js';
|
||||
|
||||
|
||||
export default async function status({interaction= undefined, guildID= undefined, callback = undefined}) {
|
||||
//if (!interaction && !guildID) // Need error of sorts
|
||||
if (interaction){
|
||||
guildID = interaction.guild.id;
|
||||
}
|
||||
const voiceConnection = getVoiceConnection(guildID);
|
||||
|
||||
const statusObj = {
|
||||
"guildID": guildID, "voiceConnection": voiceConnection
|
||||
}
|
||||
|
||||
//log.DEBUG('Status Object: ', statusObj);
|
||||
|
||||
// get the status and return it accordingly (message reply / module)
|
||||
|
||||
if (interaction) {
|
||||
return replyToInteraction(interaction, "Pong! I have Aids and now you do too!");
|
||||
}
|
||||
else {
|
||||
callback(statusObj);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"TOKEN": "OTQzNzQyMDQwMjU1MTE1MzA0.Yg3eRA.ZxEbRr55xahjfaUmPY8pmS-RHTY",
|
||||
"ApplicationID": "943742040255115304",
|
||||
"GuildID": "367396189529833472",
|
||||
"DeviceID": "5",
|
||||
"DeviceName": "VoiceMeeter Aux Output (VB-Audi"
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// Config
|
||||
import { getDeviceID } from '../utilities/configHandler.js';
|
||||
// Modules
|
||||
import alsaInstance from 'alsa-capture';
|
||||
import { returnAlsaDeviceObject } from "../utilities/executeConsoleCommands.js";
|
||||
// Debug
|
||||
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js";
|
||||
// Global Vars
|
||||
const log = new ModuleDebugBuilder("bot", "audioController");
|
||||
|
||||
/**
|
||||
* Checks to make sure the selected audio device is available and returns the device object (PortAudio Device Info)
|
||||
* At least one option must be supplied, it will prefer ID to device name
|
||||
*
|
||||
* @param deviceName The name of the device being queried
|
||||
* @param deviceId The ID of the device being queried
|
||||
* @returns {unknown}
|
||||
*/
|
||||
export async function confirmAudioDevice({deviceName = undefined, deviceId = undefined}){
|
||||
const deviceList = await getAudioDevices();
|
||||
if (!deviceName && !deviceId) throw new Error("No device given");
|
||||
if (deviceId) return deviceList.find(device => device.id === deviceId);
|
||||
if (deviceName) return deviceList.find(device => device.name === deviceName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a list of the audio devices connected with input channels
|
||||
*
|
||||
* @returns {unknown[]}
|
||||
*/
|
||||
export async function getAudioDevices(){
|
||||
// Exec output contains both stderr and stdout outputs
|
||||
const deviceList = await returnAlsaDeviceObject();
|
||||
log.DEBUG("Device list: ", deviceList);
|
||||
|
||||
return deviceList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and return the audio instance from the saved settings
|
||||
* TODO Allow the client to save and load these settings dynamically
|
||||
*
|
||||
* @returns new portAudio.AudioIO
|
||||
*/
|
||||
export async function createAudioInstance() {
|
||||
const selectedDevice = await confirmAudioDevice({deviceId: getDeviceID()});//{deviceName: "VoiceMeeter VAIO3 Output (VB-Au"});
|
||||
log.DEBUG("Device selected from config: ", selectedDevice);
|
||||
// Create an instance of AudioIO with outOptions (defaults are as below), which will return a WritableStream
|
||||
return new alsaInstance({
|
||||
channels: 2,
|
||||
format: "S16_BE",
|
||||
rate: 48000,
|
||||
device: selectedDevice.name ?? "default", // Use -1 or omit the deviceId to select the default device
|
||||
periodSize: 100, //(48000 / 1000) * 20, //(48000 * 16 * 2) / 1000 * 20 // (48000 * (16 / 8) * 2) / 60 / 1000 * 20 //0.025 * 48000 / 2
|
||||
periodTime: undefined,
|
||||
// highwaterMark: 3840
|
||||
});
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
// Debug
|
||||
import ModuleDebugBuilder from "./moduleDebugBuilder.js";
|
||||
const log = new ModuleDebugBuilder("bot", "configHandler");
|
||||
// Modules
|
||||
import { readFileSync } from 'fs';
|
||||
import path from "path";
|
||||
|
||||
export function getConfig() {
|
||||
return JSON.parse(readFileSync(path.resolve("discord-bot/config/botConfig.json")));
|
||||
}
|
||||
|
||||
export function getTOKEN() {
|
||||
const parsedJSON = getConfig();
|
||||
const token = parsedJSON.TOKEN;
|
||||
|
||||
log.DEBUG("Discord API Token: ", token)
|
||||
return token;
|
||||
}
|
||||
|
||||
export function getGuildID() {
|
||||
const parsedJSON = getConfig();
|
||||
const guildID = parsedJSON.GuildID;
|
||||
|
||||
log.DEBUG("Guild ID: ", guildID);
|
||||
return guildID;
|
||||
}
|
||||
|
||||
export function getApplicationID() {
|
||||
const parsedJSON = getConfig();
|
||||
const appID = parsedJSON.ApplicationID;
|
||||
|
||||
log.DEBUG("Application ID: ", appID);
|
||||
return appID;
|
||||
}
|
||||
|
||||
export function getDeviceID(){
|
||||
const parsedJSON = getConfig();
|
||||
const deviceID = parseInt(parsedJSON.DeviceID);
|
||||
|
||||
log.DEBUG("Device ID: ", deviceID);
|
||||
return deviceID;
|
||||
}
|
||||
|
||||
export function getDeviceName(){
|
||||
const parsedJSON = getConfig();
|
||||
const deviceName = parsedJSON.DeviceName;
|
||||
|
||||
log.DEBUG("Device Name: ", deviceName);
|
||||
return deviceName;
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
2533
Client/package-lock.json
generated
2533
Client/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -2,17 +2,30 @@
|
||||
"name": "client",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"start": "node ./bin/www"
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"preinstall": "echo preinstall",
|
||||
"postinstall": "echo postinstall"
|
||||
},
|
||||
"dependencies": {
|
||||
"convert-units": "^2.3.4",
|
||||
"cookie-parser": "~1.4.4",
|
||||
"debug": "~2.6.9",
|
||||
"dotenv": "16.0.3",
|
||||
"debug": "^4.3.4",
|
||||
"ejs": "~2.6.1",
|
||||
"express": "~4.16.1",
|
||||
"http-errors": "~1.6.3",
|
||||
"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",
|
||||
"naudiodon": "^2.3.6"
|
||||
}
|
||||
}
|
||||
|
||||
26
Client/setup.sh
Normal file
26
Client/setup.sh
Normal file
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Check if the user is root
|
||||
if [ "$EUID" -ne 0 ]
|
||||
then echo "Please run as root"
|
||||
exit
|
||||
fi
|
||||
|
||||
# Check for updates
|
||||
apt-get update
|
||||
|
||||
# Install Node Repo
|
||||
curl -fsSL https://deb.nodesource.com/setup_current.x | sudo -E bash -
|
||||
|
||||
# Update the system
|
||||
apt-get update
|
||||
apt-get upgrade -y
|
||||
|
||||
# Install the necessary packages
|
||||
apt-get install -y nodejs npm libopus-dev gcc make alsa-utils libasound2 libasound2-dev libpulse-dev pulseaudio apulse
|
||||
|
||||
# Ensure pulse audio is running
|
||||
pulseaudio
|
||||
|
||||
# Install the node packages from the project
|
||||
npm i
|
||||
15
Client/update.sh
Normal file
15
Client/update.sh
Normal file
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
# Stating Message
|
||||
echo "<!-- UPDATING ---!>"
|
||||
|
||||
# TODO - Add an updater for Stable Diffusion API
|
||||
|
||||
# Update the git Repo
|
||||
git fetch -a -p
|
||||
git pull
|
||||
|
||||
# Install any new libraries
|
||||
npm i
|
||||
|
||||
# Update complete message
|
||||
echo "<!--- UPDATE COMPLETE! ---!>"
|
||||
36
Client/utilities/configHandler.js
Normal file
36
Client/utilities/configHandler.js
Normal file
@@ -0,0 +1,36 @@
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("client", "configController");
|
||||
// Modules
|
||||
const { readFileSync } = require('fs');
|
||||
const path = require("path");
|
||||
require('dotenv').config();
|
||||
|
||||
const GuildID = process.env.GUILD_ID;
|
||||
const ApplicationID = process.env.APPLICATION_ID;
|
||||
const DeviceID = parseInt(process.env.AUDIO_DEVICE_ID);
|
||||
const DeviceName = process.env.AUDIO_DEVICE_NAME;
|
||||
|
||||
function getGuildID() {
|
||||
log.DEBUG("Guild ID: ", GuildID);
|
||||
return GuildID;
|
||||
}
|
||||
exports.getGuildID = getGuildID;
|
||||
|
||||
function getApplicationID() {
|
||||
log.DEBUG("Application ID: ", ApplicationID);
|
||||
return ApplicationID;
|
||||
}
|
||||
exports.getApplicationID = getApplicationID;
|
||||
|
||||
function getDeviceID(){
|
||||
log.DEBUG("Device ID: ", DeviceID);
|
||||
return DeviceID;
|
||||
}
|
||||
exports.getDeviceID = getDeviceID;
|
||||
|
||||
function getDeviceName(){
|
||||
log.DEBUG("Device Name: ", DeviceName);
|
||||
return DeviceName;
|
||||
}
|
||||
exports.getDeviceName = getDeviceID;
|
||||
@@ -12,6 +12,11 @@ exports.DebugBuilder = class DebugBuilder {
|
||||
this.INFO = debug(`${appName}:${fileName}:INFO`);
|
||||
this.DEBUG = debug(`${appName}:${fileName}:DEBUG`);
|
||||
this.WARN = debug(`${appName}:${fileName}:WARNING`);
|
||||
this.ERROR = debug(`${appName}:${fileName}:ERROR`);
|
||||
this.VERBOSE = debug(`${appName}:${fileName}:VERBOSE`);
|
||||
this.ERROR = (...messageParts) => {
|
||||
const error = debug(`${appName}:${fileName}:ERROR`);
|
||||
error(messageParts);
|
||||
if (process.env.EXIT_ON_ERROR && process.env.EXIT_ON_ERROR > 0) setTimeout(process.exit, process.env.EXIT_ON_ERROR_DELAY ?? 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
49
Client/utilities/deployCommands.js
Normal file
49
Client/utilities/deployCommands.js
Normal 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);
|
||||
}
|
||||
})()
|
||||
}
|
||||
};
|
||||
@@ -1,17 +1,17 @@
|
||||
// Modules
|
||||
import { promisify } from 'util';
|
||||
import { exec } from "child_process";
|
||||
const { promisify } = require('util');
|
||||
const { exec } = require("child_process");
|
||||
// Debug
|
||||
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js";
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
// Global Vars
|
||||
const log = new ModuleDebugBuilder("bot", "executeConsoleCommand");
|
||||
const log = new DebugBuilder("client", "executeConsoleCommands");
|
||||
const execCommand = promisify(exec);
|
||||
|
||||
|
||||
export default async function executeAsyncConsoleCommand(consoleCommand) {
|
||||
async function executeAsyncConsoleCommand(consoleCommand) {
|
||||
// Check to see if the command is a real command
|
||||
// TODO needs to be improved
|
||||
const acceptableCommands = [ "arecord -L" ];
|
||||
const acceptableCommands = [ "arecord -L", 'ipconfig', 'ip addr' ];
|
||||
if (!acceptableCommands.includes(consoleCommand)) {
|
||||
log.WARN("Console command is not acceptable: ", consoleCommand);
|
||||
return undefined;
|
||||
@@ -26,8 +26,9 @@ export default async function executeAsyncConsoleCommand(consoleCommand) {
|
||||
// TODO add some error checking
|
||||
return output;
|
||||
}
|
||||
exports.executeAsyncConsoleCommand = executeAsyncConsoleCommand;
|
||||
|
||||
export async function returnAlsaDeviceObject() {
|
||||
async function returnAlsaDeviceObject() {
|
||||
const listAlsaDevicesCommand = "arecord -L";
|
||||
const commandResponse = await executeAsyncConsoleCommand(listAlsaDevicesCommand);
|
||||
const brokenCommand = String(commandResponse).split('\n');
|
||||
@@ -46,4 +47,6 @@ export async function returnAlsaDeviceObject() {
|
||||
}
|
||||
|
||||
return devices;
|
||||
}
|
||||
}
|
||||
|
||||
exports.returnAlsaDeviceObject = returnAlsaDeviceObject;
|
||||
9
Client/utilities/messageHandler.js
Normal file
9
Client/utilities/messageHandler.js
Normal file
@@ -0,0 +1,9 @@
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("client", "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));
|
||||
}
|
||||
21
Client/utilities/rmsCalculator.js
Normal file
21
Client/utilities/rmsCalculator.js
Normal file
@@ -0,0 +1,21 @@
|
||||
exports.calcRmsSync = (arr , n) => {
|
||||
var square = 0;
|
||||
var mean = 0;
|
||||
var root = 0;
|
||||
|
||||
// Calculate square.
|
||||
for (i = 0; i < n; i++) {
|
||||
square += Math.pow(arr[i], 2);
|
||||
}
|
||||
|
||||
// Calculate Mean.
|
||||
mean = (square / (n));
|
||||
|
||||
// Calculate Root.
|
||||
root = Math.sqrt(mean);
|
||||
|
||||
// Normalize the output
|
||||
root = root / 10
|
||||
|
||||
return root;
|
||||
}
|
||||
@@ -68,8 +68,9 @@ function convertFrequencyToHertz(frequency){
|
||||
* @returns {any} The object containing the different systems the bot is near
|
||||
*/
|
||||
exports.getPresets = function getPresets() {
|
||||
log.DEBUG(`Getting presets from directory: '${__dirname}'`);
|
||||
return JSON.parse(fs.readFileSync( "./config/radioPresets.json"));
|
||||
const presetDir = path.resolve("./config/radioPresets.json");
|
||||
log.DEBUG(`Getting presets from directory: '${presetDir}'`);
|
||||
return JSON.parse(fs.readFileSync(presetDir));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user