Files
DRB-CnC/Server/utilities/utils.js
Logan Cusano bfda15866e Streamlined joining and leaving autocomplete
- Removed custom command builder as it's no longer needed with autocomplete
2023-06-17 17:55:27 -04:00

136 lines
4.6 KiB
JavaScript

// Debug
const { DebugBuilder } = require("../utilities/debugBuilder");
const { clientObject } = require("./recordHelper");
const { readFileSync } = require('fs');
const log = new DebugBuilder("server", "utils");
const logAC = new DebugBuilder("server", "command-autocorrect");
const path = require('path');
// Convert a JSON object to a buffer for the DB
exports.JsonToBuffer = (jsonObject) => {
return Buffer.from(JSON.stringify(jsonObject))
}
// Convert a buffer from the DB to JSON object
exports.BufferToJson = (buffer) => {
return JSON.parse(buffer.toString());
}
/**
* **DISUSED**
*
* @param {string} presetName The present name to sanitize
* @returns {string} The sanitized preset name to be used elsewhere
*/
exports.SanitizePresetName = (presetName) => {
return String(presetName).toLowerCase().replace(/[\W_]+/g,"-")
}
/**
* Get online, offline and total members in a guild. Optionally a group can be specified to get members' statuses.
*
* @param interaction Discord interaction object
* @param param0.roleName {OPTIONAL} The role name to check the members in; Defaults to 'Bots'
*/
exports.getMembersInRole = async (interaction, roleName = "Bots" ) => {
log.DEBUG("Fetching all members");
var guild = await interaction.client.guilds.fetch({ guild: interaction.guild.id, cache: false }); //cache all members in the server
await guild.members.fetch({cache: false});
await guild.roles.fetch({cache: false});
log.VERBOSE("Guild: ", guild);
const role = await guild.roles.cache.find(role => role.name === roleName); //the role to check
log.DEBUG("Role to check members from: ", role);
log.DEBUG("Members of role: ", role.members);
// This is not working, can't get the status of the users, rest of join is untested
const onlineMembers = await role.members.filter(member => member.voice.channel !== null);
const offlineMembers = await role.members.filter(member => member.voice.channel === null);
const allMembers = await role.members;
log.VERBOSE("All members: ", allMembers, onlineMembers, offlineMembers)
return {
'online': onlineMembers,
'offline': offlineMembers,
'all': allMembers
}
}
/** Find a key in an object by its value
*
* @param {*} object The object to search
* @param {*} value The value to search the arrays in the object for
* @returns The key of the object that contains the value
*/
exports.getKeyByArrayValue = (object, value) => {
if (typeof value == "string") return Object.keys(object).find(key => object[key].includes(value));
const valueKey = Object.keys(value)[0];
return Object.keys(object).find(key => (object[key][valueKey] == value[valueKey]));
}
/**
* Check to see if the input is a valid JSON string
*
* @param {*} str The string to check for valud JSON
* @returns {true|false}
*/
exports.isJsonString = (str) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
/**
* Get all client IDs from the saved JSON file
*
* @returns Object of Client IDs
*/
exports.getAllClientIds = () => {
const jsonClientIds = JSON.parse(readFileSync(path.resolve(__dirname, '../clientIds.json')));
var clientObjects = [];
for (const jsonClientId of Object.keys(jsonClientIds)){
clientObjects.push(new clientObject({
_discord_id: jsonClientId,
_name: jsonClientIds[jsonClientId].name,
_client_id: jsonClientIds[jsonClientId].id
}))
}
return clientObjects;
}
/**
* Gets a client object froma discord client ID
*
* @param {*} clientId The discord client ID to get the client object of
* @returns {clientObject|undefined}
*/
exports.getClientObjectByClientID = (clientId) => {
const clientObjects = this.getAllClientIds();
log.DEBUG("All client IDs: ", clientObjects);
for (const clientObject of clientObjects){
if (clientObject.clientId == clientId) {
log.DEBUG("Found client ID from given ID: ", clientObject);
return clientObject
}
}
return undefined
}
exports.filterAutocompleteValues = async (interaction, options) => {
// Get the command used
const command = interaction.command;
// Find values that start with what the user is entering
const focusedValue = interaction.options.getFocused();
const filtered = options.filter(preset => preset.startsWith(focusedValue));
// Give the query response to the user
logAC.DEBUG("Focused Value: ", command, focusedValue, options, filtered);
await interaction.respond(
filtered.map(option => ({ name: option, value: option })),
);
}