DiscordAPIError: 404: Not Found - javascript

I'm remaking a Discord music bot I made a while back in Discord.js v12.5.3 and when I try and use any slash command except play it gives me this error:
C:\Users\Alex\Documents\Programming\NodeJS\Discord bots\DJeff New\node_modules\discord.js\src\rest\RequestHandler.js:154
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: 404: Not Found
at RequestHandler.execute (C:\Users\Alex\Documents\Programming\NodeJS\Discord bots\DJeff New\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\Alex\Documents\Programming\NodeJS\Discord bots\DJeff New\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/interactions/callback',
code: 0,
httpStatus: 404
}
Here is how I pass the arguments and other stuff:
interaction.reply = (client, response) => {
client.api.interactions(this.id, this.token).callback.post({
data: {
type: 4,
data: {
content: response,
},
},
});
};
command.execute(client, interaction, interaction.data.options || []);
And here's my skip.js file for reference:
module.exports = {
name: "skip",
usage: null,
options: null,
async execute(client, interaction, args) {
var serverQueue = client.queue.get(interaction.guild_id);
const guild = await client.guilds.fetch(interaction.guild_id);
const userVoiceChannel = guild.members.cache.get(
interaction.member.user.id
).voice.channel;
if (!userVoiceChannel)
return interaction.reply(
client,
"You need to be in a voice channel to use this command."
);
var clientVoiceChannel = client.voice.connections.get(
interaction.guild_id
);
if (!clientVoiceChannel)
return interaction.reply(
client,
"I need to be in a voice channel to execute this command."
);
if (
clientVoiceChannel.channel.id !==
guild.members.cache.get(interaction.member.user.id).voice.channel.id
)
return interaction.reply(
client,
"You need to be in the same voice channel as me to use this command."
);
if (!serverQueue)
return interaction.reply(client, "Nothing is playing.");
serverQueue.connection.dispatcher.end("Skipped the current video.");
return interaction.reply(
client,
":fast_forward: **|** Skipped the current video."
);
},
};

Related

Discord API "APPLICATION_COMMAND_INVALID_NAME" ERROR [duplicate]

