DiscordAPIError: Unknown application command - discord.js

When I try to execute a slash command it crashes with an 404 error.
I already tried to delete all commands but it didn't work.
Here's the code I'm using
const commands = [
{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Reloading slash commands');
await rest.put(
Routes.applicationGuildCommands("client_id", "server_id"),
{ body: commands },
);
console.log("Reloaded slash commands");
} catch (error) {
console.error(error);
}
})();
Here's the error
node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Unknown application command
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildApplicationCommandManager.fetch (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:93:23)
at async Client.<anonymous> (/home/container/index.js:101:17) {
method: 'get',
path: '/applications/client_id/guilds/guild_id/commands/command_id',
code: 10063,
httpStatus: 404,
requestData: { json: undefined, files: [] }
}

if you want to register your Slash Commands with the moderately recent Discord.js Rest library you have to use the builder library as well. You are also not passing JSON to the body you are passing an Array of Objects.
From Discord.js Guide on Making Slash Commands
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);

Related

Why im getting this error tho the cmd is fine? Cannot read properties of undefined (reading 'get')

DiscordJS context menu problem, like it says the cmd is running fine but when it does it shows the error of Cannot read properties of undefined (reading 'get') don't know why
Im getting this error on my events folder in discordjs v14 my content.js event
the error kept showing up though the context is still executed/working
I know i should be ignoring this error as long as the command is running good but it just annoying to my console and it doesn't look clean haha...
my context events:
module.exports = {
name: 'interactionCreate',
execute: async (interaction, client) => {
if (interaction.isContextMenuCommand()) {
const { command } = client;
const { commandName } = interaction;
const contextCommand = command.get(commandName);
if (!contextCommand) return;
try {
await contextCommand.execute(client, interaction)
} catch (e) {
console.log(e)
}
}
}
}
simple wave context
const { ApplicationCommandType, EmbedBuilder } = require("discord.js"); // packages
const superagent = require('superagent');
const ee = require('../../Config/embed.json');
module.exports = {
name: 'wave', // name of the command
// description: '', description of the command
developer: false, // false if the command is for public
type: ApplicationCommandType.User, // chatinput
cooldown: 3000, // cooldown of the commands
default_member_permissions: 'SendMessages', // discord perms
// options: [], options string
execute: async (client, interaction) => {
try {
let { body } = await superagent.get(`https://api.waifu.pics/sfw/wave`);
const embed = new EmbedBuilder()
.setColor(ee.color)
.setDescription(`Hey <#${interaction.targetUser.id}>!, <#${interaction.user.id}> just wave at you!`)
.setImage(body.url)
.setTimestamp()
.setFooter({ text: `${client.user.username} | waifumusic.ml` })
interaction.reply({ embeds: [embed] })
} catch (e) {
console.log(e)
}
}
}

DiscordJS 403 Error Missing Access Error when trying to add Slash Commands

I am following the docs at DiscrodJS step by step and have been able to invite my bot just fine to my test server. My problem comes in when I try to add the slash commands.
Here is my index.js file.
const { Client, GatewayIntentBits } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.GuildMessages,
],
})
client.once('ready', () => {
console.log('Ready!')
})
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return
const { commandName } = interaction
const command = interaction.client.commands.get(commandName)
if (!command) {
console.error(`No command matching ${commandName} was found.`)
return
}
try {
await command.execute(interaction)
}
catch (error) {
console.error(error)
await interaction.reply({ ontent: 'There was an error while executing this command', ephemeral: true })
}
})
client.login(process.env.DISCORD_PRIVATE_TOKEN)
Here is my deploy-commands.js file.
const fs = require('node:fs')
const { Routes } = require('discord.js')
const { REST } = require('#discordjs/rest')
require('dotenv').config()
const {
DISCORD_PRIVATE_TOKEN,
DISCORD_CLIENT_ID,
DISCORD_GUILD_ID,
} = process.env
const commands = []
// Grab all the command files from the commands directory you created earlier
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'))
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
commands.push(command.data.toJSON())
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(DISCORD_PRIVATE_TOKEN)
// and deploy your commands!
const deployCommand = 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.applicationGuildCommands(DISCORD_CLIENT_ID, DISCORD_GUILD_ID),
{ 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)
}
}
deployCommand()
There error that I get back from this is the following:
requestBody: { files: undefined, json: [ [Object] ] },
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/[client_id]/guilds/[guild_id]/commands'
}
In the bot settings
I've set auth method to In-app Authorization.
I've set the scope to bot and applications.commands then included Use Slash Commands (also tried this with ALL including Administrator bot permissions.
I've also done this through the URL Generator path.
In my discord server
I've put my Discord server into Developer mode to test my bot.
I've invited my bot to my test server.
In my code
I've ran the one time script for deploy-commands.js.

