Well, I have a doubt. I want to put "aliases" in my commands in discord.js, but I am stuck without knowing what to do. Help me if something is missing, please.
This is my index.js code
bot.commands = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands')
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'))
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`)
bot.commands.set(command.name, command)
}
}
code 2:
bot.on('message', async (message) => {
if(!message.content.startsWith(process.env.PREFIX) || message.author.bot) return;
if (message.channel.type === 'dm') return;
const args = message.content.slice(process.env.PREFIX.length).split(' ');
const command = args.shift().toLowerCase();
try {
bot.commands.get(command).execute(bot, message, args)
} catch (e) {
message.channel.send('Utilize ``' + `${process.env.PREFIX}` + 'help`` para ver meus comandos.')
.then(message => setTimeout(() => message.delete(), 10000))
}
});
This is the part of the code of the commands, I put the aliases there but it is not working.
const execute = async (bot, message, args) => {
//code
};
module.exports ={
name: "ban",
aliases: ['b', 'banir'],
execute,
};
You need to check client.commands for a module that either has the name of args.shift().toLowerCase() or it's aliases array contains said argument
bot.on('message', async (message) => {
if(!message.content.startsWith(process.env.PREFIX) || message.author.bot) return;
if (message.channel.type === 'dm') return;
const args = message.content.slice(process.env.PREFIX.length).split(' ');
// Aliases Implementing starts here
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 {
bot.commands.get(command).execute(bot, message, args)
} catch (e) {
message.channel.send('Utilize ``' + `${process.env.PREFIX}` + 'help`` para ver meus comandos.')
.then(message => setTimeout(() => message.delete(), 10000))
}
});
Here's an official aliases guide by Discordjs.guide
Simply register your aliases for a command along with the command name, like this:
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'))
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`)
bot.commands.set(command.name, command)
// Register aliases
for (let alias of command.aliases) {
bot.commands.set(alias, command)
}
}
}
Related
I got this error today trying to change a little bit of my command handler from an youtube video.The video is from april and it seems to work for the guy but for me it doesnt.I tried many things but i didnt get any clue.Im not pretty good with this but i want to have an start like many others and this comunity is so good an helps me so much, thank you so much for the support you offer to me!!I hope i will get past this problem.
const Timeout = new Discord.Collection();
const bot = new Discord.Client();
const prefix = '$';
bot.commands = new Discord.Collection();
const commandFolders = readdirSync('./commands');
const ms = require('ms');
const {readdirSync , read} = require('fs');
for(const folder of commandsFolders){
const commandFiles = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${folder}/${files}`);
bot.commands.set(command.name, command);
}
}
bot.on("error" , console.error);
bot.once('ready' , () => {
console.log('M-am trezit din morti!');
});
bot.on("message" , async (message) =>{
if(message.author.bot) return;
if(message.channel.type === 'dm') return;
if(message.content.startsWith(prefix)){
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = bot.command.get(commandName) || bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if(!command) return;
if (command) {
if(command.cooldown){
if(Timeout.has(`${command.name}${message.author.id}`)) return message.channel.send(`Te rog asteapta! \`${ms(Timeout.get (`${command.name}${message.author.id}`) - Date.now(), {long: true})}\`Pana folosesti comanda din nou!`);
command.run(bot, message, args)
Timeout.set(`${command.name}${message.author.id}` , Date.now() + command.cooldown)
setTimeout(() =>{
Timeout.delete(`${coomand.name}${message.author.id}`)
}, command.cooldown)
} else command.run(bot, message, args);
}
}
})
So what you did wrong is, that you want to use readdirSync before you included the fs library in your code. Just move the require statement over the readdirSync and it should work:
const bot = new Discord.Client();
const prefix = '$';
const {readdirSync , read} = require('fs');
bot.commands = new Discord.Collection();
const commandFolders = readdirSync('./commands');
const ms = require('ms');
for(const folder of commandsFolders){
const commandFiles = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${folder}/${files}`);
bot.commands.set(command.name, command);
}
}
bot.on("error" , console.error);
bot.once('ready' , () => {
console.log('M-am trezit din morti!');
});
bot.on("message" , async (message) =>{
if(message.author.bot) return;
if(message.channel.type === 'dm') return;
if(message.content.startsWith(prefix)){
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = bot.command.get(commandName) || bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if(!command) return;
if (command) {
if(command.cooldown){
if(Timeout.has(`${command.name}${message.author.id}`)) return message.channel.send(`Te rog asteapta! \`${ms(Timeout.get (`${command.name}${message.author.id}`) - Date.now(), {long: true})}\`Pana folosesti comanda din nou!`);
command.run(bot, message, args)
Timeout.set(`${command.name}${message.author.id}` , Date.now() + command.cooldown)
setTimeout(() =>{
Timeout.delete(`${coomand.name}${message.author.id}`)
}, command.cooldown)
} else command.run(bot, message, args);
}
}
})
I have a command handler in my main.js file and alias handler is in it too - But when I try to run a command with the alias I've set in module.exports.config it does not respond.
This is my command handler:
fs.readdir(`./commands/`, (error, files) => {
if (error) {return console.log("Error while trying to get the commmands.");};
files.forEach(file => {
const command = require(`./commands/${file}`);
const commandName = file.split(".")[0];
client.commands.set(commandName, command);
if (command.aliases) {
command.aliases.forEach(alias => {
client.aliases.set(alias, command.name)
});
};
});
});
client.on("message", async message => {
if(message.author.bot || message.channel.type === "dm") return;
let prefix = (";");
let messageArray = message.content.split(" ");
let cmd = messageArray[0].toLowerCase();
let args = messageArray.slice(1)
if(!message.content.startsWith(prefix)) return;
let commandfile = client.commands.get(cmd.slice(prefix.length)) || client.commands.get(client.aliases.get(cmd.slice(prefix.length)))
if(commandfile) commandfile.run(client,message,args)
})
And this is my module.exports.config:
module.exports.config = {
name: "eval",
description: "Eval a code",
aliases: ['debug']
};
You don't need to create a new collection for the aliases. You could use collection's .find() method and check if there is an alias with the command name.
So, inside fs.readdir you only set client.commands and when there is an incoming message, you can check if there is an exact command name (using client.commands.get) and if there is not, you check if the command has an aliases property. If it has, you can check if the aliases array includes the command.
Also, if you use cmd.slice(prefix.length) in more than one place and you don't use cmd anywhere, then you probably need to remove the prefix from the command.
The following should work as expected:
fs.readdir(`./commands/`, (error, files) => {
if (error) {
console.log(error);
return console.log('Error while trying to get the commmands.');
}
files.forEach((file) => {
const command = require(`./commands/${file}`);
const commandName = file.split('.')[0];
client.commands.set(commandName, command);
});
});
client.on('message', async (message) => {
let prefix = ';';
if (
message.author.bot ||
message.channel.type === 'dm' ||
!message.content.startsWith(prefix)
)
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.config?.aliases?.includes(commandName));
if (!command) return;
try {
command.run(client, message, args);
} catch (error) {
console.log('There was an error trying to run that command:');
console.log(error);
}
});
so this is my code
//event handler
exports.run = (client, msg, args) => {
const prefix = '-';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const command = client.commands.get(cmd);
if(command) command.execute(client, message, cmd. args, Discord);
}
if(command === 'pula'){
client.commands.get('baned').execute(message, args);
}
//command handler
const fs = require('fs');
module.exports = (client, Discord) => {
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of command_files){
const command = require(`../commands/${file}`);
if(command.name){
client.commands.set(command.name, command);
} else {
continue;
}
}
}
//message.js
exports.run = (client, msg, args) => {
const prefix = '-'; ``
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const command = client.commands.get(cmd);
if(command) command.execute(client, message, cmd. args, Discord);
}
}
//ready.js
module.exports = () => {
console.log('S-a Trezit Lucreita!');
`
And it just gaves me that error, i dont really know what to do, i beg you to help me!I searched on formus, did everything they said and it didnt work.I just tryed everything, i dont have even a clue, im just a noobie being honest and i hope that someone might help me
The following line throws the error:
if (!client.commands.has(command)) return;
I'm following this tutorial= Tutorial
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require("./config.json")
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('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message.content === `${prefix}serverinfo`) {
message.channel.send(message.guild.name)
message.channel.send(`Total Members: ${message.guild.memberCount}`)
} else if (message.content === `${prefix}me`) {
message.channel.send(`Username: ${message.author.username}`)
message.channel.send(`ID: ${message.author.id}`)
} else if (message.content === `${prefix}boi`) {
message.channel.send('BOI')
}
});
if (!client.commands.has(command)) return;
You can't return in the top scope, return must be inside a function.
You may either put the logic inside an if statement
if (client.commands.has(command)) {
const command = client.commands.get(command);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an issue executing that command!")
}
client.login(token);
}
Or wrap the logic inside a function, an IIFE may be a good choice:
(() => {
if (!client.commands.has(command)) return;
const command = client.commands.get(command);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an issue executing that command!")
}
client.login(token);
})();
Whenever I try to use a function like client.users.cache.size or client.guilds.size, they keep giving me an error like "TypeError: Cannot read property 'guilds' of undefined" or "TypeError: Cannot read property 'cache' of undefined".
I was also trying to use let guilds = client.guilds.cache.array().join('\n') but it also throws the same error.
Command's code:
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(client, message) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
Bot's main file:
const path = require('path');
const fs = require("fs");
const { token, prefix } = require('./config.json');
const Discord = require('discord.js');
const db = require ('quick.db');
const client = new Discord.Client
client.commands = new Discord.Collection();
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
getDirectories(__dirname + '/commands').forEach(category => {
const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));
for(const file of commandFiles) {
const command = require(`${category}/${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) => {
const EmbedJoin = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Joined Guild: ${guild.name}!`)
.setTimestamp()
console.log(`Joined New Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedJoin)
});
//Left Guild
client.on("guildDelete", (guild) => {
const EmbedLeave = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Left Guild: ${guild.name}.`)
.setTimestamp()
console.log(`Left Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedLeave)
});
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 = `${message.author}, wrong usage`;
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);
In your code, client.guilds returns a manager, so you have to use client.guilds.cache.size. The rest of the code works fine.
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(message, args, client) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.cache.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
In your main bot file you're only passing the message and the args (in this order) to command.execute(). You can add the client too, and update the parameters in your command's code to match this order.
try {
command.execute(message, args, client);
} catch (error) {
...
}