getting the folder of a given file from a different file (JAVASCRIPT) - discord

I have subfolders for each of my commands and I'm wondering how I would check the name of the command's folder without having to add code into the command file itself. I've tried folders.filter(folder => folder.includes(command) and I'm hoping there's a similar way that could help me.
const folders = fs.readdirSync(`./categories`);
for (const folder of folders) {
const files = fs.readdirSync(`./categories/${folder}`);
for (const file of files) {
const command = require(`./categories/${folder}/${file}`);
client.commands.set(command.name, command);
};
};
client.on("message", async message => {
if (command.args && !args.length) {
const commandArgs = new Discord.MessageEmbed()
.setAuthor(command.category) // HERE - how would i check what subfolder the given command is in?
.setTitle(command.name)
.setDescription(command.description);
}
//code...
});

You can simply add a property when retrieving it:
const command = require(`./categories/${folder}/${file}`);
command.folder = folder;
client.commands.set(command.name, command);
Now you can use it when referencing the object:
const commandArgs = new Discord.MessageEmbed()
.setTitle("From folder: " + command.folder);

Related

DiscordAPIError[50035]: Invalid Form Body | 5[APPLICATION_COMMANDS_DUPLICATE_NAME]: Application command names must be unique

This Is My index.js
const LOAD_SLASH = process.argv[2] == "load"
const CLIENT_ID = "981858607362629663"
const GUILD_ID = "970702726348546078"
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildVoiceStates
]
})
client.slashcommands = new Discord.Collection()
client.player = new Player(client, {
ytdlOptions: {
quality: "highestaudio",
highWaterMark: 1 << 25
}
})
let commands = []
const slashFiles = fs.readdirSync("./slash").filter(file => file.endsWith(".js"))
for (const file of slashFiles){
const slashcmd = require(`./slash/${file}`)
client.slashcommands.set(slashcmd.data.name, slashcmd)
if (LOAD_SLASH) commands.push(slashcmd.data.toJSON())
}
I Recieve The Following Error After I Run node index.js load :-
DiscordAPIError[50035]: Invalid Form Body 5[APPLICATION_COMMANDS_DUPLICATE_NAME]: Application command names must be unique at SequentialHandler.runRequest
I have tried uninstalling and re-installing discord.js, still I am experiencing this error, I would really like some help!
You have a duplicate command name somewhere in your files. Try finding it with the following snippet:
const slashFiles = fs.readdirSync("./slash").filter(file => file.endsWith(".js"))
for (const file of slashFiles){
const slashcmd = require(`./slash/${file}`)
console.log(slashcmd.data.name)
}
Find the command name which is logged twice and edit the command file accordingly.
In one of the files you duplicated name with another file

Discord.JS bot - how can I include spaces in my command names?

When I include spaces in my command names, those commands won't run. I'm using a command handler and in my index.js file, we have:
client.on('message', msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).trim().split(/ +/g);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
try {
command.execute(msg, args);
} catch (error) {
console.error(error);
msg.reply("I'm encountering an error trying to execute that command. Please try again.");
}
});
and in my command.js file, we have:
module.exports = {
name: 'command name',
execute(msg, args) {
msg.channel.send("command");
},
};
When I change command name to command-name or to commandname it works! But when it's command name, my bot doesn't output any response... not even an error message. Where am I going wrong? Is there some simple solution or workaround that I'm overlooking? Thanks in advance.
This is because you shift() your arguments in the line
const commandName = args.shift().toLowerCase();
This takes the first argument and returns it, any following arguments will not be included.
To take the first 2 argument use
const commandName = args.splice(0, 2);
Change command to the following to account for any other arguments.
const command = client.commands.get(commandName.join(' ').toLowerCase())
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName.join(' ').toLowerCase()));

Flutter & Dart file path not found

I tried check file for exists but on all case flutter can't found file from directory.
Code:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocDir = await path_provider.getApplicationDocumentsDirectory();
var path1 = '/assets/images/text.txt';
var path2 = 'assets/images/text.txt';
var path3 = '${appDocDir.path}/assets/images/banner.png';
if (await File(path3).exists()) {
print("File exists");
} else {
print("File don't exists");
}
}
File pubspec.yaml:
flutter:
assets:
- assets/images/
- assets/icons/
Where I have error on my code?
Assets directory should be in project root path.
assets
lib
build
etc.
You should to write file names too:
text.txt, banner.png
flutter:
assets:
- assets/images/text.txt
- assets/images/banner.png
-
path3:
var path3 = '${appDocDir.path}/assets/images/banner.png';
You don't need to use path_provider to get image form assets dir.

client.commands.has() not working with normal input

To get the files with commands (such as ping.js)
module.exports = {
name: 'ping',
description: 'Play some ping pong.',
execute(message, args) {
const bot = require('../bot.js');
message.channel.send('pong!');
bot.log(message, '$ping', message.guild.name);
},
};
I use this in bot.js
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command_file = require(`./commands/${file}`);
client.commands.set(command_file.name, command_file);
}
I'm trying to set the variable for the command with this:
let command = '';
if(message.content.includes(' ')){
command = message.content.substr(1, message.content.indexOf(' ')).toLowerCase();
} else {
command = message.content.substr(1).toLowerCase();
}
which returns the name of the command as a string, like 'info' or 'ping'.
But, when I put that variable into client.commands.has() it doesnt find the command and returns back with this:
if(!client.commands.has(command)) return;
I cant find any answers to this online so I figured I'd ask, sorry if this doesnt fit
Try this instead:
const cmd =
message.client.commands.get(command) ||
message.client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(command) // if you're also using aliases
);
if (!command) return;

Scala Lift - Save uploaded files to server directory

I'm currently storing images within the webapp folder of my Lift project, which I know will cause problems in future.
val path = "src/main/webapp/files/"
And the code I'm using to save it:
case Full(file) =>
val holder = new File(path, "test.txt")
val output = new FileOutputStream(holder)
try {
output.write(file)
} finally {
output.close()
}
}
What I'm trying to do is save the to the server root in an easily manageable folder called files, so SERVER_ROOT/files outside of the project folder.
Firstly how would I access the path to the root of the server so I can save them there?
Secondly how would I serve these files from my app, so I can display them on a page?
Thanks in advance, any help much appreciated :)
You have to store file to exact place on filesystem according to absolute path. I have written this code and it works, so maybe it helps you:
def storeFile (file : FileParamHolder): Box[File] =
{
getBaseApplicationPath match
{
case Full(appBasePath) =>
{
var uploadDir = new File(appBasePath + "RELATIVE PATH TO YOUR UPLOAD DIR")
val uploadingFile = new File(uploadDir, file.fileName)
println("upload file to: " + uploadingFile.getAbsolutePath)
var output = new FileOutputStream(uploadingFile)
try
{
output.write(file.file)
}
catch
{
case e => println(e)
}
finally
{
output.close
output = null
}
Full(uploadingFile)
}
case _ => Empty
}
}
and this is my getBaseApplicationPath function which finds out absolute path of local machine (server or your devel PC):
def getBaseApplicationPath: Box[String] =
{
LiftRules.context match
{
case context: HTTPServletContext =>
{
var baseApp: String = context.ctx.getRealPath("/")
if(!baseApp.endsWith(File.separator))
baseApp = baseApp + File.separator
Full(baseApp)
}
case _ => Empty
}
}

Resources