discord.js: Cannot read properties of undefined (reading 'toJSON') - javascript

Hello,
I was trying to make a bot with discord.js, and following the tutorial at https://discordjs.guide.
And apparently data.toJSON() wasn't recognized (even though builders are installed)
deploy-commands.js:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, clientId, guildId } = require('./config.json');
const fs = require('node:fs');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON()); // error here
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
}
catch (error) {
console.error(error);
}
})();
[]

I had some empty files in my commands folder that were getting read without a data property. I deleted them to solve the problem.

Related

Why does im getting ["Invalid Form Body"]?

DiscordAPIError[50035]: Invalid Form Body
0[CONTENT_TYPE_INVALID]: Expected "Content-Type" header to be one of {'application/json'}.
Im getting this while starting my bot.
const fs = require("fs");
const colors = require('colors');
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v10");
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync("./src/commands");
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
}
}
const clientId = "0";
const guildId = "0";
const rest = new REST({ version: "10" }).setToken(process.env.TOKEN);
try {
console.log("Started refreshing application (/) commands.".yellow);
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log("Successfully reloaded application (/) commands.".green);
} catch (error) {
console.error(`${error}`.red);
}
};
};
This is the code of handleCommands.js, and error above is getting by this script, anyway to fix?
(client id and guild id is blurred.)
Im beginner in the js so i dont really know much abt it.
I were trying to do slash command loader, but actually it gave me some kind of errors.

Error In My Discord Bot: Cannot read properties of undefined (reading 'get')

I've been getting this error recently and I don't really know how I'm supposed to fix this;
TypeError: Cannot read properties of undefined (reading 'get')
This is the line of code it refers to:
const command1 = interaction.client.commands.get(interaction.commandName);
It was working earlier, but I tried adding the command refresh thingy and it's not working anymore.
Here's my full code:
const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const { clientId, guildId, token } = require('./config.json');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
client.once('ready', () => {
console.log('Ready!');
});
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command1 = interaction.client.commands.get(interaction.commandName);
if (!command1) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command1.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
hey try adding this code
const channel = await client.channels.fetch('<channel-id>')

discord.js v13 deploying slash commands doesn't work

I'm trying to deploy a slash commands and it gives me error DiscordAPIError[50035]: Invalid Form Body
guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
const path = require('node:path');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, clientId } = require('./config.json');
const fs = require('node:fs');
const commands = [];
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
getDirectories(__dirname + '/slash').forEach(category => {
const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));
for(const file of commandFiles) {
const command = require(`${category}/${file}`);
commands.push(command.data.toJSON());
}
});
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
Routes.applicationGuildCommands() requires a guild id as a second parameter.
Define the id of the guild you wish to test the bot on and supply it
Routes.applicationGuildCommands(clientId, guildId)

How to unregister/delete a slash command in Discord.js

I'm using Discord.js V13 (Node JS v16.8.0) and wanted to delete all registered global commands, I'm using the #discordjs/rest module, but I'm not sure how
Here is my deploy-commands.js file:
const fs = require('fs');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
To delete all global commands, use Client.application.commands.set() and pass an empty array
client.application.commands.set([])
I managed to figure it out, turns out you need to put this line of code in between the async function
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: commands,
});

Discord not loading slash commands

I am trying to make a slash command system for my discord.js bot, but it does not show up in the app
Here is the code I am using
const {
Client,
Collection,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const fs = require('fs');
const {
Routes
} = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const commands = [];
// Creating a collection for commands in client
client.commands = new Collection();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
}
client.on('ready', () => {
console.log(`Ready! Logged in as ${client.user.tag}`)
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
console.log(`Loaded slash command /${command.data.name}.`)
}
const CLIENT_ID = client.user.id;
const rest = new REST({
version: '9'
}).setToken("myToken");
(async () => {
try {
await rest.put(
Routes.applicationCommands(CLIENT_ID), {
body: commands
},
);
console.log('Successfully registered all application commands globally');
} catch (error) {
if (error) console.error(error);
}
})();
})
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
const { options } = interaction
try {
await command.execute(interaction, options, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `ERROR: There was a problem executing the **${command.name}** command. Please try again later.`,
ephemeral: true
});
}
});
client.login("myToken")
This is my command file (My ping.js file)
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Ping Pong!"),
async execute(interaction, options, client) {
interaction.reply("Pong!")
}
}
Whenever I launch my bot, no slash commands appear. All the strings are logged to the console though.
I have given the bot application.commands scope.

Categories