Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug fixes #74

Merged
merged 2 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions src/commands/misc/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import getLocalCommands from '../../utils/getLocalCommands.js';
import mConfig from '../../config/messageConfig.js';

const COMMANDS_PER_PAGE = 8;
const INTERACTION_TIMEOUT = 300000; // 5 minutes
const INTERACTION_TIMEOUT = 300000;

const categorizeCommands = (commands) => {
const categorized = commands.reduce((acc, cmd) => {
Expand Down Expand Up @@ -48,7 +48,7 @@ export default {
run: async (client, interaction) => {
try {
const localCommands = await getLocalCommands();
const embedColor = mConfig.embedColorDefault || '#0099ff';
const embedColor = mConfig.embedColorDefault ?? '#0099ff';
const prefix = '!';

const commandOption = interaction.options.getString('command');
Expand All @@ -65,6 +65,11 @@ export default {
embedColor,
prefix
);
} else {
return await interaction.reply({
content: `Command "${commandOption}" not found.`,
ephemeral: true,
});
}
}

Expand All @@ -81,6 +86,11 @@ export default {
embedColor,
prefix
);
} else {
return await interaction.reply({
content: `Category "${categoryOption}" not found.`,
ephemeral: true,
});
}
}

Expand All @@ -103,22 +113,22 @@ export default {
async function showCommandDetails(interaction, command, embedColor, prefix) {
const embed = new EmbedBuilder()
.setTitle(`📖 Command: ${command.name}`)
.setDescription(command.description || 'No description available.')
.setDescription(command.description ?? 'No description available.')
.setColor(embedColor)
.addFields(
{
name: '🏷️ Category',
value: command.category || 'Uncategorized',
value: command.category ?? 'Uncategorized',
inline: true,
},
{
name: '⏳ Cooldown',
value: `${command.cooldown || 0}s`,
value: `${command.cooldown ?? 0}s`,
inline: true,
},
{
name: '🔒 Permissions',
value: command.userPermissions?.join(', ') || 'None',
value: command.userPermissions?.join(', ') ?? 'None',
inline: true,
},
{
Expand Down Expand Up @@ -182,7 +192,7 @@ async function showCommandDetails(interaction, command, embedColor, prefix) {
.setTitle(`📝 Examples for ${command.name}`)
.setColor(embedColor)
.setDescription(
command.examples?.join('\n') || 'No examples available.'
command.examples?.join('\n') ?? 'No examples available.'
);
await i.reply({ embeds: [examplesEmbed], ephemeral: true });
}
Expand All @@ -193,7 +203,6 @@ async function showCommandDetails(interaction, command, embedColor, prefix) {
interaction.editReply({ components: [row] });
});
}

async function showCategoryCommands(
interaction,
localCommands,
Expand All @@ -202,7 +211,15 @@ async function showCategoryCommands(
prefix
) {
const categorizedCommands = categorizeCommands(localCommands);
const categoryCommands = categorizedCommands[category] || [];
const categoryCommands = categorizedCommands[category] ?? [];

if (categoryCommands.length === 0) {
return interaction.reply({
content: `No commands found in the "${category}" category.`,
ephemeral: true,
});
}

const pages = createCommandPages(
categoryCommands,
category,
Expand Down Expand Up @@ -268,7 +285,6 @@ async function showCategoryCommands(
interaction.editReply({ components: [row] });
});
}

async function showCommandOverview(
interaction,
localCommands,
Expand Down
5 changes: 4 additions & 1 deletion src/events/ready/registerCommands.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ async function deleteUnusedCommands(
);

await Promise.all(
commandsToDelete.map(deleteCommand(applicationCommands, errorHandler))
commandsToDelete.map((cmd) =>
deleteCommand(applicationCommands, errorHandler)(cmd)
)
);
}

Expand Down Expand Up @@ -100,6 +102,7 @@ const deleteCommand = (applicationCommands, errorHandler) => async (cmd) => {
}
};


/**
* Processes a local command, updating or creating it as needed.
* @param {Collection} applicationCommands - The current application commands.
Expand Down
27 changes: 16 additions & 11 deletions src/events/validations/chatInputCommandValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,11 @@ const sendEmbedReply = async (
.setTimestamp();

await interaction.reply({ embeds: [embed], ephemeral });
} catch (err) {}
} catch (err) {
}
};


const getCachedData = async (key, fetchFunction) => {
const cachedItem = cache.get(key);
if (cachedItem) return cachedItem;
Expand All @@ -77,11 +79,13 @@ const initializeCommandMap = async () => {
};

const applyCooldown = (interaction, commandName, cooldownAmount) => {
if (isNaN(cooldownAmount) || cooldownAmount <= 0) {
throw new Error('Invalid cooldown amount');
}

const userCooldowns = cooldowns.get(commandName) || new Collection();
const now = Date.now();
const userId = `${interaction.user.id}-${
interaction.guild ? interaction.guild.id : 'DM'
}`;
const userId = `${interaction.user.id}-${interaction.guild ? interaction.guild.id : 'DM'}`;

if (userCooldowns.has(userId)) {
const expirationTime = userCooldowns.get(userId) + cooldownAmount;
Expand Down Expand Up @@ -118,13 +122,14 @@ export default async (client, errorHandler, interaction) => {
try {
const commandObject = commandMap.get(interaction.commandName);

if (!commandObject) {
return sendEmbedReply(
interaction,
mConfig.embedColorError,
'Command not found.'
);
}
if (!commandObject) {
return sendEmbedReply(
interaction,
mConfig.embedColorError,
'Command not found.'
);
}


if (interaction.isAutocomplete()) {
return await commandObject.autocomplete(client, interaction);
Expand Down
42 changes: 24 additions & 18 deletions src/handlers/eventHandler.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import path from 'path';
import { fileURLToPath } from 'url';
import getAllFiles from '../utils/getAllFiles.js';
import 'colors';
import fs from 'fs';

const __filename = fileURLToPath(import.meta.url);
Expand Down Expand Up @@ -33,7 +32,12 @@ const loadEventFile = async (
eventRegistry
) => {
try {
const { default: eventFunction } = await import(`file://${eventFile}`);
const { default: eventFunction } = await import(
encodeURI(`file://${eventFile}`)
);
if (typeof eventFunction !== 'function') {
throw new Error(`Invalid or missing event function in ${eventFile}`);
}
const eventInfo = {
function: eventFunction,
fileName: path.basename(eventFile),
Expand All @@ -56,20 +60,27 @@ const loadEventFile = async (
* @param {Map} eventRegistry - The event registry.
*/
const processEventFolder = async (eventFolder, errorHandler, eventRegistry) => {
const eventFiles = getAllFiles(eventFolder);
let eventName = path.basename(eventFolder);
try {
const eventFiles = getAllFiles(eventFolder);
let eventName = path.basename(eventFolder);

if (eventName === 'validations') {
eventName = 'interactionCreate';
}
if (eventName === 'validations') {
eventName = 'interactionCreate';
}

const loadPromises = eventFiles
.filter((eventFile) => fs.lstatSync(eventFile).isFile())
.map((eventFile) =>
loadEventFile(eventFile, eventName, errorHandler, eventRegistry)
);
const loadPromises = eventFiles
.filter((eventFile) => fs.lstatSync(eventFile).isFile())
.map((eventFile) =>
loadEventFile(eventFile, eventName, errorHandler, eventRegistry)
);

await Promise.all(loadPromises);
await Promise.all(loadPromises);
} catch (error) {
errorHandler.handleError(error, {
type: 'processingEventFolder',
eventFolder,
});
}
};

/**
Expand Down Expand Up @@ -107,11 +118,6 @@ const loadEventHandlers = async (client, errorHandler) => {
handler: handler.fileName,
eventName,
});
console.error(
`Error executing event handler ${handler.fileName} for event ${eventName}:`
.red,
error
);
}
}
});
Expand Down
Loading