Discord.js code: 50001, status: 403, method: 'put'

I'm building a bot with Discord.js.
I wrote below code, and persists same error.
How can I fix or avoid that error?
require("dotenv").config();
const fs = require("fs");
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];
const commandfiles = fs.readdirSync("./src/Commands").filter(file => file.endsWith(".js"));
commandfiles.forEach(commandfile => {
const command = require(`./Commands/${commandfile}`);
commands.push(command.data.toJSON());
});
const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);
restClient.put(Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, process.env.DISCORD_GUILD_ID),
{body: commands})
.then(()=> console.log("Successfully registered commands"))
.catch(console.error);
Error message and stacktrace:
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\kitel\vscode workspace\DiscordBot\node_modules\#discordjs\rest\dist\index.js:708:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\kitel\vscode workspace\DiscordBot\node_modules\#discordjs\rest\dist\index.js:511:14) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'put',
url: 'https://discord.com/api/v9/applications/932218396219674624/guilds/932240564102000710/commands',
requestBody: { files: undefined, json: [ [Object] ] }
{ rawError: { message: 'Missing Access', code: 50001 }
As you mentioned, it's missing access i think. Enable your intents on web and grant your bot application commands privilege.

Discord.js: Export Ban list command not working

I recently started working on discord ban bot with 3 main features:
Export IDs of all banned users in current Server/Guild.
Import IDs of banned users into current guild
Transfer ban list from current server to target server. (Under development)
None of the slash commands are working even though the logic is seemingly correct.
I'm following the discordjs guide & managed to make a Time Tag generator bot & this is my 2nd bot project. I admit I'm not familier with Javascript but the guide is very helpful nonetheless
Here is the export-ban-list code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
function new_paste(serverName, results) {
const outputFile = `${serverName}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return data;
}
else {
return 'There was some unexpected error.';
}
});
}
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
const fe = new_paste(interaction.serverName, results);
return interaction.editReply(fe);
},
};
This command basically calculates the number of users banned, makes an array & exports it to pastebin.
The issue is, the bot code reaches till calculation part, but when it comes to making the list, console throws me errors:
Found 13 bans. Exporting...
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async InteractionWebhook.editMessage (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\Webhook.js:311:15)
at async CommandInteraction.editReply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:137:21)
at async Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:41:3) {
method: 'patch',
path: '/webhooks/897454611370213436/aW50ZXJhY3Rpb246ODk4ODkyNzI0NTcxMzczNjA5OmtPeGtqelQ5eUFhMnNqVzc1Q3BpMWtQZUZRdVhveGQxaHFheFJCdVFoUWNxNUk5TVpGbThEQjdWcDdyaHZyaUJPeUpsRWFlbUp0WnVLYjB5V0RtYmJCSmlNU2wwUVlka1hYMHg0bHRJbzlHelVwRmJ6VUpRaXF2YktaVDN1ZlVp/messages/#original',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at CommandInteraction.reply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89:46)
at Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:45:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
Thanks to Jim I used the console.log() to check what was going on.
And indeed the data from function inside new_paste() wasn't being returned to fe.
(I had messed up the return scopes basically)
Here is the final code after fixes & scope resolutions
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
console.log(results);
const outputFile = `${interaction.guild.name}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return interaction.editReply(data);
}
else {
return interaction.editReply('There was some unexpected error.');
}
});
},
};
And finally I get the proper pastebin url as output.
Code hosted here
I think your npm package better-pastebin has an error. I am not familiar with that npm package, so I can’t determine whether it has an error for you, but I think if you change the npm package, the error will not appear.

Can't registry slash commands. Getting missing access error

I'm getting a missing access error when trying to add slash commands to my guild. I already kicked the bot, deleted the bot and changed the intents.
My intent number is 32265
This is my code for adding it the commands:
const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
const arrayOfSlashCommands = [];
commandFiles.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
if (file.name) {
const properties = { directory, ...file };
client.commands.set(file.name, properties);
arrayOfSlashCommands.push(file);
}
});
client.on("ready", () => {
client.guilds.cache.get("783606158669381663").commands.set(arrayOfSlashCommands);
});
But I'm getting this error:
E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async GuildApplicationCommandManager.set (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\managers\ApplicationCommandManager.js:146:18) {
method: 'put',
path: '/applications/893555323200237599/guilds/783606158669381663/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: [
{
name: 'search',
description: 'Search',
type: undefined,
options: undefined,
default_permission: undefined
}
],
files: []
}
}
The solution was to invite the bot using:

Resources