#create commands using slashcommandbuilder

1 messages · Page 1 of 1 (latest)

mystic panther
#

help

peak kraken
#

alright so whats your current command handler

#

just so I can get a sense of where you are at

mystic panther
#

const commands = [
{
name: 'ping',
description: 'Replies with Pong!',
},
{

name: 'picker',
description: 'picker'
},
{

name: 'delmsg',
description: 'deletes messages'

}

#

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

await rest.put(
  Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
  { body: commands },
);

console.log('Successfully reloaded application (/) commands.');

} catch (error) {
console.error(error);
}
})();

#

if (interaction.commandName === 'picker') {
//................ .................. ................... .......................

marble iris
#

So for reference, here's my current 'getGuilds' command (some code removed):

const command = new SlashCommandBuilder()
  .setName(`GetGuilds`.toLowerCase())
  .setDescription('[Bot] Get Guilds')
  .addIntegerOption(option =>
    option
      .setName('Page'.toLowerCase())
      .setDescription('Page of Guilds to View')
  )
;

export const data = command;
export const execute = async function execute(interaction, client) {
 // do stuff
};
#

@mystic panther Please use code blocks:

```js
<code/>
```

mystic panther
#
  const data = new SlashCommandBuilder()
    .setName('delmsg')
    .setDescription('deletes messages')
  .addIntegerOption(option => option.setName('int').setDescription('Enter an integer'))
    .setRequired(true)
    ```
will this work is this without errors?
peak kraken
#

uh

#

why don't you find out

marble iris
#

Your code is effectivly:

await rest.put(
      Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
      {
        body: [
          {
            name: 'ping',
            description: 'Replies with Pong!',
          },
          {
             name: 'picker',
            description: 'picker'
          },
          {
            name: 'delmsg',
            description: 'deletes messages'
          }
        ]
      },
    );
#

You want to move from hard-coded array, to files.

peak kraken
#

yes

marble iris
#

You want that part of the guide 'Individual Command Files'

peak kraken
#

give me a second to give an example command loader

mystic panther
#

ill create bot from scratch for easier

#

code

#

do i add the command builder to the main file or command file?

#

@marble iris

marble iris
peak kraken
#

now

#

this wont work if you just copy paste it in

#

thats why I added comments

#

so read the comments and try to work them into your code

#

and lemme make an example command file for a second

peak kraken
#

this isnt a handler

#

its more just

#

a loader

mystic panther
#

is my command file looking ok

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

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

actually yes

#

that looks really good

#

but

#

for the execute function

#

add a client variable

#

like this

mystic panther
#

async execute(client, interaction)
?

peak kraken
#

yes

mystic panther
#

ohh

peak kraken
#

since your no longer in the file which client is created

#

you'll need a reference to it

mystic panther
#

what do i put into main file?

marble iris
peak kraken
peak kraken
mystic panther
#

client.commands.set(command.data.name, command);
^

TypeError: Cannot read properties of undefined (reading 'name')

peak kraken
#

hm

mystic panther
#

const {Collection} = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');



client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    // Set a new item in the Collection
    // With the key as the command name and the value as the exported module
    client.commands.set(command.data.name, command);
}



const { clientId, guildId, token } = require('./config.json');

const commands = [];


for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    commands.push(command.data.toJSON());
}
#

hi

peak kraken
#

one sec

#

what does the command file look like

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

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

hm

mystic panther
#

client.commands.set(command.data.name, command);
^

TypeError: Cannot read properties of undefined (reading 'name')

#

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { MessageActionRow, MessageButton } = require('discord.js');
const wait = require('node:timers/promises').setTimeout;
const { SlashCommandBuilder } = require('@discordjs/builders');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

peak kraken
#

try changing commandsPath to just "./commands"

#

as ./ indicates the local directory

mystic panther
#
Error: Cannot find module 'commands\ping.js'
Require stack:
- C:\Users\unkno\OneDrive\Desktop\discord bot 2\bot.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:\Users\unkno\OneDrive\Desktop\discord bot 2\bot.js:49:18)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'C:\\Users\\unkno\\OneDrive\\Desktop\\discord bot 2\\bot.js' ]
}
#

after doing it

peak kraken
#

can you send your code

mystic panther
#
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});



const {Collection} = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');



client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join("./commands", file);
    const command = require(filePath);
    // Set a new item in the Collection
    // With the key as the command name and the value as the exported module
    client.commands.set(command.data.name, command);
}



const { clientId, guildId, token } = require('./config.json');

const commands = [];


for (const file of commandFiles) {
    const filePath = path.join("./commands", file);
    const command = require(filePath);
    commands.push(command.data.toJSON());
}

peak kraken
#

try to

#

theres prolly an obvious fix which I am blanking and missing

#

but try to

#

change ```js
const filePath = path.join("./commands", file);

to
```js
const filePath = `./commands/${file}`
mystic panther
#

Error: Cannot find module './config.json'
Require stack:
- C:\Users\unkno\OneDrive\Desktop\discord bot 2\bot.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:\Users\unkno\OneDrive\Desktop\discord bot 2\bot.js:57:38)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'C:\\Users\\unkno\\OneDrive\\Desktop\\discord bot 2\\bot.js' ]
}
peak kraken
#

huh

#

do you still have your config file

mystic panther
#

i never had it

peak kraken
#

ah

#

its trying to

#

access a config file

mystic panther
#

ohh

peak kraken
#

which doesnt exist

mystic panther
#



C:\Users\unkno\OneDrive\Desktop\discord bot 2>node bot.js
node:internal/modules/cjs/loader:1176
    throw err;
    ^

SyntaxError: C:\Users\unkno\OneDrive\Desktop\discord bot 2\config.json: Unexpected end of JSON input
    at parse (<anonymous>)
    at Object.Module._extensions..json (node:internal/modules/cjs/loader:1173:22)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:\Users\unkno\OneDrive\Desktop\discord bot 2\bot.js:57:38)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)```gsdkmgo
peak kraken
#

the config file doesnt have any data it seems

#

try adding

mystic panther
#

can you send me the data required

peak kraken
#
{
  clientId: 0,
  guildId: 0,
  token: 0,
}
#

this is temp

#

and if your token is based off this config file

mystic panther
peak kraken
#

oh right json is specific with that

#
{
  "clientId": 0,
  "guildId": 0,
  "token": 0
}
mystic panther
#

bot started now but the command is not there'

peak kraken
#

try restarting discord or try to click on the bot icon

#

as slash commands are

#

buggy

mystic panther
#

nop

#

doesnt work

peak kraken
#

hm

mystic panther
#

@peak kraken ill go rest ok im tired sorry

peak kraken
#

this part

for (const file of commandFiles) {
    const filePath = path.join("./commands", file);
    const command = require(filePath);
    // Set a new item in the Collection
    // With the key as the command name and the value as the exported module
    client.commands.set(command.data.name, command);
}

try removing this

client.commands.set(command.data.name, command);

and adding in the client.on('ready' () => ....
this code https://discordjs.guide/interactions/slash-commands.html#global-commands