Its a index.js with simple handling why him dont respond my commands?
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } =
require('discord.js');
const prefix = require('./config.json');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
//here a command(in directory commands) (new file)
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
return interaction.reply('Pong!');
},
};
can give config. json
erorr havent only bot dont respond on my commands
and prefix is %
who know why bot dont respond on my messages?
Related
I am using Discord.js library to build a Discord bot. I am following the Official Documentation and I am facing an error while handling events.
File Structure:
index.js
const fs = require('node:fs');
const path = require('node:path');
const { Client, GatewayIntentBits } = require('discord.js');
require('dotenv').config()
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(process.env.token)
interactionCreate.js
module.exports = {
name: 'interactionCreate',
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName); console.log("command ", interaction.client)
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
},
};
The slash command worked successfully when I used the below method in index.js file, instead of creating a new interactionCreate.js file
client.on(Events.InteractionCreate, async (interaction) => {
console.log(interaction)
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
But as soon as I moved this function to interactionCreate.js file, The program started throwing the following error
Any help or advice is appreciated! Thank you
You need to refer to the commands file in index.js because your bot doesn't know about the commands method
From the official document you linked,
add this in index.js
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
}
I'm building a discord bot using discord.js. All of my source code is from the official discord.js guide website, and I'm wondering how I could list all declared slash commands to a JSON file commands.json.
Here is my code:
deploy_commands.js:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
index.js:
const { Client, Collection, Intents } = require("discord.js");
const client = new Client({intents: [Intents.FLAGS.GUILDS]});
const config = require("./config.json");
const { guildId, clientId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log(`user : ${client.user.tag}\nguildid : ${guildId}\nclientid : ${clientId}`);
});
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);
await interaction.reply({content: 'Sorry, there was a problem while executing this command, maybe try again later?', ephemeral: true});
}
});
client.login(token);
deploy_commands.js is a file for deploying commands, and what I want to do is to save all the declared slash commands and transfer all of them to a JSON file.
I personally suggest you the usage of map() to manage the array where you store every command inside deploy_commands.js.
Following you can find a solution that worked for me:
const fs = require('fs');
const commands = [...commandBuilders...].map(command => command.toJSON());
const commandsToString = JSON.stringify(commands);
fs.writeFile('commands.json', commandsToString, (e, res) =>{
if (e) console.log('ERROR: ' + e);
}
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);
I'm new to using Discord.js, and after looking through the basic guide/docs, I'm still somehow confused as to how to allow event and/or command files to access the main client instance. For example, I may want to call client.database within an event file in order to make use of CRUD operations.
I did some digging on my own, and I saw that someone had implemented this by getting rid of the .execute function in each of the event files, and passing in event.bind(null, client) to client.on(). I don't really understand it though:
https://github.com/KSJaay/Alita/blob/fe2faf3c684227e29fdef228adaae2ee1c87065b/Alita.js
https://github.com/KSJaay/Alita/blob/master/Events/guildMemberRemove.js
My Main File:
require("dotenv").config();
const fs = require('fs');
util = require('util');
readdir = util.promisify(fs.readdir);
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const mongoose = require('mongoose');
client.events = new Collection();
client.commands = new Collection();
//client.database = require('./src/db/index.js')
async function init() {
const eventFiles = fs.readdirSync('./src/discord/events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
const eventName = file.split(".")[0];
if (event.once) {
client.once(eventName, (...args) => event.execute(...args));
} else {
client.on(eventName, (...args) => event.execute(...args));
}
}
const commandFiles = await readdir('./src/discord/commands')
commandFiles.filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
mongoose.connect(process.env.DB_CONNECT, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB')
}).catch((err) => {
console.log('Unable to connect to MongoDB Database.\nError: ' + err)
})
await client.login(process.env.TOKEN);
}
init();
My Sample Event:
module.exports = {
name: 'interactionCreate',
async execute(interaction) {
console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an 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 });
}
},
};
Get the client using .client on an object, an Interaction in this case
const command = interaction.client.commands.get(interaction.commandName)
I'm trying to do a command handler on a discord bot (with discord.js) but when I start the bot I get an error:
ReferenceError: command is not defined
This is the error I get
const discord = require('discord.js');
const intents = new discord.Intents();
const client = new discord.Client({ intents: 32767 });
const fs = require('fs');
const { readdirSync } = require('fs');
client.commands = new discord.Collection();
const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./comandos/${file}`);
client.commands.set(command.name, command);
}
let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
if(!cmd){
cmd.execute(client, message, args);
} else {
if(!cmd){
return;
}
}
const config = require('./config.js');
const prefix = config.prefix;
client.login(config.token);
That must be in a messageCreate event:
client.on("messageCreate", message => {
const [ command, ...args ] = message.content.split(/ +/g);
let cmd = client.commands.get(command) || client.commands.find((c) => c.alias?.includes(command));
if (cmd) { //you also made a mistake here, remove the "!"
cmd.execute(client, message, args);
}
})
The problem is that you're using const to define command inside the loop. You need to replace it with var and it should work fine:
const discord = require('discord.js');
const intents = new discord.Intents();
const client = new discord.Client({ intents: 32767 });
const fs = require('fs');
const { readdirSync } = require('fs');
client.commands = new discord.Collection();
const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
var command = require(`./comandos/${file}`);
client.commands.set(command.name, command);
}
let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
if(!cmd){
cmd.execute(client, message, args);
} else {
if(!cmd){
return;
}
}
const config = require('./config.js');
const prefix = config.prefix;
client.login(config.token);
(using "let" won't work either because it is not in the global scope).