405 Error using slash command handler Discord.js - javascript

I got a 405: Method Not Allowed error when I was running the slash command builder.
There's the code:
const { glob } = require("glob");
const { promisify } = require("util");
const { Client } = require("discord.js");
const mongoose = require("mongoose");
const globPromise = promisify(glob);
/**
* #param {Client} client
*/
module.exports = async (client) => {
// Commands
const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
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);
}
});
// Events
const eventFiles = await globPromise(`${process.cwd()}/events/*.js`);
eventFiles.map((value) => require(value));
// Slash Commands
const slashCommands = await globPromise(
`${process.cwd()}/SlashCommands/*/*.js`
);
const arrayOfSlashCommands = [];
slashCommands.map((value) => {
const file = require(value);
if (!file?.name) return;
client.slashCommands.set(file.name, file);
if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
if (file.userPermissions) file.defaultPermission = false;
arrayOfSlashCommands.push(file);
});
client.on("ready", async () => {
// Register for a single guild
const guild = client.guilds.cache.get("1014471738844790844");
await guild.commands.set(arrayOfSlashCommands).then((cmd) => {
const getRoles = (commandName) => {
const permissions = arrayOfSlashCommands.find((x) => x.name === commandName).userPermissions;
if (!permissions) return null;
return guild.roles.cache.filter(x => x.permissions.has(permissions) && !x.managed);
};
const fullPermissions = cmd.reduce((accumulator, x) => {
const roles = getRoles(x.name);
if (!roles) return accumulator;
const permissions = roles.reduce((a, v) => {
return [
...a,
{
id: v.id,
type: 'ROLE',
permission: true,
}
];
}, []);
return [
...accumulator,
{
id: x.id,
permission: permissions,
}
];
}, []);
guild.commands.permissions.set({ fullPermissions });
});
// Register for all the guilds the bot is in
// await client.application.commands.set(arrayOfSlashCommands);
});
// mongoose
const { mongooseConnectionString } = require('../config.json')
if (!mongooseConnectionString) return;
mongoose.connect(mongooseConnectionString).then(() => console.log('Connected to mongodb'));
};
There's the interactionCreate.js file:
const client = require("../index");
client.on("interactionCreate", async (interaction) => {
// Slash Command Handling
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch(() => { });
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "An error has occurred " });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
if (!interaction.member.permissions.has(cmd.userPermissions || [])) return interaction.followUp({ content: `Error: Mission Permissions.` });
cmd.run(client, interaction, args);
}
// Context Menu Handling
if (interaction.isContextMenu()) {
await interaction.deferReply({ ephemeral: false });
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
});
And there's the error I got:
C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\rest\RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: 405: Method Not Allowed
at RequestHandler.execute (C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async ApplicationCommandPermissionsManager.set (C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\managers\ApplicationCommandPermissionsManager.js:186:18) {
method: 'put',
path: '/applications/991997852538634311/guilds/1014471738844790844/commands/permissions',
code: 0,
httpStatus: 405,
requestData: { json: [], files: [] }
}
Discord.js version is 13.11.0, bot has administrator permission on the server.
Please help me solve this.

Related

Discord.js: TypeError: Cannot read properties of undefined (reading 'hello')

I am creating a Discord command handler using discord.js version 14.4.0 but I keep getting this error, here is my code:
const settings = require(`${process.cwd()}/config/settings.json`);
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const Discord = require("discord.js");
module.exports = {
name: "hello",
description: "say hello!",
cooldown: settings.cooldown,
memberpermissions: [],
requiredroles: [],
alloweduserids: [],
type: Discord.ApplicationCommandType.ChatInput,
options: [],
run: async (client, interaction) => {
try {
interaction.reply({ content: `${client.word.hello}` });
} catch (error) {
console.log(colors.red(error));
let somethingWrong = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| Something wrong!")
.setDescription(`❌| Sorry, I failed setting up...!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [somethingWrong], ephemeral: true });
}
}
};
The error I get when running that command:
interaction.reply({ content: `${client.word.hello}` });
and this my index.js file:
const lang_db = require("./dataBases/db");
const dotenv = require("dotenv"); dotenv.config();
const colors = require("colors");
const fs = require("fs");
const Discord = require("discord.js");
const client = new Discord.Client({
intents: [32767],
partials: [
Discord.Partials.GuildScheduledEvent,
Discord.Partials.ThreadMember,
Discord.Partials.GuildMember,
Discord.Partials.Reaction,
Discord.Partials.Channel,
Discord.Partials.Message,
Discord.Partials.User,
],
});
client.slashCommands = new Discord.Collection();
module.exports = client;
fs.readdirSync("./handlers").forEach((handler) => {
require(`./handlers/${handler}`)(client);
});
client.on("interactionCreate", async (interaction) => {
let lang = await lang_db.get(`language_${interaction.guild.id}`);
if(lang == null) {
lang = "en";
} else if(lang == "ar") {
lang = "ar"
}
let word = require(`./languages/${lang}.json`);
client.word = word;
});
client.login(process.env.TOKEN).catch((error) => {
console.log(colors.red(error));
});
TypeError: Cannot read properties of undefined (reading 'hello')
handlers/slashCommand.js
const colors = require("colors");
const fs = require("fs");
const AsciiTable = require("ascii-table");
const table = new AsciiTable().setHeading("Slash Commands", "Stats").setBorder("|", "=", "0", "0");
const { Routes } = require("discord-api-types/v9");
const { REST } = require("#discordjs/rest");
const Discord = require("discord.js");
const APPLICATION_ID = process.env.APPLICATION_ID;
const TOKEN = process.env.TOKEN;
const rest = new REST({ version: "10" }).setToken(TOKEN);
module.exports = (client) => {
const slashCommands = [];
fs.readdirSync("./slashCommands/").forEach(async (dir) => {
const files = fs.readdirSync(`./slashCommands/${dir}/`).filter((file) => file.endsWith(".js"));
for (const file of files) {
const slashCommand = require(`../slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
type: slashCommand.type,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? Discord.PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null,
});
if (slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split(".js")[0], "✅");
} else {
table.addRow(file.split(".js")[0], "⛔");
}
}
});
console.log(colors.green(table.toString()));
(async () => {
try {
const data = await rest.put(process.env.GUILD_ID ? Routes.applicationGuildCommands(APPLICATION_ID, process.env.GUILD_ID) : Routes.applicationCommands(APPLICATION_ID), { body: slashCommands });
console.log(colors.green(`Started refreshing ${slashCommands.length} application (/) commands.`));
console.log(colors.green(`Successfully reloaded ${data.length} application (/) commands.`));
} catch (error) {
console.log(colors.red(error));
}
})();
};
events/guid/interactionCreate.js
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const ms = require("ms");
const Discord = require("discord.js");
const client = require("../..");
const delay = new Discord.Collection();
client.on("interactionCreate", async (interaction) => {
const slashCommand = client.slashCommands.get(interaction.commandName);
if (interaction.type == 4) {
if (slashCommand.autocomplete) {
const choices = [];
await slashCommand.autocomplete(interaction, choices);
}
}
if (!interaction.type == 2) return;
if (!slashCommand)
return client.slashCommands.delete(interaction.commandName);
try {
if (slashCommand.cooldown) {
if (delay.has(`${slashCommand.name}-${interaction.user.id}`)) {
let time = ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true }).includes("ms") ? "0 second" : ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true });
let timeLeft = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| Please wait **${time}** before reusing the \`${slashCommand.name}\` command!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [timeLeft], ephemeral: true });
}
}
if (slashCommand.memberpermissions && slashCommand.memberpermissions.length > 0 && !interaction.member.permissions.has(slashCommand.memberpermissions)) {
let memberPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need these Permission(s): \`${slashCommand.memberpermissions}\``)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [memberPerms], ephemeral: true });
}
if (slashCommand.requiredroles && slashCommand.requiredroles.length > 0 && interaction.member.roles.cache.size > 0 && !interaction.member.roles.cache.some(r => slashCommand.requiredroles.includes(r.id))) {
let rolesPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to have one of the Following Roles: <#&${slashCommand.requiredroles}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [rolesPerms], ephemeral: true });
}
if (slashCommand.alloweduserids && slashCommand.alloweduserids.length > 0 && !slashCommand.alloweduserids.includes(interaction.member.id)) {
let userPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to be one of the Following Users: <#!${slashCommand.alloweduserids}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [userPerms], ephemeral: true });
}
await slashCommand.run(client, interaction);
delay.set(`${slashCommand.name}-${interaction.user.id}`, Date.now() + slashCommand.cooldown * 1000);
setTimeout(() => {
delay.delete(`${slashCommand.name}-${interaction.user.id}`);
}, slashCommand.cooldown * 1000);
} catch (error) {
console.log(colors.red(error));
}
});
I don't know why this is happening, please could someone help me?

