Personal discord bot not recognizing my commands when? - javascript

I have downloaded a discord bot to read commands such as !gen dysney then they get the account. (educational purposes only ofc) then the user gets a messasage with the details but my discord bot wont recognise my commands. It is online but I put !gen disney and it doesnt do anything. I'd love to know where I've gone wrong. I'd love some support as I've been working on this all day but can't figure out the problem. I've given it administrator and everthing but nothing works. I've included an image of the permissions it has, incase something is wrong.
index.js:
// Dependencies
const Discord = require('discord.js');
const fs = require('fs');
const config = require('./config.json');
const CatLoggr = require('cat-loggr');
// Functions
const client = new Discord.Client();
const log = new CatLoggr();
// New discord collections
client.commands = new Discord.Collection();
// Logging
if (config.debug === true) client.on('debug', stream => log.debug(stream)); // if debug is enabled in config
client.on('warn', message => log.warn(message));
client.on('error', error => log.error(error));
// Load commands from folder
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); // Command directory
for (const file of commandFiles) {
const command = require(`./commands/${file}`); // Load the command
log.init(`Loaded command ${file.split('.')[0] === command.name ? file.split('.')[0] : `${file.split('.')[0]} as ${command.name}`}`); // Logging to console
client.commands.set(command.name, command); // Set command by name to the discord "commands" collection
};
// Client login
client.login(config.token);
client.once('ready', () => {
log.info(`I am logged in as ${client.user.tag} to Discord!`); // Say hello to console
client.user.setActivity(`${config.prefix} • ${client.user.username.toUpperCase()}`, { type: "LISTENING" }); // Set the bot's activity status
/* You can change the activity type to:
* LISTENING
* WATCHING
* COMPETING
* STREAMING (you need to add a twitch.tv url next to type like this: { type: "STREAMING", url: "https://twitch.tv/twitch_username_here"} )
* PLAYING (default)
*/
});
// Discord message event and command handling
client.on('message', (message) => {
if (!message.content.startsWith(config.prefix)) return; // If the message does not start with the prefix
if (message.author.bot) return; // If a command executed by a bot
// Split message content to arguments
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
// If the command does not exists
if (config.command.notfound_message === true && !client.commands.has(command)) {
return message.channel.send(
new Discord.MessageEmbed()
.setColor(config.color.red)
.setTitle('Unknown command :(')
.setDescription(`Sorry, but I cannot find the \`${command}\` command!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
// Executing the command
try {
client.commands.get(command).execute(message, args); // Execute
} catch (error) {
log.error(error); // Logging if error
// Send error messsage if the "error_message" field is "true" in the configuration
if (config.command.error_message === true) {
message.channel.send(
new Discord.MessageEmbed()
.setColor(config.color.red)
.setTitle('Error occurred!')
.setDescription(`An error occurred while executing the \`${command}\` command!`)
.addField('Error', `\`\`\`js\n${error}\n\`\`\``)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
};
});
config.json
{
"token": "TOKEN_placeholder",
"prefix": "!gen",
"genChannel": "1011720065739133008",
"genCooldown": "120000",
"color": {
"green": "0x57F287",
"yellow": "0xFEE75C",
"red": "0xED4245",
"default": "0x5865F2"
},
"command": {
"notfound_message": false,
"error_message": false
}
}
commands/gen.js
// Dependencies
const { MessageEmbed, Message } = require('discord.js');
const fs = require('fs');
const config = require('../config.json');
const CatLoggr = require('cat-loggr');
// Functions
const log = new CatLoggr();
const generated = new Set();
module.exports = {
name: 'gen', // Command name
description: 'Generate a specified service if stocked.', // Command description
/**
* Command exetute
* #param {Message} message The message sent by user
* #param {Array[]} args Arguments splitted by spaces after the command name
*/
execute(message, args) {
// If the generator channel is not given in config or invalid
try {
message.client.channels.cache.get(config.genChannel).id; // Try to get the channel's id
} catch (error) {
if (error) log.error(error); // If an error occured log to console
// Send error messsage if the "error_message" field is "true" in the configuration
if (config.command.error_message === true) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Error occured!')
.setDescription('Not a valid gen channel specified!')
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
} else return;
};
// If the message channel id is the generator channel id in configuration
if (message.channel.id === config.genChannel) {
// If the user have cooldown on the command
if (message.author.id === "665621994649288770" ){
generated.delete(message.author.id);
};
if (message.author.id === "705881983909363742" ){
generated.delete(message.author.id);
};
if (generated.has(message.author.id)) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Cooldown!')
.setDescription(`Please wait ${generated} before executing that command again!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
} else {
// Parameters
const service = args[0];
// If the "service" parameter is missing
if (!service) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Missing parameters!')
.setDescription('You need to give a service name!')
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
// File path to find the given service
const filePath = `${__dirname}/../stock/${args[0]}.txt`;
// Read the service file
fs.readFile(filePath, function (error, data) {
// If no error
if (!error) {
data = data.toString(); // Stringify the content
const position = data.toString().indexOf('\n'); // Get position
const firstLine = data.split('\n')[0]; // Get the first line
// If the service file is empty
if (position === -1) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Generator error!')
.setDescription(`I do not find the \`${args[0]}\` service in my stock!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
// Send messages to the user
message.author.send(
new MessageEmbed()
.setColor(config.color.green)
.setTitle('Generated account')
.addField('Service', `\`\`\`${args[0][0].toUpperCase()}${args[0].slice(1).toLowerCase()}\`\`\``, true)
.addField('Account', `\`\`\`${firstLine}\`\`\``, true)
.setTimestamp()
)
.then(message.author.send('Here is your copy+paste:'))
.then(message.author.send(`\`${firstLine}\``));
// Send message to the channel if the user recieved the message
if (position !== -1) {
data = data.substr(position + 1); // Remove the gernerated account line
// Write changes
fs.writeFile(filePath, data, function (error) {
message.channel.send(
new MessageEmbed()
.setColor(config.color.green)
.setTitle('Account generated seccessfully!')
.setDescription(`Check your private ${message.author}! *If you do not recieved the message, please unlock your private!*`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
generated.add(message.author.id); // Add user to the cooldown set
// Set cooldown time
setTimeout(() => {
generated.delete(message.author.id); // Remove the user from the cooldown set after expire
}, config.genCooldown);
if (error) return log.error(error); // If an error occured, log to console
});
} else {
// If the service is empty
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Generator error!')
.setDescription(`The \`${args[0]}\` service is empty!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
} else {
// If the service does not exists
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Generator error!')
.setDescription(`Service \`${args[0]}\` does not exist!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
});
};
} else {
// If the command executed in another channel
message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Wrong command usage!')
.setDescription(`You cannot use the \`gen\` command in this channel! Try it in <#${config.genChannel}>!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
}
};
commands/help.js
// Dependencies
const { MessageEmbed, Message } = require('discord.js');
const config = require('../config.json');
module.exports = {
name: 'help', // Command name
description: 'Display the command list.', // Command description
/**
* Command exetute
* #param {Message} message The message sent by user
*/
execute(message) {
const { commands } = message.client; // Get commands from the client
message.channel.send(
new MessageEmbed()
.setColor(config.color.default)
.setTitle('Command list')
.setDescription(commands.map(c => `**\`${config.prefix}${c.name}\`**: ${c.description ? c.description : '*No description provided*'}`).join('\n')) // Mapping the commands
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
}
};
commands/stock.js
// Dependencies
const { MessageEmbed, Message } = require('discord.js');
const fs = require('fs');
const config = require('../config.json');
module.exports = {
name: 'stock', // Command name
description: 'Display the service stock.', // Command description
/**
* Command exetute
* #param {Message} message The message sent by user
*/
execute(message) {
// Arrays
const stock = [];
// Read all of the services
fs.readdir(`${__dirname}/../stock/`, function (err, files) {
// If cannot scan the dictionary
if (err) return console.log('Unable to scan directory: ' + err);
// Put services into the stock
files.forEach(function (file) {
if (!file.endsWith('.txt')) return
stock.push(file)
});
const embed = new MessageEmbed()
.setColor(config.color.default)
//.setTitle(`${message.guild.name} has **${stock.length} services**`)
.setTitle(`**${stock.length} services**`)
.setDescription('')
// Push all services to the stock
stock.forEach(async function (data) {
const acc = fs.readFileSync(`${__dirname}/../stock/${data}`, 'utf-8')
const lines = [];
// Get number of lines
acc.split(/\r?\n/).forEach(function (line) {
lines.push(line); // Push to lines
});
// Update embed description message
embed.description += `**${data.replace('.txt','')}:** \`${lines.length}\`\n`
});
message.channel.send(embed);
});
}
};
I tried to add adminitrator. I tried to use differnt ways to run the bot. I added and removed the bot. I tried different prefixes

Related

Cannot read properties of undefined (reading 'send') (Discord.js v13)

i have been trying to make a leaveserver code for my bot, but i always get the error message Cannot read properties of undefined (reading 'send') I really wanna know why it always says the error messages! Please help me! Thanks!
const Discord = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
var self = this
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leavs a server",
run: async (client, message, args) => {
if (!OWNER_ID)
return message.channel.send("This command is Owner Only")},
async run(message, args) {
const guildId = args[0];
if (!rgx.test(guildId))
return message.channel.send("Please Provide a valid server id!")
const guild = message.client.guild.cache.get(guildId);
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send({embeds: [embed]});
}
}
Try this code
const {
MessageEmbed
} = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leaves a server",
run: async (client, message, args) => {
const guildId = args[0];
const guild = message.client.guilds.cache.get(guildId);
if (!OWNER_ID) return message.channel.send("This command is Owner Only");
if (!rgx.test(guildId)) return message.channel.send("Please Provide a valid server id!")
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter({
text: message.member.displayName,
iconURL: message.author.displayAvatarURL({
dynamic: true
})
})
.setTimestamp()
.setColor(message.guild.me.displayHexColor)
message.channel.send({
embeds: [embed]
})
}
}
Removed the duplicated async run(message, args) {
Try to do this:
const client = new Discord.Client({intents:
["GUILDS", "GUILD_MESSAGES"]});
client.on("message" , msg => {
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(msg.member.displayName, msg.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(msg.guild.me.displayHexColor);
msg.channel.send({embeds: [embed]});
})

Discord.JS bot not replying to commands nor returning a error in console regarding it

I've been struggling to get my new Discord bot's command handler to work, While it is seeing the command files (as indicated by its log entry on startup stating the amount of commands it has loaded) it either isn't sending the messages, or it isn't even executing them.
Here's my code:
const { Client, Intents, Collection } = require('discord.js');
const { token, ownerid, statuses, embedColors, prefix } = require('./cfg/config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const fs = require('fs');
const { config } = require('process');
client.commands = new Collection();
const commands = [];
const cmdfiles = fs.readdirSync('./cmds').filter(file => file.endsWith('.js'));
client.once('ready', () => {
console.clear
console.log(`Ready to go, Found ${cmdfiles.length} commands and ${statuses.length} statuses!`)
setInterval(() => {
var status = Math.floor(Math.random() * (statuses.length -1) +1)
client.user.setActivity(statuses[status]);
}, 20000)
}),
client.on("error", (e) => console.log(error(e)));
client.on("warn", (e) => console.log(warn(e)));
// Command Handler
for (const file of cmdfiles) {
const command = require(`./cmds/${file}`);
commands.push(command.data);
}
client.on('messageCreate', 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 (!client.commands.has(command)) {
embeds: [{
title: ":x: Oopsie!",
color: config.embedColors.red,
description: `Command ${args.[0]} doesn't exist! Run ${config.prefix}help to see the avaliable commands!`,
footer: app.config.footer + " Something went wrong! :("
}];
} else {
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
embeds: [{
title: ":x: Oopsie!",
description: "Command execution failed",
fields: [
{ name: "Error Message", value: `${e.message}` }
],
footer: app.config.footer + " Something went wrong :("
}];
}
message.channel.send
}});
client.login(token);
and the test command is
module.exports = {
name: "test",
description: "does as it implies, dingusA",
async execute(client, message, args) {
message.channel.send("This is a message!");
}
}
You need the GUILD_MESSAGES intent in order to receive messages in guilds.
Add the following intent in your code
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES ]
})
This applies to other things as well eg. DIRECT_MESSAGES for DMs and etc.

