2603003199
2603003199

Reputation: 46

Discord.js dynamic command handler not working

So I followed the dynamic command handler guide on the discord.js guide site, and it turns out every time I try to let it execute a command, it says that the execute function is undefined, no matter how I tried to fix it. To make sure that my code is supposed to be working, I downloaded the example code they had on the guide and ran it, which also didn’t work for some reason. My discord.js and node.js are all up to date.

Upvotes: -1

Views: 1408

Answers (1)

BotNC
BotNC

Reputation: 56

Since I do not know your current files/code, I can provide an example.
Also, in this example, I will be assuming that you have named your bot variable client.

  • First, make sure you have a folder named commands.

  • On the top of your bot code (index.js or whatever it's called), add this line: const fs = require("fs");

  • In your bot code, after the bot definition (var client = new Discord.Client()), add these lines:

client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for(let file of commandFiles) {
  let command = require('./commands/' + file);
  client.commands.set(command.name, command);
}
  • And on your message event listener (assuming that you already have made some commands in the folder), replace your command if statement(s) with this:
// you can use other expressions to check if the command is there
// the commandname in the client.commands.get is the filename without .js
if(message.content.startsWith("commandname")) client.commands.get("commandname").execute(message, args);
  • Creating commands will be the process of creating JavaScript files in your commands folder. So in your commands folder, create a file (filename will be like "commandname.js" or something) and the content will be:
module.exports = {
  name: "commandname",
  description: "Command description here.",
  execute(message, args) {
    // Now you can do your command logic here
  }
}

I hope this helped! If it isn't clear, feel free to downvote.

Upvotes: 3

Related Questions