DiscordJS Slash Command Permission Set Error

I have a problem with the command.permission.set() function for slash commands in discordJS. DiscordJS version is 13. Node Version: v16.8.0.
(I have made a Slash Command Handler in a directory named commands. There are all the files for the commands)
The Error is:
TypeError [INVALID_TYPE]: Supplied permissions is not an Array of ApplicationCommandPermissionData.
The code of the Permission Set:
client.on('messageCreate', async (msg) => {
if (msg.content.startsWith('$')) {
if (msg.content === '$add') {
const slashCommandData = {};
const commandFiles = fs
.readdirSync('./src/commands')
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require('./commands/' + file);
console.log("- " + command.data.name);
slashCommandData['name'] = command.data.name;
slashCommandData['description'] = command.data.description;
if (command.data.options !== undefined) {
console.log('Option for ' + command.data.name);
slashCommandData['options'] = command.data.options;
} else {
slashCommandData['options'] = [];
}
await client.guilds.cache
.get('877098630299934740')
?.commands.create(slashCommandData);
if (command.data.permission !== undefined) {
console.log("Permission for " + command.data.name);
const permission = [
{
id: '461976441110921218',
type: 'USER',
permission: true,
},
]
const commando = await client.guilds.cache.get('877098630299934740')?.commands.fetch('884318697794195486');
try {
await commando.permissions.set({ permission })
}
catch (error) {
console.log(error)
}
}
}
msg.reply('Aggiunti i comandi nuovi!');
}
}
});
Where I failed?
You need to access the ApplicationCommandPermissionsManager property of ApplicationCommands then you may add a permission using ApplicationCommandPermissionsManager#add method.
Here is an example!
client.guilds.cache.get('877098630299934740').commands.permissions.add({
command: '884318697794195486',
permissions: [{
id: '461976441110921218',
type: 'USER',
permission: true,
}, ]
})
.then(console.log)
.catch(console.error);

