Files
DRB-CnC/Client/controllers/botController.js
2023-03-26 20:17:38 -04:00

97 lines
3.1 KiB
JavaScript

// Debug
const { DebugBuilder } = require("../utilities/debugBuilder.js");
const log = new DebugBuilder("client", "clientController");
// Modules
const { status, join, leave } = require("./commandController")
/**
* Get an object of client guilds
* @param req The express request which includes the discord client
* @returns
*/
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) => {
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);
if (!statusObj.voiceConnection) guildStatuses.push({ guildId : 201 });
else guildStatuses.push({ guildId: 202 })
}});
}
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 presetName = req.body.presetName;
const guildObj = getGuildFromChannel(channelId, req);
if (!channelId || !presetName || !guildId) return res.status(400).json({'message': "Request does not have all components to proceed"});
// join the sever
join({guildID: guildId, guildObj: guildObj, channelID: channelId, callback: () => {
return req.sendStatus(202);
}});
}
/**
* Leaves the server if it's in one
*/
exports.leaveServer = (req, res) => {
const guildIds = getGuilds(req);
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);
}});
}
}