registering commands

I'm trying to create a script that registers commands globally but it doesn't work
21 Replies
d.js toolkit
d.js toolkit4mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button!
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
// Funkcja do ładowania komend
const loadCommands = async () => {
console.log('Ładowanie komend...');
try {
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
if (Array.isArray(command.data)) {
command.data.forEach(cmd => client.commands.set(cmd.name, { ...command, data: cmd }));
} else if (command.data && command.execute) {
client.commands.set(command.data.name, command);
} else {
console.error(`Błąd w pliku komendy: ${file}`);
}
}
console.log(`Załadowano ${client.commands.size} komend.`);
} catch (error) {
console.error('Błąd podczas ładowania komend:', error);
}
};

client.once('ready', async () => {
console.log(`Shard ${client.shard.ids[0]} gotowy!`);
logtail.info('Bot jest online!');
console.log('Bot jest gotowy!');
await loadCommands(); // Załaduj komendy

// Rejestracja komend globalnie (nadpisując stare)
await registerGlobalCommands(client);

setInterval(() => updatePresence(client), 60000); // Aktualizuj status co minutę
});
// Funkcja do ładowania komend
const loadCommands = async () => {
console.log('Ładowanie komend...');
try {
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
if (Array.isArray(command.data)) {
command.data.forEach(cmd => client.commands.set(cmd.name, { ...command, data: cmd }));
} else if (command.data && command.execute) {
client.commands.set(command.data.name, command);
} else {
console.error(`Błąd w pliku komendy: ${file}`);
}
}
console.log(`Załadowano ${client.commands.size} komend.`);
} catch (error) {
console.error('Błąd podczas ładowania komend:', error);
}
};

client.once('ready', async () => {
console.log(`Shard ${client.shard.ids[0]} gotowy!`);
logtail.info('Bot jest online!');
console.log('Bot jest gotowy!');
await loadCommands(); // Załaduj komendy

// Rejestracja komend globalnie (nadpisując stare)
await registerGlobalCommands(client);

setInterval(() => updatePresence(client), 60000); // Aktualizuj status co minutę
});
// Rejestracja komend globalnie (nadpisując stare)
await registerGlobalCommands(client);

setInterval(() => updatePresence(client), 60000); // Aktualizuj status co minutę
});