TypeError: Cannot read property 'execute' of undefined,;

So I have a problem with the main.js file for the play.js command.
When I check console it's saying that problem is right here:
client.commands.get('play').execute(message, args);
^
Here is the play.js command:
const ytdl = require("ytdl-core");
const ytSearch = require("yt-search");
module.exports = {
name: "play",
description: "Play Komanda",
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send("Moraš biti u nekom kanalu kako bi koristio ovu komandu!");
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT")) return message.channel.send("Nemaš permisije!");
if (!permissions.has("SPEAK")) return message.channel.send("Nemaš permisiju!");
if (!args.length) return message.channel.send("Moraš poslati drugi argumenat.");
const validURL = (str) => {
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if (!regex.test(str)) {
return false;
} else {
return true;
}
};
if (validURL(args[0])) {
const connection = await voiceChannel.join();
const stream = ytdl(args[0], { filter: "audioonly" });
connection.play(stream, { seek: 0, volume: 1 }).on("finish", () => {
voiceChannel.leave();
message.channel.send("leaving channel");
});
await message.reply(`:musical_note: Trenutno slušaš ***Your Link!***`);
return;
}
const connection = await voiceChannel.join();
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return videoResult.videos.length > 1 ? videoResult.videos[0] : null;
};
const video = await videoFinder(args.join(" "));
if (video) {
const stream = ytdl(video.url, { filter: "audioonly" });
connection.play(stream, { seek: 0, volume: 1 }).on("finish", () => {
voiceChannel.leave();
});
await message.reply(`:musical_note: Trenutno slušaš ***${video.title}***`);
} else {
message.channel.send("Nijedan video nije pronadjen");
}
},
};
I think you're getting this error because you're never setting the commands. is just a collection you have to fill by yourself in order to use .get().
To fix this, you may try something like that (for example in your index.js):
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
// Set the command equal to the file
const command = require(`./commands/${file}`);
// Add the command to the collection
bot.commands.set(command.name, command);
}
But...
...this requires all of your commands to be in seperate files in a folder called commands (if your bot isn't already structured like this)

Problem with sending text from yaml Discord.js

i have a problem sending text from yaml. Saving text works but sending does not. Here's the code:
const { Message, MessageEmbed } = require("discord.js")
const { channel } = require('./kanal')
const db = require('quick.db')
module.exports = {
name: "reklama",
guildOnly: true,
description:
"Change guild prefix. If no arguments are passed it will display actuall guild prefix.",
usage: "[prefix]",
run(msg, args, guild) {
if (!guild) {
const guld = new MessageEmbed()
.setTitle("Błąd!")
.setColor("RED")
.setDescription("Tą komende można tylko wykonać na serwerze!")
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(`${msg.author.tag} (${msg.author.id})`, `${msg.author.displayAvatarURL({dynamic: true})}`)
msg.channel.send(guild)
}
const { settings } = client
const prefixArg = args[0]
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null })
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama
let Kanal = client.settings.get(guild.id).Kanał
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField("Treść reklamy:", Reklama)
.addField("Kanał do wysyłania reklam:", Kanal)
msg.channel.send(embed)
}
setInterval(() => {
Kanal.send(`${Reklama}`)
}, 1000)
},catch(e){
console.log(e)
}
}
Here is a part of command handler:
const args = msg.content.slice(length).trim().split(" ")
const cmdName = args.shift().toLowerCase()
const cmd =
client.commands.get(cmdName) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(cmdName),
)
try {
cmd.run(msg, args)
} catch (error) {
console.error(error)
}
})
}
The problem is that when I start the bot, it shows me such an error:
let Reklama = client.settings.get(guild.id).Reklama
^
TypeError: Cannot read property 'id' of undefined
The problem is you don't pass the guild variable to your run method. You call cmd.run(msg, args) but run accepts three parameters.
You can either pass the guild or get it from the msg like this:
module.exports = {
name: 'reklama',
guildOnly: true,
description:
'Change guild prefix. If no arguments are passed it will display actuall guild prefix.',
usage: '[prefix]',
run(msg, args) {
// destructure the guild the message was sent in
const { guild } = msg;
if (!guild) {
const embed = new MessageEmbed()
.setTitle('Błąd!')
.setColor('RED')
.setDescription('Tą komende można tylko wykonać na serwerze!')
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(
`${msg.author.tag} (${msg.author.id})`,
`${msg.author.displayAvatarURL({ dynamic: true })}`,
);
return msg.channel.send(embed);
}
const { settings } = client;
const prefixArg = args[0];
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null });
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama;
let Kanal = client.settings.get(guild.id).Kanał;
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField('Treść reklamy:', Reklama)
.addField('Kanał do wysyłania reklam:', Kanal);
msg.channel.send(embed);
}
setInterval(() => {
Kanal.send(`${Reklama}`);
}, 1000);
},
catch(e) {
console.log(e);
},
};

