DiscordJS Slash Command Permission Set Error - javascript

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);

Related

405 Error using slash command handler Discord.js

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.

Heroku: how to have it access multiple .js files

I'm getting this error message on heroku and I think I'm getting it cause of Procfile.
I'm using Worker at the moment, but I'm trying to figure out how to have heroku access both index.js and ping.js. Unless I'm reading the error message completely wrong and this could be a different issue. Any help is appreciated!
EDIT:
Here's my code for index.js
const Discord = require('discord.js');
const music = require('#koenie06/discord.js-music');
const fs = require('fs');
const { dir } = require('console');
const bot = new Discord.Client({
shards: "auto",
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.GUILD_VOICE_STATES
]
});
bot.commands = new Discord.Collection();
bot.aliases = new Discord.Collection();
//Command handler and aliases
fs.readdirSync('./commands/').forEach(dir => {
//in the commands folder, we gonna check for the category
fs.readdir(`./commands/${dir}`, (err, files) => {
//console log error(catch error)
if(err)throw err;
//checking if the files ends with .js if its a javascript file
var jsFiles = files.filter(f => f.split('.').pop() === 'js');
//if there is no commands in the file it will return
if(jsFiles.length <= 0) {
console.log("Can't find any commands");
return;
}
jsFiles.forEach(file => {
//console the loaded commands
var fileGet = require(`./commands/${dir}/${file}`);
console.log(`[COMMAND HANDLER] - File ${file} was loaded`);
//gonna let the commands run
try {
bot.commands.set(fileGet.help.name, fileGet);
// it search in the commands folder if there is any aliases
fileGet.help.aliases.forEach(alias => {
bot.aliases.set(alias, fileGet.help.name);
})
} catch(err) {
//catch error in console
return console.log(err);
}
})
})
})
/**
* ECHO STUFF
*/
//slash command to echo
bot.on('ready', async () => {
bot.user.setPresence({ activities: [{ name: "Tedi", type: "WATCHING"}] });
console.log("bye");
const data = {
name: 'echo',
description: 'Echo your text',
options: [{
name: 'text',
type: 'STRING',
description: 'The user input',
required: true,
}],
};
const command = await bot.guilds.cache.get('872986148681703444')?.commands.create(data);
})
bot.on('messageCreate', async message => {
if(message.author.bot || message.channel.type == 'DM') return
let prefix = '~'
let messageArray = message.content.split(' ');
let cmd = messsageArray[0];
let args = messageArray.slice(1);
//it will make the cmd work with his original name and his aliases
let commands = bot.commands.get(cmd.slice(prefix.length)) || bot.commands.get(bot.aliases.get(cmd.slice(prefix.length)));
if(commands) {
if(!message.content.startsWith(prefix)) return
commands.run(bot, message, args, prefix);
}
})
//interactionCreate for echo slash command
bot.on('interactionCreate', async interaction => {
/**
* isButton() used to check if its a button
* isCommand() used to check if its a slash command
* isSelectMenu() used to check if its a dropdown menu
* isMessageComponent()
*/
if(interaction.isCommand()) {
if(interaction.commandName === 'echo') {
const text = interaction.options.getString('text');
await interaction.reply({ content: text, ephemeral: false}); //if ephemeral if true, it would make the slash command private
}
}
})
bot.login(process.env.token);
Here is my ping.js
const Discord = require("discord.js");
module.exports.run = async (Client, message, args, prefix) => {
message.channel.send("pong")
}
module.exports.help = {
name: "ping",
aliases: ["p"]
}
This error is not because of Heroku, it's basically because there is a file in your command handler that doesn't have a name while handling it, as example like this code over here:
const Discord = require("discord.js");
module.exports.run = async (Client, message, args, prefix) => {
message.channel.send("pong")
}
module.exports.help = {
// here the name isn't included
aliases: ["p"]
}
// so just check if you have a file without a name while handling it and put a name, and if you don't want aliases make it `aliases: []`
This command handler should be like thisCommands Folder commands > Subfolder e.g. Moderation > kick.jsThats how it works, also thank you for watching my videos, I'm UltraX :)

UnhandledPromiseRejectionWarning: ReferenceError: client is not defined