async function registerGlobalCommands(client, batchSize = 5, delay = 5000) {
console.log("Rozpoczynam rejestrację komend globalnych partiami...");

const commandsToSet = [];
console.log("client.commands.values() =>", client.commands.values());

for (const command of client.commands.values()) {
console.log("Przetwarzam komendę:", command);

if (!command || !command.data) {
console.warn(`Pominięto nieprawidłową komendę: ${command}`);
continue;
}

commandsToSet.push(command.data.toJSON());
}

console.log("Komendy do zarejestrowania:", commandsToSet);

try {
// Dzielimy komendy na partie
const totalBatches = Math.ceil(commandsToSet.length / batchSize);
for (let i = 0; i < totalBatches; i++) {
const batchStart = i * batchSize;
const batchEnd = batchStart + batchSize;
const batch = commandsToSet.slice(batchStart, batchEnd);

console.log(`Rejestruję partię ${i + 1} z ${totalBatches}:`, batch);

// Rejestracja partii komend
const setCommands = await client.application.commands.set(batch);
console.log(`Zarejestrowano ${setCommands.size} komend w partii ${i + 1}.`);

// Czekanie przed wysłaniem kolejnej partii, aby uniknąć rate limitów
if (i < totalBatches - 1) {
console.log(`Oczekiwanie ${delay}ms przed rejestracją kolejnej partii...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}

console.log("Zakończono rejestrację wszystkich partii.");

} catch (error) {
console.error("Błąd podczas rejestracji komend globalnych partiami:", error);
}
}
// Rejestracja komend globalnie (nadpisując stare)
await registerGlobalCommands(client);

setInterval(() => updatePresence(client), 60000); // Aktualizuj status co minutę
});

async function registerGlobalCommands(client, batchSize = 5, delay = 5000) {
console.log("Rozpoczynam rejestrację komend globalnych partiami...");

const commandsToSet = [];
console.log("client.commands.values() =>", client.commands.values());

for (const command of client.commands.values()) {
console.log("Przetwarzam komendę:", command);

if (!command || !command.data) {
console.warn(`Pominięto nieprawidłową komendę: ${command}`);
continue;
}

commandsToSet.push(command.data.toJSON());
}

console.log("Komendy do zarejestrowania:", commandsToSet);

try {
// Dzielimy komendy na partie
const totalBatches = Math.ceil(commandsToSet.length / batchSize);
for (let i = 0; i < totalBatches; i++) {
const batchStart = i * batchSize;
const batchEnd = batchStart + batchSize;
const batch = commandsToSet.slice(batchStart, batchEnd);

console.log(`Rejestruję partię ${i + 1} z ${totalBatches}:`, batch);

// Rejestracja partii komend
const setCommands = await client.application.commands.set(batch);
console.log(`Zarejestrowano ${setCommands.size} komend w partii ${i + 1}.`);

// Czekanie przed wysłaniem kolejnej partii, aby uniknąć rate limitów
if (i < totalBatches - 1) {
console.log(`Oczekiwanie ${delay}ms przed rejestracją kolejnej partii...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}

console.log("Zakończono rejestrację wszystkich partii.");

} catch (error) {
console.error("Błąd podczas rejestracji komend globalnych partiami:", error);
}
}
Mark
Mark4mo ago
a) stop deploying commands on ready, they only need to be deployed again if you changed data that's deployed to discord (name, options, etc) b) why are you not just setting all commands at once? what is the point of "batching" them? c) do you get any logs from trying to deploy?
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
a) I do not register commands every time I run the script b) This did not work either c) Yes, but no errors
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
I comment that line
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
old script
// Funkcja do rejestracji komend globalnych
async function registerGlobalCommands(client) {
console.log("Rozpoczynam rejestrację komend globalnych...");
const commandsToSet = [];

for (const command of client.commands.values()) {
if (!command || !command.data) {
console.warn(`Pominięto nieprawidłową komendę: ${command}`);
continue;
}
commandsToSet.push(command.data.toJSON());
}

try {
// Użycie metody set() nadpisze wszystkie istniejące komendy
const setCommands = await client.application.commands.set(commandsToSet);
console.log(`Zarejestrowano ${setCommands.size} komend globalnie.`);

// Wypisanie zarejestrowanych komend
console.log("Obecnie zarejestrowane komendy globalne:");
setCommands.forEach(cmd => console.log(`- ${cmd.name}`));
} catch (error) {
console.error(`Błąd podczas rejestracji komend globalnych:`, error);
}
}
// Funkcja do rejestracji komend globalnych
async function registerGlobalCommands(client) {
console.log("Rozpoczynam rejestrację komend globalnych...");
const commandsToSet = [];

for (const command of client.commands.values()) {
if (!command || !command.data) {
console.warn(`Pominięto nieprawidłową komendę: ${command}`);
continue;
}
commandsToSet.push(command.data.toJSON());
}

try {
// Użycie metody set() nadpisze wszystkie istniejące komendy
const setCommands = await client.application.commands.set(commandsToSet);
console.log(`Zarejestrowano ${setCommands.size} komend globalnie.`);

// Wypisanie zarejestrowanych komend
console.log("Obecnie zarejestrowane komendy globalne:");
setCommands.forEach(cmd => console.log(`- ${cmd.name}`));
} catch (error) {
console.error(`Błąd podczas rejestracji komend globalnych:`, error);
}
}
d.js docs
d.js docs4mo ago
:guide: Creating Your Bot: Registering slash commands read more
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
Started refreshing 0 application (/) commands. Successfully reloaded 0 application (/) commands. why 0
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');

const commands = [];
// Grab all the command folders from the commands directory you created earlier
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}

// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);

// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);

// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);

console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');

const commands = [];
// Grab all the command folders from the commands directory you created earlier
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}

// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);

// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);

// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);