Discord.js Cannot read property 'name'

can someone help me fix this error? It's causing me some critical damage.
const Discord = require('discord.js');
const config = require('./config.json');
const bot = new Discord.Client();
const cooldowns = new Discord.Collection();
const fs = require('fs');
bot.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) console.log(err);
let jsfile = files.filter((f) => f.split('.').pop() === 'js');
if (jsfile.length <= 0) {
console.log('No Commands fonud!');
return;
}
jsfile.forEach((f, i) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
});
fs.readdir('./events/', (error, f) => {
if (error) console.log(error);
console.log(`${f.length} Loading events...`);
f.forEach((f) => {
const events = require(`./events/${f}`);
const event = f.split('.')[0];
client.on(event, events.bind(null, client));
});
});
});
let statuses = ['By LeRegedit#1281', 'Prefix => !', 'V1.0', 'Coming Soon'];
bot.on('ready', () => {
console.log(bot.user.username + ' is online !');
setInterval(function() {
let status = statuses[Math.floor(Math.random() * statuses.length)];
bot.user.setPresence({ activity: { name: status }, status: 'online' });
}, 10000);
});
bot.on('message', async (message) => {
if (message.author.bot) return;
if (message.channel.type === 'dm') return;
let content = message.content.split(' ');
let command = content[0];
let args = content.slice(1);
let prefix = config.prefix;
let commandfile = bot.commands.get(command.slice(prefix.length));
if (commandfile) commandfile.run(bot, message, args);
if (!message.content.startsWith(prefix)) return;
});
bot.login(config.token);
Type Error: Cannot read property 'name' of undefined

Categories