I was developing a discord bot and I wanted to register a slash command with some options for the ban command and when I tried to register the command gave me this error:
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Invalid Form Body
options[0].name: Command name is invalid
options[1].name: Command name is invalid
at RequestHandler.execute (/Users/me/Desktop/LavaBot/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/Users/me/Desktop/LavaBot/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildApplicationCommandManager.create (/Users/me/Desktop/LavaBot/node_modules/discord.js/src/managers/ApplicationCommandManager.js:127:18)
in this file: /Users/me/Desktop/LavaBot/node_modules/discord.js/src/rest/RequestHandler.js:350
index.js code:
client.on('messageCreate', async (message) => {
if (!client.application?.owner) {
await client.application?.fetch();
}
if (message.content.toLowerCase() === 'lava.registra' && message.author.id === client.application?.owner.id) {
const data = {
name: 'ban',
description: 'Banna un utente dal server permanentemente',
options: [
{
name: "UTENTE",
description: "Specifica l'utente da bannare",
type: "USER",
require: true,
},
{
name: "MOTIVO",
description: "Specifica il motivo del ban",
type: "STRING",
require: true,
}
]
};
//Register a global command
//const command = await client.application?.commands.create(data);
//console.log(command);
//Register a guild command
const command = await client.guilds.cache.get('957317299289858108')?.commands.create(data);
console.log(comando);
}
})
and the file code:
if (res.status >= 400 && res.status < 500) {
// Handle ratelimited requests
if (res.status === 429) {
const isGlobal = this.globalLimited;
let limit, timeout;
if (isGlobal) {
// Set the variables based on the global rate limit
limit = this.manager.globalLimit;
timeout = this.manager.globalReset + this.manager.client.options.restTimeOffset - Date.now();
} else {
// Set the variables based on the route-specific rate limit
limit = this.limit;
timeout = this.reset + this.manager.client.options.restTimeOffset - Date.now();
}
this.manager.client.emit(
DEBUG,
`Hit a 429 while executing a request.
Global : ${isGlobal}
Method : ${request.method}
Path : ${request.path}
Route : ${request.route}
Limit : ${limit}
Timeout : ${timeout}ms
Sublimit: ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,
);
await this.onRateLimit(request, limit, timeout, isGlobal);
// If caused by a sublimit, wait it out here so other requests on the route can be handled
if (sublimitTimeout) {
await sleep(sublimitTimeout);
}
return this.execute(request);
}
// Handle possible malformed requests
let data;
try {
data = await parseResponse(res);
} catch (err) {
throw new HTTPError(err.message, err.constructor.name, err.status, request);
}
throw new DiscordAPIError(data, res.status, request);
}
What's wrong?
Command names must be all lowercase, between 1 and 32 characters, so UTENTE should be utente, and MOTIVO should be motivo.

Check in which channel the bot has access to and send a message

I'm trying to make my bot type a message upon joining a guild, but it doesn't seem to work.
What I've tried: (among some other variations)
const { PermissionsBitField } = require('discord.js');
module.exports = async (client, guild) =>{
const channel = guild.channels.cache.find(channel => channel.type === 0 && channel.permissionsFor(guild.members.me).has(PermissionsBitField.Flags.SendMessages))
channel.send("Thank you for inviting me!")
}
const { PermissionsBitField } = require('discord.js');
module.exports = async (client, guild) =>{
const channel = guild.channels.cache.find(channel => channel.type === 0 && guild.members.me.permissionsIn(channel).has(PermissionsBitField.Flags.SendMessages))
channel.send("Thank you for inviting me!")
}
For some reason it still tries to send in a channel where the bot doesn't have permission to send messages in.
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:659:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:458:14)
at async REST.request (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:902:22)
at async TextChannel.send (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:15) {
requestBody: {
files: [],
json: {
content: 'Thank you for inviting me!',
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,
thread_name: undefined
}
},
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'POST',
url: 'https://discord.com/api/v10/channels/1007005313968390306/messages'
}
Turns out adding
&&channel.permissionsFor(guild.members.me).has(PermissionsBitField.Flags.ViewChannel) has solved my problem.

why register slash commands with options doesn't work (discord.js)

I was developing a discord bot and I wanted to register a slash command with some options for the ban command and when I tried to register the command gave me this error:
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Invalid Form Body
options[0].name: Command name is invalid
options[1].name: Command name is invalid
at RequestHandler.execute (/Users/me/Desktop/LavaBot/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/Users/me/Desktop/LavaBot/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildApplicationCommandManager.create (/Users/me/Desktop/LavaBot/node_modules/discord.js/src/managers/ApplicationCommandManager.js:127:18)
in this file: /Users/me/Desktop/LavaBot/node_modules/discord.js/src/rest/RequestHandler.js:350
index.js code:
client.on('messageCreate', async (message) => {
if (!client.application?.owner) {
await client.application?.fetch();
}
if (message.content.toLowerCase() === 'lava.registra' && message.author.id === client.application?.owner.id) {
const data = {
name: 'ban',
description: 'Banna un utente dal server permanentemente',
options: [
{
name: "UTENTE",
description: "Specifica l'utente da bannare",
type: "USER",
require: true,
},
{
name: "MOTIVO",
description: "Specifica il motivo del ban",
type: "STRING",
require: true,
}
]
};
//Register a global command
//const command = await client.application?.commands.create(data);
//console.log(command);
//Register a guild command
const command = await client.guilds.cache.get('957317299289858108')?.commands.create(data);
console.log(comando);
}
})
and the file code:
if (res.status >= 400 && res.status < 500) {
// Handle ratelimited requests
if (res.status === 429) {
const isGlobal = this.globalLimited;
let limit, timeout;
if (isGlobal) {
// Set the variables based on the global rate limit
limit = this.manager.globalLimit;
timeout = this.manager.globalReset + this.manager.client.options.restTimeOffset - Date.now();
} else {
// Set the variables based on the route-specific rate limit
limit = this.limit;
timeout = this.reset + this.manager.client.options.restTimeOffset - Date.now();
}
this.manager.client.emit(
DEBUG,
`Hit a 429 while executing a request.
Global : ${isGlobal}
Method : ${request.method}
Path : ${request.path}
Route : ${request.route}
Limit : ${limit}
Timeout : ${timeout}ms
Sublimit: ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,
);
await this.onRateLimit(request, limit, timeout, isGlobal);
// If caused by a sublimit, wait it out here so other requests on the route can be handled
if (sublimitTimeout) {
await sleep(sublimitTimeout);
}
return this.execute(request);
}
// Handle possible malformed requests
let data;
try {
data = await parseResponse(res);
} catch (err) {
throw new HTTPError(err.message, err.constructor.name, err.status, request);
}
throw new DiscordAPIError(data, res.status, request);
}
What's wrong?
Command names must be all lowercase, between 1 and 32 characters, so UTENTE should be utente, and MOTIVO should be motivo.

Transfer embed messages between chats discord.js

I'm trying to transfer a embed message from a channel to another channel using reactions.
I've trying somthing like this:
client.on("messageReactionAdd", (message) => {
let analiseChannel = message.client.channels.cache.get(analiseChannelID);
const channel = message.client.channels.cache.get(aprovadasChannelID);
if (analiseChannel) {
const { content, embeds } = message
channel.send({
content,
embeds
}).then(msg => {
msg.delete({ timeout: 3000 })
})
.catch(console.error);
}
});
And this is the error:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (R:\#Aplicações\Discord\hylex\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (R:\#Aplicações\Discord\hylex\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async TextChannel.send (R:\#Aplicações\Discord\hylex\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:172:15) {
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
*I don't know if the way I'm doing is the better one
The messageReactionAdd event gives an instance of MessageReaction as its first argument. You can destructure the message out of it
client.on("messageReactionAdd", ({ message }) => { //notice the braces around "message"
let analiseChannel = message.client.channels.cache.get(analiseChannelID);
const channel = message.client.channels.cache.get(aprovadasChannelID);
if (analiseChannel) {
const { content, embeds } = message
channel.send({
content,
embeds
}).then(msg => {
msg.delete({ timeout: 3000 })
})
.catch(console.error);
}
});

Discord JS - DiscordAPIError: Missing Access

So i follow worn off keys tutorial to discord bot and i don't know what the problem is, here is the error
/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async GuildApplicationCommandManager.create (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:117:18) {
method: 'post',
path: '/applications/901999677011005472/guilds/905266476573950023/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: {
name: 'ping',
description: 'Bot uptime/latency checker.',
type: undefined,
options: undefined,
default_permission: undefined
},
files: []
}
}
I also try looking at my code but I didn't see something wrong.
This is my code, I really think something is wrong in the code.
const DiscordJS = require('discord.js')
const { Intents } = require('discord.js')
const dotenv = require('dotenv')
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
client.on('ready', () => {
console.log("The bot is online")
// Carlos: 883425101389914152
const guildId = '905266476573950023'
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application.commands
}
commands.create({
name: 'ping',
description: 'Bot uptime/latency checker.',
})
commands.create({
name: 'add',
description: 'Adds two numbers given by user.',
options: [
{
name: 'number1',
description: 'The first number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
{
name: 'number2',
description: 'The second number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
]
})
})
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, Options } = interaction
if (commandName === 'ping') {
interaction.reply({
content: 'Pong! **60ms**',
// If anyone can see = True, Only command user can see = False
ephemeral: true,
})
} else if (commandName === 'add') {
interaction.reply({
content: 'The sum is ${number1 + number2}'
})
}
})
client.login(process.env.KEY)
For anyone that having the same problem. I fix this by simply going to bot developer portal then go to OAuth2 > URL generator. And for the scope select both "bot" and "applications.commands". Then scroll down choose whatever permission your bot need copy the URL.
You did not select the right permissions when creating bot login link for your discord server.
Goto developers / oauth again, click bot and select all the required permissions that you're using in this bot.
Then copy the link generated and use it to login with your bot into your server.
don't forget to change this:
content: 'The sum is ${number1 + number2}'
to this:
content: `The sum is ${number1 + number2}`

Categories

Resources