I have a few files right now, but the main file is main.js. . . and I want each of my bot's commands in different files. How do I connect those files to main.js? This is my main.js file:
const Discord = require('discord.js');
const { token, prefix } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Dr. Gamer is now online!');
});
client.login(token);
You need to write what is called a "Command Handler" to do this.
Basically, you check the command name to a list of imported commands and call it.
Here's a very simple command handler which imports files from commands/
const discord = require('discord.js');
const fs = require('fs');
const { token, prefix } = require('./config.json');
const client = new discord.Client();
client.commands = new discord.Collection();
client.once('ready', () => {
console.log('Dr. Gamer is now online!');
fs.readdirSync('./commands/').forEach(file => {
if (!file.endsWith('.js')) return;
const f = require(`./commands/${file}`);
client.commands.set(file.replace('.js', ''), f);
});
});
client.on('message', (message) => {
// assuming ! is the prefix
if (!message.content.startsWith('!')) return;
let args = message.content.slice(/ +/g);
let command = args.shift();
if (client.commands.get(command)) {
client.commands.get(command).run(client, message, args);
}
});
client.login(token);
An example command:
// ping.js
exports.run = (client, message, args) => {
message.reply("Pong!");
}
Take a look at https://anidiots.guide/ for beginner Discord.js stuff, it's a great resource.
Related
I started programming a discord bot with nodejs on replete and I use code similar to the example in the official site of discord.js. Bot registered the command and it appears in discord but when I run it doesn't work.
The application did not respond
This is the code I use to make the command:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('hi')
.setDescription('say hi'),
async execute(interaction) {
await interaction.reply('hi');
},
};
The index code:
const { Client, Events, GatewayIntentBits } = require('discord.js');
const token = process.env['TOKEN']
const clientId = process.env['APID']
const guildId = process.env['SID']
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
//
const { REST, Routes } = require('discord.js');
/*const { clientId, guildId, token } = require('./config.json');*/
const fs = require('node:fs');
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(token);
// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
//
client.on("ready", () => {
console.log("Bot is online!");
})
client.login(process.env['TOKEN']);
Project Structure
Command Registered
Bot Config
Bot Scopes
Bot Permissions
const Discord = require('discord.js');
// fs
const fs = require('fs');
// path
const path = require('path');
// config
const config = require('./config.json');
// config.json
const token = config.token;
// config config.json
const PREFIX = config.prefix;
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: \[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES\] })
client.commands = new Discord.Collection();
// message
client.on('message', message =\> {
// message not sent by bot
if (!message.author.bot) {
// if the message starts with the prefix
if (message.content.startsWith(PREFIX)) {
// split the message into an array
const args = message.content.slice(PREFIX.length).split(/ +/);
// command is the first element of the array
const command = args.shift().toLowerCase();
// ping command
if (command === 'ping') {
// send a message to the channel
message.channel.send('pong');
}
// success message after login
client.on('ready', () =\> {
console.log(`Logged in as ${client.user.tag}!`);
})
// token config file
client.login(config.token);
so I run node index.js it's supposed to shown Logged in as "my bot name here" on the VSC terminal and should be online on the discord, but it doesn't and I can't figure it out, mind anyone help
Formatting will save your life, Bro:
Also, I'd recommend less comments. It's a lot of noise. I refactored this stuff out. Look how much nicer your code looks:
const { token, prefix: PREFIX } = require('./config.json');
const { Collection, Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
client.commands = new Collection();
client.on('message', message => {
if (message.author.bot) return
if (!message.content.startsWith(PREFIX)) return
const args = message.content.slice(PREFIX.length).split(' ');
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('pong');
}
})
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
})
client.login(token);
My problem is the following: when compiling, I get the error that the property 'execute' is not defined. What I'm trying to do is open a file that is in another folder and dock it in the if, I was guided by the command handling documentation, I don't know if the error is in the other file which is called 'pong.js'. I recently started, so I don't fully understand it. The main code is as follows:
The Error error message
index.js file
const Discord = require('discord.js');
const client = new Discord.Client();
const keepAlive = require("./server")
const prefix = "!";
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./src').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`./src/${file}`);
client.commands.set(command.name, command);
}
// ======== Ready Log ========
client.on ("ready", () => {
console.log('The Bot Is Ready!');
client.user.setPresence({
status: 'ONLINE', // Can Be ONLINE, DND, IDLE, INVISBLE
activity: {
name: '!tsc help',
type: 'PLAYING', // Can Be WHATCHING, LISTENING
}
})
});
client.on('message', async message => {
if(!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(" ");
let command = args.shift().toLowerCase()
if (command === "ping"){
client.commands.get('ping').execute(message, args)
}
})
const token = process.env.TOKEN;
keepAlive()
client.login(token);
pong.js file
module.exports.run = {
name: 'pong',
description: "pong cmd",
execute(message, args){
message.reply("pong!")
}
}
When I make a command, my discord bot will respond multiple time instead of once. I'm using JavaScript and can't find any ways to make it work.
Here's my part of my main script:
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require("fs");
const prefix = '-';
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.categories = fs.readdirSync("./commands/");
client.once('ready', () => {
console.log('Bot is online!');
});
client.on('message', message => {
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
}
}
Here's my subfolder for the command ping:
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args){
message.channel.send('pong!')
}
}
Thanks for helping
Currently writing one too and I dont see anything wrong with this, is it possible your node is running twice?
I just made a command handler, but for some reason it starts two bots (I used the same commands I used before, I just put them inro a different file). I tried generating new token but that did not help. I rebooted my pc but nothing. This is my code:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
const fs = require("fs");
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.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
let args = message.content.substring(prefix.length).split(" ");
switch (args[0]) {
case "kick":
client.commands.get("kick").execute(message, args);
break;
case "serverinfo":
client.commands.get("serverinfo").execute(message, args);
break;
}
});
client.login(token);
}
The commands were in the for loop.