Set channel permissions to only allow the ticket opener and admin to view the channel - Discord ticket system

I'm having an issue with my ticket discord system where the lock react emoji doesn't actually lock the text chat. The overall slash command executes and my second react emoji, which is an X used to delete the text chat works, but the locking system does not.
The structure is written that any member within the discord will use the /ticket command in "open a ticket" chat and the bot will then create a ticket in a new text channel and name it ticket-userid, and once an admin comes to help the ticket he will then react to the "lock" emoji and lock to channel where only him and the member can see it, no one else. But it's not executing like this, only everything else except this. Does anyone have any idea?
ticket.js
name: 'ticket',
aliases: [],
permissions: [],
description: 'open a ticket!',
async execute(interaction) {
// message.guild is now interaction.guild
const channel = await interaction.guild.channels.create(
// message.author.tag is now interaction.user.tag
`ticket: ${interaction.user.tag}`,
);
channel.setParent('932177870661509141');
// message.guild is now interaction.guild
channel.permissionOverwrites.edit(interaction.guild.id, {
SEND_MESSAGES: false,
VIEW_CHANNEL: false,
});
// message.author is now interaction.member
channel.permissionOverwrites.edit(interaction.member, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
// we're sending a reply with interaction.reply
// and use fetchReply so we can delete it after 7 seconds
const reply = await interaction.reply({
content: `We will be right with you! ${channel}`,
fetchReply: true,
});
setTimeout(() => {
reply.delete();
}, 7000);
const reactionMessage = await channel.send(
'Thank you for contacting support!',
);
try {
await reactionMessage.react('🔒');
await reactionMessage.react('🛑');
} catch (err) {
channel.send('Error sending emojis!');
throw err;
}
// you should also check if the user reacted is a bot
const filter = (reaction, user) =>
!user.bot &&
interaction.guild.members.cache
.get(user.id)
.permissions.has('ADMINISTRATOR');
const collector = reactionMessage.createReactionCollector({
dispose: true,
filter,
});
collector.on('collect', (reaction, user) => {
switch (reaction.emoji.name) {
case '🔒':
channel.permissionOverwrites.edit(interaction.member, {
SEND_MESSAGES: false,
});
break;
case '🛑':
channel.send('Deleting this channel in 5 seconds!');
setTimeout(() => channel.delete(), 5000);
break;
}
});
},
};
index.js
const fs = require('fs');
const { Client, Collection, Intents, DiscordAPIError } = require('discord.js');
const { token } = require('./config.json');
const prefex = '!';
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],
});
client.commands = new Collection();
client.events = new 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.once('ready', () => {
console.log("You are now connected to Boombap Tickets!");
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true,
});
}
});
client.login(token);
channel.permissionOverwrites.edit(interaction.member, {
SEND_MESSAGES: false
});
In this code, the bot sets permission overwrite for reacted person(actually a mod) to restrict sending messages.
But since admins have full privileges, it has no effect.
Instead, you need to restrict #everyone of viewing the channel.
Also you can put all the role id to restrict access in an array and iterate over it to edit overwrites and restrict their access.
So the code would be:
channel.permissionOverwrites.edit(interaction.guild.id, {
VIEW_CHANNEL: false
});
['headchef-role-id', 'cook-role-id'].forEach(roleId => {
channel.permissionOverwrites.edit(roleId, {
VIEW_CHANNEL: false
});
});
Also when opening, your code restricts #everyone to view and send. But since you want #everyone to view the channel, set overwrites code would be:
channel.permissionOverwrites.edit(interaction.member, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
});
channel.permissionOverwrites.edit(interaction.guild.id, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
});
Also please note that when creating a channel, its name isn't ticket: user#1234. It would be ticket-user1234.