console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
and now:
Error: ENOTDIR: not a directory, scandir '/home/container/commands/8ball.js'
at Object.readdirSync (node:fs:1508:26)
at Object.<anonymous> (/home/container/register.js:14:26)
at Module._compile (node:internal/modules/cjs/loader:1368:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
at Object.require.extensions.<computed> [as .js] (/usr/local/lib/node_modules/ts-node/src/index.ts:1608:43)
at Module.load (node:internal/modules/cjs/loader:1205:32)
at Function.Module._load (node:internal/modules/cjs/loader:1021:12)
at cjsLoader (node:internal/modules/esm/translators:366:17)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:315:7)
at ModuleJob.run (node:internal/modules/esm/module_job:222:25) {
errno: -20,
code: 'ENOTDIR',
syscall: 'scandir',
path: '/home/container/commands/8ball.js'
}
Error: ENOTDIR: not a directory, scandir '/home/container/commands/8ball.js'
at Object.readdirSync (node:fs:1508:26)
at Object.<anonymous> (/home/container/register.js:14:26)
at Module._compile (node:internal/modules/cjs/loader:1368:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
at Object.require.extensions.<computed> [as .js] (/usr/local/lib/node_modules/ts-node/src/index.ts:1608:43)
at Module.load (node:internal/modules/cjs/loader:1205:32)
at Function.Module._load (node:internal/modules/cjs/loader:1021:12)
at cjsLoader (node:internal/modules/esm/translators:366:17)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:315:7)
at ModuleJob.run (node:internal/modules/esm/module_job:222:25) {
errno: -20,
code: 'ENOTDIR',
syscall: 'scandir',
path: '/home/container/commands/8ball.js'
}
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
Mark
Mark4mo ago
the guide deploy code includes subfolders in /commands to organize by category eg /commands/fun /commands/utility etc it looks like you don't do that
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
Do I have to do this or can it be done without it?
Mark
Mark4mo ago
you would have to modify the deployment code to not do the subdirectory scans it's up to you whether that's easier or to just categorize your commands into subfolder(s)
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
// Funkcja do rejestracji komend globalnych
async function registerGlobalCommands(client) {
console.log("Rozpoczynam rejestrację komend globalnych...");

const commandsToSet = [];

// Przygotowanie komend do zarejestrowania
for (const command of client.commands.values()) {
if (!command || !command.data) {
console.warn(`Pominięto nieprawidłową komendę: ${command}`);
continue;
}
commandsToSet.push(command.data.toJSON());
}

// Inicjalizuj REST API z tokenem
const rest = new REST().setToken(token);

try {
console.log(`Rozpoczęto odświeżanie ${commandsToSet.length} komend aplikacji (/)`);

// Rejestruj komendy globalnie
const data = await rest.put(
Routes.applicationCommands(clientId), // Rejestracja globalna komend
{ body: commandsToSet },
);

console.log(`Pomyslnie odświeżono ${data.length} komend aplikacji (/)`);

// Wypisanie zarejestrowanych komend
console.log("Obecnie zarejestrowane komendy globalne:");
data.forEach(cmd => console.log(`- ${cmd.name}`));
} catch (error) {
console.error('Błąd podczas rejestracji komend globalnych:', error);
}
}
// Funkcja do rejestracji komend globalnych
async function registerGlobalCommands(client) {
console.log("Rozpoczynam rejestrację komend globalnych...");

const commandsToSet = [];

// Przygotowanie komend do zarejestrowania
for (const command of client.commands.values()) {
if (!command || !command.data) {
console.warn(`Pominięto nieprawidłową komendę: ${command}`);
continue;
}
commandsToSet.push(command.data.toJSON());
}

// Inicjalizuj REST API z tokenem
const rest = new REST().setToken(token);

try {
console.log(`Rozpoczęto odświeżanie ${commandsToSet.length} komend aplikacji (/)`);

// Rejestruj komendy globalnie
const data = await rest.put(
Routes.applicationCommands(clientId), // Rejestracja globalna komend
{ body: commandsToSet },
);

console.log(`Pomyslnie odświeżono ${data.length} komend aplikacji (/)`);

// Wypisanie zarejestrowanych komend
console.log("Obecnie zarejestrowane komendy globalne:");
data.forEach(cmd => console.log(`- ${cmd.name}`));
} catch (error) {
console.error('Błąd podczas rejestracji komend globalnych:', error);
}
}
Unfortunately it still doesn't work
Rozpoczęto odświeżanie 80 komend aplikacji (/)
Rozpoczęto odświeżanie 80 komend aplikacji (/)
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
But I don't see the ending Commands don't register Maybe I have a rate limit? I have a synchronous function and I can see that the registration starts but does not end because the status change function does not start
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
🗿Patryk🍷
🗿Patryk🍷OP4mo ago
I did everything right I just have a rate limit

Did you find this page helpful?