Every time I try to run my discord bot I get this error:
node:internal/modules/cjs/loader:1047
const err = new Error(message);
^
Error: Cannot find module './src/Commands/Tools/ping.js'
Require stack:
- /Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js
- /Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1047:15)
at Module._load (node:internal/modules/cjs/loader:893:27)
at Module.require (node:internal/modules/cjs/loader:1113:19)
at require (node:internal/modules/cjs/helpers:103:18)
at client.handleCommands (/Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js:15:25)
at Object.<anonymous> (/Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js:19:8)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Module._load (node:internal/modules/cjs/loader:930:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js',
'/Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js'
]
}
Here are my bot.js, commandHandler.js, and ping.js files and my file structure
bot.js
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.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.handleCommands();
client.handleEvents();
client.login(token);
commandHandler.js
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const fs = require("fs");
const path = require("node:path");
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync(`./src/Commands`);
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`src/Commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`src/Commands/${folder}/${file}`);
commands.set(command.data.name, command);
commandArray.push(command, command.data.toJSON());
console.log(`Command: ${command.data.name} has been registered`);
}
}
const clientId = "1070133880671174697";
const guildId = "1070126560004276305";
const rest = new REST({ version: "9" }).setToken(process.env.token);
try {
console.log("Started refreshing commands.");
await rest.put(Routes.applicationCommands(clientId, guildId), {
body: client.commandArray,
});
console.log("Successfully refreshed commands.");
} catch (err) {
console.error(error);
}
};
};
ping.js
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Returns my ping"),
async execute(interaction, client) {
console.log("pinged");
},
};
File Structure
File Structure
I've tried editing it myself, checking I've written the right code in the tutorial, and extensive googling, but nothing works, and for people who have had the same problem theirs just 'magically' fixed.
Edit 1 - I have tried ../../src as #rebe100x suggested but when I did path.basename it gave me this error
Error: ENOENT: no such file or directory, scandir 'Tools'
Edit 2 - I used 'src/Commands/${folder} but now it gives me the same error as before
On commandHandler.js line 15
const command = require(`./src/Commands/${folder}/${file}`);
The file directory is wrong. From your structure, commandHandler.js is in Function > Handlers > commandHandler.js.
Simply change the directory to ../../src/Commands/${folder}/${file} and it should fix the path problem
Related
/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:548
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:548:13)
at new Client (/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:76:10)
at Object.<anonymous> (/home/kevind/Downloads/VibeUtils2/commands/role.js:3:16)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155: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> (/home/kevind/Downloads/VibeUtils2/index.js:13:21) {
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
This is the error I'm getting, however my code looks like
const fs = require('fs');
const {prefix, reactEmoji, token, clientId, guildId} = require('./config/config.json');
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
const { Client, Collection, Intents, Discord } = require('discord.js');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MESSAGES] });
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.name, command);
}
const commands = [];
const slashcommandFiles = fs.readdirSync('./slashcommands').filter(file => file.endsWith('.js'));
for (const file of slashcommandFiles) {
const command = require(`./slashcommands/${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);
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
client.on('message', message => {
if (message.content.toLowerCase().startsWith('welcome')) {
message.react(reactEmoji);
console.log(`Reacted on ${message.author.tag}'s 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;
try {
command.execute(message, args);
}catch (error) {
console.error(error);
message.reply('There was an error while trying to execute that command!');
}
})};
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);
I'm still handing normal commands until v12 gets deprecated,and so I can transition. However I'm having issues with intents. Please help me on what intents are valid, because those look valid to me. If I'm doing something critically wrong, then please let me know. This is one of my first times actually delving into v13, however as far as I've seen I've done everything correct, that is going off of documentation. If I missed something please let me know, because I think that should work. Most of my ready is handled in an event file.Is there an easy way to add all intents? The ways I've seen here don't work
Ensure your intents are turned on in your Developer Portal.
Go to https://discord.com/developers/applications
Click on your application
Click on the "Bot" section
Enable the intents you need there; these are only privileged intents so not everything will be there, you will need the Server Members Intent & Message Content Intent (just so you're ready for when it is enforced)
Upon checking,GUILD_EMOJIS_AND_STICKERS and GUILD_BANS are not valid intents in Discord.js V12. You'll either need to switch or remove those intents from your array. (Added from comments, just so it's easier to find)
As for adding every intent at once, that's not really possible. Though you could run this in the repl and paste the results into the intents array (this is done in V13, I highly suggest running this yourself in a node repl so it uses your Discord.js version):
const discord = require("discord.js"); const intents = Object.keys(discord.Intents.FLAGS); let formattedIntents = []; intents.forEach((intent) => {formattedIntents.push(`"${intent}"`)}); formattedIntents;
(I made this as one-line as possible because I tested it in my bot's eval slash command, but what it does is pretty simple, imports d.js, gets the keys of the discord.Intents.FLAGS, makes an empty array to hold them, loops through the intents and pushes it to the array, then outputs the list of intents.)
Which should output
"GUILDS","GUILD_MEMBERS","GUILD_BANS","GUILD_EMOJIS_AND_STICKERS","GUILD_INTEGRATIONS","GUILD_WEBHOOKS","GUILD_INVITES","GUILD_VOICE_STATES","GUILD_PRESENCES","GUILD_MESSAGES","GUILD_MESSAGE_REACTIONS","GUILD_MESSAGE_TYPING","DIRECT_MESSAGES","DIRECT_MESSAGE_REACTIONS","DIRECT_MESSAGE_TYPING","GUILD_SCHEDULED_EVENTS"
though I'm not sure if you really want or need every intent.
I have a code which I'm doing on replit, and I'm pretty new to node.js so I really do need assistance with this. I have a code which is this:
const Discord = require("discord.js")
const fetch = require("node-fetch")
const client = new Discord.Client()
const mySecret = process.env['TOKEN']
function getQuote() {
return fetch('https://zenquotes.io/api/random')
.then(res => {
return res.json
})
.then(data => {
return data[0]["q"] + " —" + data [0]["a"]
})
}
client.on("ready", () => {
console.log('Logged in as ${client.user.tag}' )
})
client.on("message", msg => {
if (msg.author.bot) return
if (msg.content === "$inspire") {
getQuote().then(quote => msg.channel.send(quote))
}
})
client.login(process.env.TOKEN)
However, I'm receiving the error:
npx node .
/home/runner/1Starty/index.js:2
const fetch = require("node-fetch")
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/runner/1Starty/node_modules/node-fetch/src/index.js from /home/runner/1Starty/index.js not supported.
Instead change the require of /home/runner/1Starty/node_modules/node-fetch/src/index.js in /home/runner/1Starty/index.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/home/runner/1Starty/index.js:2:15) {
code: 'ERR_REQUIRE_ESM'
}
May someone help me on why this is the case?
Open shell and run this command
npm i node-fetch#2.6.6
I've got all the packages necessary and whatnot but I keep on getting an error. First of all, here's my coding (in a file called main.js.):
const client = new Discord.Client();
require("dotenv").config();
const fs = require('fs');
const mongoose = require('mongoose');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
["command_handler", "event_handler"].forEach((handler) => {
require(`./handlers/${handler}`)(client, Discord);
});
mongoose
.connect(process.env.MONGODB_SRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(()=>{
console.log('Connected to the database!');
})
.catch((err) => {
console.log(err);
});
client.login(process.env.DISCORD_TOKEN);
My error is
C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:10
client.on(event_name, event.bind(null, Discord, client));
^
TypeError: event.bind is not a function
at load_dir (C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:10:41)
at C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:14:38
at Array.forEach (<anonymous>)
at module.exports (C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:14:25)
at C:\Users\shann\Desktop\DiscordBot\main.js:11:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\shann\Desktop\DiscordBot\main.js:10:38)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
I honestly don't know what the problem is this time. Should I define event.bind? I thought .bind was a function and event was the variable. I've been following a tutorial. I do have mongoose installed through the command center but I don't know if I should reinstall it. Also, I don't see any errors in my coding but I am pretty new so please point them out and how I can fix it!
The coding for command_handler.js
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;
}
}
}
The coding for event_handler.js is
const fs = require('fs');
module.exports = (client, Discord)=>{
const load_dir = (dirs)=>{
const event_files = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith('.js'));
for(const file of event_files){
const event = require(`../events/${dirs}/${file}`);
const event_name = file.split('.')[0];
client.on(event_name, event.bind(null, Discord, client));
}
}
['client', 'guild'].forEach(e => load_dir(e));
}
There isn't actually much of an answer here but the thing is, you don't even need an advanced event handler. All I did was remove the event handler from my handlers and added an event handler to my main.js. Then I removed client and guild from my events. After that, I made it so that in main.js it would look at all the files in events (the folder with all my events) and run them (using fs)!
Credits to #WorthyAlpaca for the help in introducing this alternate method
I am making a Discord Bot. Now I've added command handling. The Bot Starts normal but if I type the command it chrashes with this error code:
C:\Users\Matteo\sudo_\sudocanary\index.js:24
client.commands.get('ping').execute(message, args);
^
TypeError: Cannot read property 'execute' of undefined
at Client.<anonymous> (C:\Users\Matteo\sudo_\sudocanary\index.js:24:36)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\Matteo\sudo_\sudocanary\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\Matteo\sudo_\sudocanary\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\Matteo\sudo_\sudocanary\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\Matteo\sudo_\sudocanary\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\Matteo\sudo_\sudocanary\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\Matteo\sudo_\sudocanary\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\Matteo\sudo_\sudocanary\node_modules\ws\lib\websocket.js:825:20)
Process finished with exit code 1
This is my Code from the index.js:
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.on('ready', () => {
console.log('Ready!');
});
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);
}
})
client.login(token);
And now the code from the ping.js:
module.exports.execute = {
name: 'ping',
description: 'Ping!',
execute(message) {
message.channel.send('Pong.');
},
};
Thanks! (I am using discord.js v12)
In your index.js, you need to add your commands to your client.commands in order to actually use them. You've also used module.exports.execute in your ping.js, whereas you should be using just module.exports (the execute() method is already defined within your module.exports, as the method execute(message)).
Here are the fixes in your code.
index.js:
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);
}
ping.js:
module.exports = {
name: 'ping',
description: 'Ping!',
execute(message) {
message.channel.send('Pong.');
},
};
Please look more closely at the examples of the command handler you are attempting to use, as they show the proper way to do this and explain what each part of the command handler does. I would advise going through the discordjs.guide command handler examples and learning how everything works.
I'm creating a discord bot using the discord.js v12.2.0 library. In my file Command.js, I have this code:
const { readdirSync } = require("fs")
module.exports = (Bot) => {
const load = dirs => {
const Commands = readdirSync(`./SRC/Commands/${dirs}/`).filter(d => d.endsWith('.js'));
for (let file of Commands) {
let pull = require(`../Commands/${dirs}/${file}`);
Bot.Commands.set(pull.config.name, pull);
if (pull.config.aliases) pull.config.aliases.forEach(a => Bot.aliases.set(a, pull.config.name));
};
};
["Miscellaneous", "Moderation", "Owner"].forEach(x => load(x));
};
This is my Index.js file:
const { Client, Collection } = require("discord.js");
const { Token } = require("./Config.json");
const Bot = new Client();
["aliases", "commands"].forEach(x => Bot[x] = new Collection());
["console", "command", "event"].forEach(x => require(`./SRC/Handlers/${x}`)(Bot));
Bot.login(Token);
The error I get from running this code is TypeError: Cannot read property 'set' of undefined
This is my Project Structure
Have you initialized Bot.Commands to a Discord.Collection() ?
index.js or whatever main file
const Discord = require("discord.js");
const Bot = new Discord.Client();
Bot.Commands = new Discord.Collection();
//or
const { Client, Collection } = require("discord.js");
const Bot = new Client();
Bot.Commands = new Collection();
I would suggest you make Bot and commands lowercase as that's the convention in js, and helps others understand better.