res.join is not a function

I've been getting this error while trying to code a discord bot in discord.js. The Bot is being used to check for the status of a discord server.
Error:
D:\MinecraftBot\commands\mcserver.js:13
.then((res) => res.join())
^
TypeError: res.join is not a function
at D:\MinecraftBot\commands\mcserver.js:13:28
Code In Question:
module.exports = {
name: "mcserver",
description: "Get info about a Minecraft Server",
usage: "mcserver <ip>",
run: async (client, message, args) => {
let ip = args[0];
fetch("https://api.mcsrvstat.us/2/"+args[0])
.then((res) => res.join()) // <-------- This Line Is Producing The Error
.then((body) => {
if(body.online === false) {
let oneembed = new discord.MessageEmbed()
.setColor('RANDOM')
.setAuthor("MC SERVER", message.guild.iconURL ({ dynamic: true }))
.addField("Status","<a:Offline:766303914654957610>")
.setTimestamp();
message.channel.send(oneembed)
}
else {
let embed = new discord.MessageEmbed()
.setColor('RANDOM')
.setThumbnail(`https://mc-api.net/v3/server/favicon/${args[0]}`)
.setAuthor("Mc Server", message.guild.iconURL({ dynamic: true }))
.addField("Status", "<a:Online:766303827850690600>")
.addField("IP", body.ip)
.addField("Hostname", body.hostname)
.addField("Players", `${body.players.online}/${body.players.max}`)
.addField("Software", body.software)
.addField("Version", body.version)
.addField("Motd", `${body.motd.clean[0]}\n${body.motd.clean[1]}`)
.setTimestamp()
.setImage(`http://status.mclive.eu/${args[0]}/${args[0]}/25565/banner.png`)
message.channel.send(embed)
}
})
}
}
The Data It's Requesting Is Here: https://api.mcsrvstat.us/2/hypixel.net

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

Categories