./commands/hello.js:
const discord = require("discord.js")
const client = require("./index.js").client
const { prefix } = require("./config/config.json")
const { hello } = "./config/config.js"
//modules
module.exports = () => {
//onClient
client.on("messageCreate", (message) => {
if (!message.content.startsWith(`${prefix}hello`)) return
//creating the embed
const embed = new discord.MessageEmbed()
.setTitle("test")
.setAuthor("Sanke")
.addField("Test", "this is a test")
.setDescription("This is a test commmand")
//message send
message.channel.send({
content:"",
embeds: [embed],
files: []
})
})
}
index.js:
const { Client,Intents } = require("discord.js")
const { token } = require("./config/config.json")
const fs = require('fs')
//Client init
const client = new Client({ intents: [Intents.FLAGS.GUILDS]})
exports.client = client
client.once('ready', () =>{
console.log("First time seeing ya face on discord :)")
client.user.setActivity("First time here :D")
})
//comand Handler
const command = require("./commands/hello")
command()
client.login(token)
Problem:
-in ./commands/hello.js is recognized as a module,not a target file. I don't know what to do...I tried to make the command handler with the const command = require("./commands(commands directory)/hello(the command file)")
-Error:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module './index.js'
Require stack:
- /Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/commands/hello.js
- /Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/commands/hello.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/commands/hello.js',
'/Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/index.js'
]
}
It looks from the code you shared that you're trying to require ./index.js inside commands/hello.js. Shouldn't that be ../index.js?
The next problem you're likely to encounter is a circular dependency - each file requires the other.
Can you remove the require of index.js in hello.js and pass the client to the hello command directly? E.g.
index.js
const { Client, Intents } = require("discord.js")
const { token } = require("./config/config.json")
const fs = require('fs')
//Client init
const client = new Client({ intents: [Intents.FLAGS.GUILDS]})
exports.client = client
client.once('ready', () =>{
console.log("First time seeing ya face on discord :)")
client.user.setActivity("First time here :D")
})
//comand Handler
const command = require("./commands/hello")
// CHANGE >> PASS CLIENT TO COMMAND
command(client)
client.login(token)
Related
Terminal error:
\commands\ping.js:4
data: new SlashCommandbuilder()
^
TypeError: SlashCommandbuilder is not a constructor
at Object.<anonymous> (D:\MichelDev\Pessoais JM\Relphi (BOT)\commands\ping.js:4:11)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (D:\MichelDev\Pessoais JM\Relphi (BOT)\index.js:20:21)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
Codding (commands/ping.js)
const { SlashCommandbuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandbuilder()
.setName("ping")
.setDescription("Pong."),
async execute(interaction)
{
interaction.reply("Pong!");
}
}
Codding (commands/index.js)
require("dotenv").config();
const fs = require("fs");
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v10");
const { Client, GatewayIntentBits, Collection } = require("discord.js");
//const config = ("./config.js");
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages
]
});
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
const commands = [];
client.commands = new Collection();
for (const file of commandFiles)
{
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
}
client.once("ready", () =>
{
console.log("(Discord.js v14) Ralphi online!");
const CLIENT_ID = client.user.id;
const rest = new REST
({
version: "10"
}).setToken(process.env.TOKEN);
(async () =>
{
try {
if(process.env.ENV === "production")
{
await rest.put(Routes.applicationCommands(CLIENT_ID),
{
body: commands
});
console.log("Comandos registrados com sucesso (global).");
}
else
{
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID),
{
body: commands
});
console.log("Comandos registrados com sucesso (local).");
}
}
catch(err)
{
if(err) console.error(err);
}
})();
});
client.login(process.env.TOKEN);
I'm creating a bot for the first time on discord.js (v14) and using it as a way of learning, but when I started to assemble these "SlashCommandBUilder", it wasn't. But before that there was an error in the main code (index.js) that is needed for this "CommandBuilder". I don't know what else to do, so I ask you to help me. Thank you very much in advance.
I think the letter B in the builder part (SlashCommandbuilder) should be uppercase. Like SlashCommandBuilder
So i have been trying to fix this issue for a while now and even rewrote some bits but so far it still keeps giving the same thing... Below is the code and the terminal output
This is done using node.js and discord.js
Main Bot Code
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.color = "";
client.commandarray = [];
const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync(`./src/functions/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of functionFiles)
require(`./functions/${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.login(token);
The Terminal Output
C:\Users\Maheel\Desktop\NewTestingBOt\src\bot.js:17
require(`./functions/${folder}/${file}`)(client);
^
TypeError: require(...) is not a function
at Object.<anonymous> (C:\Users\Maheel\Desktop\NewTestingBOt\src\bot.js:17:45)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Thanks in advance to those who help with this error message
Please make sure that what your exporting from that file is a function, and not an object.
function:
module.exports = (param) => {
console.log("hello world")
}
object:
module.exports = {
helloWorld: () => {
console.log("hello world")
}
}
Full Error:
c:\Users\beed\.vscode\HTML + JS\Javascript\Mystic-Sneaky_Helper_2\node_modules\discord.js\src\rest\APIRequest.js:34
agent ??= new https.Agent({ ...this.client.options.http.agent, keepAlive: true });
^^^
SyntaxError: Unexpected token '??='
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.<anonymous> (c:\Users\beed\.vscode\HTML + JS\Javascript\Mystic-Sneaky_Helper_2\node_modules\discord.js\src\rest\RESTManager.js:5:20)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
[Done] exited with code=1 in 0.117 seconds
I used VSCode, I followed the DisordJS Guide, I used Code Runner to run the JavaScript.
==== DIVIDER ====
Directory:
commands
ping.js
node_modules
#discord.js
rest
APIRequest.js
Some More Modules...
NOTE: I ONLY SHOWED THE MODULE THE ERROR IS IN.
config.json
deploy_commands.js
index.js
package-lock.json
package.json
It took me some time to write the directory above, so please answer...
Index.js:
// Require the necessary discord.js classes
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json')
const fs = require('fs')
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
client.commands = new Collection()
client.once('ready', () => {
console.log('Ready!');
});
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: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
==== DIVIDER ====
Thanks in advance,
Beedful
You need to upgrade to Node.JS v15.0.0+
Since the error is Unexpected token '??=', you should try to add engines in your package.json
"engines": {
"node": "16.x"
}
let me know if it works.
const fs = require('fs');
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.commands = 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.data.name, command);
}
client.once('ready', () => {
console.log('Ready!');
});
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);
that's the index.js file
the error= TypeError: Cannot read properties of undefined (reading 'name')
at Object.<anonymous> (C:\Users\shado\OneDrive\Pulpit\Command\index.js:12:35)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
there is also a second issue
TypeError: Cannot read properties of undefined (reading 'toJSON')
at Object.<anonymous> (C:\Users\shado\OneDrive\Pulpit\Command\deploy-commands.js:11:29)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
const fs = require('fs');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
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);
^ deploy-commands.js
the second issue concerns that
i have no idea what is happening, it worked yesterday, everything is falling apart, please help
there have been no major changes made since it last worked on my pc. none at all to the code of these two files themselves, only additional commands being added
I had the same issue. Try printing both command and command.data and look at the types. For me when i did typeof(command.data) i saw that one of my objects was undefined. This was due to a typo in my user.js file in commands folder. Instead of data i had written Data.
My code
require('dotenv').config();
const fs = require('fs');
const Discord = require('discord.js')
const { error } = require('console');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const PREFIX = "zm.";
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.login(process.env.BOT_TOKEN);
client.on('ready', () =>{
console.log('ZeKuS Modification bot is now online!');
client.user.setActivity('ZeKuS Modification | ZM', {type: 'PLAYING'}).catch(console.error)});
client.on('message', message =>{
if (message.author.bot) return;
if (!message.content.startsWith(PREFIX)) return;
const args = message.content.slice(PREFIX.length).trim().split(/\s+/);
const cmd = args.shift();
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);
}
if (!client.commands.has(command)) return;
try{
client.commands.get(cmd).execute(message, args);
} catch (error){
console.error(error);
message.reply('there was an error trying to execute that command!');
}
})
//verify
//ban
client.on('guildMemberAdd', member => {
console.log(member.user.tag);
});
Error:
Error: Cannot find module './commands/ban.js'
Require stack:
- c:\Users\uporabnik\Documents\GitHub\zm-bot\src\bot.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
at Function.Module._load (internal/modules/cjs/loader.js:862:27)
at Module.require (internal/modules/cjs/loader.js:1042:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (c:\Users\uporabnik\Documents\GitHub\zm-bot\src\bot.js:13:21)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'c:\\Users\\uporabnik\\Documents\\GitHub\\zm-bot\\src\\bot.js' ]
}
My folderss:
enter image description here
Error: Cannot find module './commands/ban.js'
Require stack:
c:\Users\uporabnik\Documents\GitHub\zm-bot\src\bot.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
Basicly it trows the error and Im not sure how to fix it, please help since Im just stuck at the mmoment
Your folder structure looks like this:
ZM-Bot/
|
Commands/
| |
| ban.js
|
src/
|
app.js
If you want to require ban.js from app.js, you need to navigate out of src/ first.
So the path is ../commands/ban.js.
const commandFiles = fs.readdirSync(`../commands/`).filter(file => file.endsWith('.js'));