I'm encountering an error while making a command for my discord.js bot which says UnhandledPromiseRejectionWarning: ReferenceError: client is not defined even tho i defined client in the main bot file so i'm pretty confused the code for the command i'm making:
let ticketGen = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split("");
let ticketStr = "";
for(let i = 0; i < 3; i++) {
ticketStr += ticketGen[Math.floor(Math.random() * ticketGen.length)];
}
return ticketStr;
}
const fsn = require("fs-nextra");
const colors = require("colors");
module.exports = {
name: 'order',
description: 'Ordering something',
aliases: ['o'],
execute(message) {
let order = message.content.substring(8);
let customer = message.author.id
fsn.readJSON("./blacklist.json").then((blacklistDB) => {
let entry = blacklistDB[message.guild.id];
// Checks is server is blacklisted or not.
if(entry === undefined) {
// Gets ticket ID.
const ticketID = generateID();
// Sends ticket information to tickets channel.
client.guilds.cache.get("745409671430668389").channels.get("746423099871985755").send({embed: {
color: 0xFFFFFF,
title: message.author.username,
fields: [{
name: "New Order",
value: `${message.author.username} would like to order something.`,
}, {
name: "Order Description",
value: order,
}, {
name: "Order ID",
value: ticketID,
}, {
name: "Guild Infomation",
value: `This order came from ${message.guild} (${message.guild.id}) in ${message.channel} (${message.channel.id}).`,
}, {
name: "Order Status",
value: "Unclaimed",
}],
timestamp: new Date(),
footer: {
text: "Taco Bot"
}
}}).then((m) => {
m = m.id;
//rest of the code
forgive me if it was an stupid error i'm completely new to coding and was watching youtube videos to learn the code for the main bot file:
const fs = require("fs");
const { prefix, token, ownerID } = require('./config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on("ready", () => {
console.log(`ready!.`);
console.log(token);
// Activities
const activities_list = [
`Serving Tacos | .help`,
`Preparing Orders | .help`
];
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index]);
}, 10000);
});
//Joined Guild
client.on("guildCreate", (guild) => {
console.log(colors.green(`Joined New Guild, ${guild.name}`));
});
//Left Guild
client.on("guildDelete", (guild) => {
console.log(colors.green(`Left Guild, ${guild.name}`));
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
process.on("error", () => {
console.log("Oops something happened!");
});
client.login(token);
There is no need to create a new client, and absolutely no need to pass it in as an additional argument in your execute method. As you have seen in the comments, the issue is that while client is defined in your main bot file, it is not defined in your command's file. Variables defined in one file aren't accessible in all other files, unless you specifically export that variable using module.exports.
But luckily, you don't need to export your client or pass it as a parameter; discord.js conveniently has a message.client property on the message object which allows you to access your client easily. All you need to do to fix your code is add a single line to the top of your execute() method in your command file:
module.exports = {
name: 'order',
description: 'Ordering something',
aliases: ['o'],
execute(message) {
const client = message.client; //<- Line added right here
let order = message.content.substring(8);
let customer = message.author.id
fsn.readJSON("./blacklist.json").then((blacklistDB) => {
let entry = blacklistDB[message.guild.id];
// Checks is server is blacklisted or not.
if(entry === undefined) {
// Gets ticket ID.
const ticketID = generateID();
// Sends ticket information to tickets channel.
client.guilds.cache.get("745409671430668389").channels.get("746423099871985755").send({embed: {
color: 0xFFFFFF,
title: message.author.username,
fields: [{
name: "New Order",
value: `${message.author.username} would like to order something.`,
}, {
name: "Order Description",
value: order,
}, {
name: "Order ID",
value: ticketID,
}, {
name: "Guild Infomation",
value: `This order came from ${message.guild} (${message.guild.id}) in ${message.channel} (${message.channel.id}).`,
}, {
name: "Order Status",
value: "Unclaimed",
}],
timestamp: new Date(),
footer: {
text: "Taco Bot"
}
}}).then((m) => {
m = m.id;
//rest of the code
And that's all! Problem solved. That message.client property is amazingly convenient.
Relevant Resources:
https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=client
I will suggest you to add the client in the command.execute() too, because it is easier to use. So you will have:
try {
command.execute(client, message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
And in every command file you just simply do this.
execute(client, message, args) {
//code
}

Cannot `.setActivity()` using external functions module

I was trying to setup the bot's .setActivity(), but it doesn't seem to work, though, if I do it using the eval command, it actually sets it and works. Is this because I tried calling an external functions module?
Files
Essentials: ./resources/utils/essentials.js
placeHolder(client, string) {
const owner = client.users.cache.get(client.config.admin.owner.id);
if (typeof string === "string") {
return string
.replace(/%totalCommands%/g, client.commands.array().length)
.replace(/%clientName%/g, client.name)
.replace(/%clientId%/g, client.user.id)
.replace(/%clientDescription/g, client.package.description)
.replace(/%clientUsername%/g, client.user.username)
.replace(/%clientTag%/g, client.user.tag)
.replace(/%clientDevName%/g, client.dev.name)
.replace(/%clientDevHelpers%/g, client.dev.helpers.join(", "))
.replace(/%clientDefaultPrefix%/g, client.def.prefix)
.replace(/%clientGuildCount%/g, client.guilds.cache.size)
.replace(/%clientChannelCount%/g, client.channels.cache.size)
.replace(/%clientPackageName%/g, client.package.name)
.replace(/%clientVersion%/g, client.package.version)
.replace(/%clientLicense%/g, client.package.license)
.replace(/%clientAvatarURL%/g, client.avatar)
.replace(/%clientRepository%/g, client.package.repository)
.replace(/%clientAuthor%/g, client.package.author)
.replace(/%clientOwnerUsername%/g, owner.username)
.replace(/%clientOwnerTag%/g, owner.tag)
.replace(/%clientOwnerID%/g, owner.id)
.replace(/%clientMainFile%/g, client.package.main)
.replace(/%clientOwnerAvatarURL%/g, owner.avatarURL() || owner.defaultAvatarURL)
.replace(/%clientOriginalAuthor%/g, client.package.original_author);
} else {
return string;
}
}
Event Handler for ready: ./resources/events/ready.js
const Discord = require('discord.js');
const Essentials = require("../utils/essentials.js");
module.exports = {
name: "ready", // Event Name
async execute(
client, event
) {
let activity = {};
async function setActv() {
activity.type = client.config.client.presence.activity.default.name;
activity.status = client.config.client.presence.activity.status;
activity.name = await Essentials.placeHolder(client, client.config.client.presence.activity.default.name);
client.user.setActivity(activity.name, {
type: activity.type
});
client.user.setStatus(activity.status);
}
client.footer = Essentials.placeHolder(client, client.config.client.settings.footer);
try {
// Set Activity every 30 seconds
setInterval(async () => {
await setActv().catch(err => Essentials.log(client, error))
}, 5000);
} catch (error) {
Essentials.log(client, error);
}
// Bot Ready Log //
console.log(
`Logged in as ${client.user.tag}.\n`
+ `There are ${client.users.cache.size} users and/or bots online.\n`
+ `${client.user.tag} connected to:\n${client.guilds.cache
.map(g => g.name)
.join(", ")}`
);
}
};
Main bot file: ./bot.js
client.events = new Discord.Collection();
var eventFiles = fs
.readdirSync(`./resources/events`)
.filter(file => file.endsWith(".js"));
for (var file of eventFiles) {
var event = require(`./resources/events/${file}`);
client.events.set(event.name, event);
console.log(`Loading event handler for event "${event.name}".`);
}
client.on("ready", async () => {
const event = client.events.get("ready");
if (event) {
try {
await event.execute(
client, event
)
} catch (err) {
Essentials.log(client, err)
}
}
});
Eval command: ./resources/commands/eval.js
const Discord = require('discord.js');
const Essentials = require('../utils/essentials.js')
module.exports = {
id: "eval",
name: "Eval", // Command name
description: "A simple eval tool to use on Discord.", // Command Description
aliases: ["evl", "ev"], // Command Aliases
category: "Utilities",
cooldown: 5000, // Command cooldown
examples: ["eval message.author.id", "eval process.cwd()"], // Command Examples
usage: ["<args>"], // Command Usage
permissions: ["SEND_MESSAGES", "READ_MESSAGE_HISTORY"], // Command Permissions
memberPermissions: ["SEND_MESSAGES", "READ_MESSAGE_HISTORY", "MANAGE_SERVER"], // User is required to have these permissions
admin: true, // Command is admin only
async execute(client, command, message, args, auth, channel, guild) { // Function async execute()
// Command Starts Here
try {
let evaled = eval(args.join(" "));
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
const avtr = message.author.avatarURL() || message.author.defaultAvatarURL;
const embed = new Discord.MessageEmbed()
.setAuthor(client.name, client.avatar)
.setTitle(command.name)
.setTimestamp()
.setColor(client.color.default)
.addField("**Input**", '```' + args.join(" ") + '```')
.addField("**Result**", '```' + Essentials.clean(evaled) + '```')
.setFooter(`${message.author.username} evaled`, avtr);
message.channel.send(embed);
} catch (err) {
const embed = Essentials.errorEmbed(err);
message.channel.send((embed), { split: true });
}
}
};
I've tried a lot of combinations, ranging from actually putting it outside of the Event Handler and straight to the bot.js until actually using eval(), shown above is my current code. NO error codes were thrown, and all of the other components in ready.js works, including client.footer = ..., except for setting the activity, did I miss something?

ROBLOX Discord bot

I'm trying to create a discord bot that connects to a Roblox account that I made.
I'm trying to create a command that will shout a message in a group, but there's a problem at the login and I can't figure out how to fix the problem.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);
It gives me the error:
Shout error: Error: Shout failed, verify login, permissions, and message
At the first you don`t close you client.on('ready') state.
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
This funcyion will never reply, because you use return, before reply.
Your groupId looks like undefined, because you declarate it let groupId = groupid;, so this is the one way, why got you got this error.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
})
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) return message.reply("You didn't specify a message to shout.")
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);

Categories