NamVr / DiscordBot-Template

A boilerplate / template for discord.js v14 bots with 100% coverage of Discord API, command handler, error handler based on https://discordjs.guide/
https://djs.docs.namanvrati.me/
Apache License 2.0
316 stars 74 forks source link

[BUG] Button issue #31

Closed ODHG1 closed 6 months ago

ODHG1 commented 6 months ago

Describe the bug I made a command with a button (a prefix command), when i try linking the button or pressing it without even linking it, it crashes and says that command is undefined in slashCreate, thing is, i didn't touch slashCreate while making this, and command is defined in that file, else no slash command would even work. Error

TypeError: Cannot read properties of undefined (reading 'data')
    at Object.execute (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\events\slashCreate.js:27:30)
    at Client.<anonymous> (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\bot.js:60:35)
    at Client.emit (node:events:526:35)
    at InteractionCreateAction.handle (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
    at module.exports [as INTERACTION_CREATE] (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\websocket\WebSocketManager.js:355:31)
    at WebSocketManager.<anonymous> (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\websocket\WebSocketManager.js:239:12)
    at WebSocketManager.emit (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:282:31)
    at WebSocketShard.<anonymous> (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\@discordjs\ws\dist\index.js:1173:51)
    at WebSocketShard.emit (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:282:31)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:397:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Additional context Here is my slashCreate (i only added cooldowns following the djs guide):

/**
 * @file Slash Command Interaction Handler
 * @author Naman Vrati
 * @since 3.0.0
 * @version 3.3.0
 */
const {Collection} = require("discord.js");

module.exports = {
    name: "interactionCreate",

    /**
     * @description Executes when an interaction is created and handle it.
     * @author Naman Vrati
     * @param {import('discord.js').CommandInteraction & { client: import('../typings').Client }} interaction The interaction which was created
     */

    async execute(interaction) {

        // Deconstructed client from interaction object.
        const { client } = interaction;

        // Checks if the interaction is a command (to prevent weird bugs)
        const { cooldowns } = interaction.client;
        const command = client.slashCommands.get(interaction.commandName);

        if (!cooldowns.has(command.data.name)) {
            cooldowns.set(command.data.name, new Collection());
        }

        const now = Date.now();
        const timestamps = cooldowns.get(command.data.name);
        const defaultCooldownDuration = 3;
        const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;

        if (timestamps.has(interaction.user.id)) {
            const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;

            if (now < expirationTime) {
                const expiredTimestamp = Math.round(expirationTime / 1_000);
                return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`, ephemeral: true });
            }
        }

        timestamps.set(interaction.user.id, now);
        setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);

        if (!interaction.isChatInputCommand()) return;

        // If the interaction is not a command in cache.

        if (!command) return;

        // A try to executes the interaction.

        try {
            await command.execute(interaction);
        } catch (err) {
            console.error(err);
            await interaction.reply({
                content: "There was an issue while executing that command!",
                ephemeral: true,
            });
        }

    },
};

Line 60 in bot.js is async (...args) => await event.execute(...args, client) Whole loop would be

for (const file of eventFiles) {
    const event = require(`./events/${file}`);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args, client));
    } else {
        client.on(
            event.name,
            async (...args) => await event.execute(...args, client)
        );
    }
}
ODHG1 commented 6 months ago

Oh i forgot the most important part lol the command:

       const { EmbedBuilder, ButtonBuilder, ActionRowBuilder, ButtonStyle, ChannelType } = require('discord.js')
        const { channel, author, content } = (message)
        if (channel.type === ChannelType.DM){  
        const openticket = new ButtonBuilder()
        .setCustomId('openticket')
        .setLabel('🎟️ Open Modmail Ticket')
        .setStyle(ButtonStyle.Danger)
        const row69 = new ActionRowBuilder()
        .addComponents(openticket)
        const embed69 = new EmbedBuilder()
        .setTitle('FrankyBotv2 Modmail')
        .setColor('DarkBlue')
        .setDescription(`Welcome, <@${message.author.id}>! You can use this menu to contact the staff members of the server. You may use this menu to report people or ask questions from the moderators. 👍\n**Please note that abusing this feature will lead to punishment**`)
        .setFooter({text:'Click the button below to open a ticket!'})
        channel.send({embeds: [embed69], components: [row69]})}}}

I removed the button linking part here just because i had a doubt about it

NamVr commented 6 months ago

On reading your error, it is clear that the error is in slashCreate.js, it appears to me that it is a modified slashCreate file.

The error is in line 27 (which you have created a custom cooldown system):

if (!cooldowns.has(command.data.name)) {

command is undefined. It appears to me that you have added the cooldown command section (or do I say, copy pasted) at wrong place. The original slash file is checking whether it is a slash interaction or not. Please run your cooldown system AFTER verification of interaction. That should fix your issue.

NamVr commented 6 months ago

On a side note, I will be removing the bug label because it is not a bug on the template end. Feel free to reach out to us on discord if you want further help! https://discord.gg/N7AJFYf8EP