MunJitso
MunJitso

Reputation: 23

Slashcommands doesn't work with my discord.js bot

i posted a question before 'my discord.js bot doesn't reply to a user message even if there isn't any error'. Well, the solution works but just with messages, not with commmands.

I'm also activing applications.commands scope in OAuth2 of the bot.

I'm working on node 16.7.0 and these are installed packages :

the console doesn't show any error message but it shows these and it means that it's working :

Started refreshing application (/) commands.
Successfully reloaded application (/) commands.
Ready! Logged in as {mydiscord_bot_tag}

these are the file of my bot:

discord-bot/
├── node_modules
├── .env
├── public/
    |── index.js
    └── functions/
        |──handleCommands.js
        └──handleEvents.js
    └── events/
        |──interactionCreate.js
        └──ready.js
    └── commands/
        |── Information/
            └── ping.js
        └── Moderation
├── package-lock.json
└── package.json

index.js's code

const { Client, Intents, Collection } = require('discord.js');
const fs = require('fs');
require('dotenv').config();

const client = new Client({ intents:[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

client.commands = new Collection();

const functions = fs.readdirSync('./src/functions').filter(file => file.endsWith('.js'));
const commandsFolder = fs.readdirSync('./src/commands').filter(file => file.endsWith('.js'));
const eventFiles = fs.readdirSync('./src/events').filter(file => file.endsWith('.js'));

client.once('ready', () => {
    client.user.setPresence({ activities: [{ name: 'i am stuck ' }], status: 'dnd' });
});

(async () => {
    for (const file of functions) {
        require(`./functions/${file}`)(client);
    }
    client.handleEvents(eventFiles, './src/commands');
    client.handleCommands(commandsFolder, './src/events');
    client.login(process.env.token);
})();

functions/handleCommands.js's code

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');

const clientId = '878988418665816156';
const guildId = '879887194268008520';

module.exports = (client) => {
    client.handleCommands = async (commandsFolders, path) => {
        client.commandArray = [];
        for (const folder of commandsFolders) {
            const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
            for (const file of commandFiles) {
                const command = require(`../commands/${folder}/${file}`);
                client.commands.set(command.data.name, command);
                client.commandArray.push(command.data.toJSON);
            }
        }
        const rest = new REST({ version: '9' }).setToken(process.env.token);

        (async () => {
            try {
                console.log('Started refreshing application (/) commands.');

                await rest.put(
                    Routes.applicationGuildCommands(clientId, guildId),
                    { body: client.commandArray },
                );

                console.log('Successfully reloaded application (/) commands.');
            }
            catch (error) {
                console.error(error);
            }
        })();
    };
};

functions/handleEvents.js's code

module.exports = (client) => {
    client.handleEvents = async (eventFiles) => {
        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, (...args) => event.execute(...args, client));
            }
        }
    };
};

events/interactionCreate.js's code

module.exports = {
    name: 'interactionCreate',
    async execute(interaction, client) {
        if (!interaction.isCommand()) return;

        const command = client.commands.get(interaction.commandName);

        if (!command) return;

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

events/ready.js

module.exports = {
    name: 'ready',
    once: true,
    execute(client) {
        console.log(`Ready! Logged in as ${client.user.tag}`);
    },
};

commands/Information/ping.js's code

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        await interaction.reply('Pong!');
    },
};

So sorry about all these huge codes they was my whole folder :")

I hope reciving an answer, thanks already!

Upvotes: 1

Views: 1939

Answers (3)

Opilite Elix
Opilite Elix

Reputation: 30

I think too that @user16[…] ‘s method is easier, but When you use SlashCommandBuilder, you don’t need the builders subfolder at your defining. So instead this:

const { SlashCommandBuilder } = require('@discordjs/builders');

Try this:

const { SlashCommandBuilder } = require('discord.js');

Here an easy example (even if your code hasn’t any problem):

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        await interaction.reply('Pong!');
    },
};

And documentation: https://discordjs.guide/creating-your-bot/slash-commands.html#individual-command-files

Upvotes: 1

user16591251
user16591251

Reputation:

I used this (without builder):

client.on('interactionCreate', async (interaction) => {
  if (!interaction.isCommand()) return;

  if (interaction.commandName === 'yourCommand') {
    await interaction.reply({
    //your code
  });
  }
});

Upvotes: 0

codeboi
codeboi

Reputation: 150

this is the event which is triggered on a message.

client.on("message",message => {
    console.log(message);
});

i dont see this event in your code anywhere

Upvotes: 0

Related Questions