fs has already been declared - node.js

enter image description here
const fs = require('fs');
const path = require('path');
const {
Client,
Collection,
Intents
} = require('discord.js');
const chalk = require('chalk')
const config = require('./config.json');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MEMBERS],
});
const Discord = require('discord.js');
client.discord = Discord;
client.config = config;
client.commands = new Collection();
const commandFiles = fs.readdirSync(path.resolve('G:\\Five_M\\txData\\ZAP-HostingESXPack_EBD469.base\\resources\\ticketbot','./commands')).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
};
const eventFiles = fs.readdirSync(path.resolve('G:\\Five_M\\txData\\ZAP-HostingESXPack_EBD469.base\\resources\\ticketbot', './events')).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
client.on(event.name, (...args) => event.execute(...args, client));
};
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction, client, config);
} catch (error) {
console.error(error);
return interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true
});
};
});
client.login(require('./config.json').token);
[ script:ticketbot] Error loading script index.js in resource ticketbot: SyntaxError: Identifier 'fs' has already been declared
[ script:ticketbot] stack:
[ script:ticketbot] SyntaxError: Identifier 'fs' has already been declared
Need Help with this issue mention "fs has already been declared"

Related

Discord.js command handling. Command handling dont work

I copied the code exactly from the official Discord.JS Guide. But the bot does not respond to the command in any way. How to solve it?
index.js:
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
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(Events.ClientReady, () => {
console.log('Ready!');
});
client.on(Events.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);
config.json:
{
"clientId": "my id",
"guildId": "my id",
"token": "my token"
}
ping.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
return interaction.reply('Pong!');
},
};
I searched on the Internet, and even found something, but in an attempt to repeat this, the bot did not respond to commands, although it turned on calmly.

Discord.js cooldown not working, what should I do?

I want to create a cooldown for my team, but when using the command multiple times, the cooldown doesn't appear.
My code:
const fs = require('fs');
const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');
const Discord = require('discord.js');
const { Client, GatewayIntentBits, Collection} = require('discord.js');
const Timeout = new Discord.Collection();
const client = new Client({
intents: [
GatewayIntentBits['Guilds'],
GatewayIntentBits['GuildMessages'],
GatewayIntentBits['MessageContent']
]
});
const { prefix, token } = require('./config.json');
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('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)) return;
if (command) {
if(command.timeout) {
if(Timeout.has(`${command.name}${message.author.id}`)) return message.channel.send(`Осталось ждать \`${ms(Timeout.get(`${command.name}${message.author.id}`) - Date.now(), {long : true})}\`секунд!`)
command.run(client, message, args)
Timeout.set(`${command.name}${message.author.id}`, Date.now() + command.timeout)
setTimeout(() => {
Timeout.delete(`${command.name}${message.author.id}`)
}, command.timeout)
}
}
try {
client.commands.get(command).execute(client, message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
And this is the command
const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');
const { EmbedBuilder} = require('discord.js');
module.exports = {
name: 'ферма1',
timeout: 15,
execute(client, message, args) {
...
I searched on this topic but I've still not found a way to make the cooldown work

TypeError: Cannot read properties of undefined (reading 'login')

My Index.js is having a error. I can't understand why.
const { Client, Collection } = require("discord.js");
const { readdirSync } = require("fs");
const { join } = require("path");
const { TOKEN, PREFIX } = require("./util/Util");
const i18n = require("./util/i18n");
const { Intents, client } = require('discord.js');
client.login(TOKEN);
client.commands = new Collection();
client.prefix = PREFIX;
client.queue = new Map();
const cooldowns = new Collection();
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
client.on("ready", () => {
console.log(`${client.user.username} ready!`);
client.user.setActivity(`with ${client.guilds.cache.size} servers`);
});
client.on("warn", (info) => console.log(info));
client.on("error", console.error);
const commandFiles = readdirSync(join(__dirname, "commands")).filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(join(__dirname, "commands", `${file}`));
client.commands.set(command.name, command);
}
client.on("message", async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
const prefixRegex = new RegExp(`^(<#!?${client.user.id}>|${escapeRegex(PREFIX)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [, matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.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;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 1) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
i18n.__mf("common.cooldownMessage", { time: timeLeft.toFixed(1), name: command.name })
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply(i18n.__("common.errorCommand")).catch(console.error);
}
});
client.login(TOKEN);
The import is called Client instead of client. So change your import and instantiate the client like so:
const { Intents, Client } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
You will have to set the intents according to your own use case, as per this answer.
You are calling client.login(TOKEN); two times, in the beginning and in the final of the code.

Bot not responding to commands (discord.js v12)

I've tried doing a test command using client.on which worked but everything else in my command handler does not work. Nothing is returned, is there something I am doing wrong?
Issue: My ping command does not do anything whatsoever.
Index.js file
require('dotenv').config();
const Discord = require('discord.js');
const { Client, Collection, Intents } = require('discord.js');
const config = require('./config.json');
const fs = require("fs");
const client = new Client({ disableMentions: 'everyone', partials: ['MESSAGE', 'CHANNEL', 'REACTION'], ws: { intents: Intents.ALL } });
const PREFIX = config.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.commands = new Collection();
Ping file
let config = require('../config.json');
const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ping',
category: 'Info',
description: 'Returns the bot\'s latency and API ping.',
aliases: ['latency'],
usage: 'ping',
userperms: [],
botperms: [],
run: async (client, message, args) => {
message.channel.send('🏓 Pinging....').then((msg) => {
const pEmbed = new MessageEmbed()
.setTitle('🏓 Pong!')
.setColor('BLUE')
.setDescription(
`Latency: ${Math.floor(
msg.createdTimestamp - message.createdTimestamp,
)}ms\nAPI Latency: ${client.ws.ping}ms`,
);
msg.edit(pEmbed);
});
},
};
You need to add event which will trigger every time a message is created and the bot can see it.
An example on version 12 would be (using message :
client.on('message', message => {
if (message.content.startsWith("!ping")) {
message.channel.send('Pong!');
}
});
In v13, message is deprecated so use messageCreate :
client.on('messageCreate', message => {
if (message.content.startsWith("!ping")) {
message.channel.send('Pong!');
}
});

Discord.JS Events Handler Commands

Ok so I finally figured out how to code my fs events handler to use the events folder. now I just need to know the basic method for coding the evtns in their own files.
Here is what I have for now [starting with the ready.js file]. Is this correct and if not how do I code the event files properly?
module.exports = {
name: 'avatar',
description: 'Get the avatar URL of the tagged user(s), or your own avatar.',
execute(message) {
client.on("ready", () => {
client.user.setActivity(`on ${client.guilds.size} servers`);
console.log(`Ready to serve on ${client.guilds.size} servers, for ${client.users.size} users.`);
}
}};
This is my index.js file for reference:
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token } = require('./config.json');
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);
}
fs.readdir('./events/', (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
const eventFunction = require(`./events/${file}`);
if (eventFunction.disabled) return; //
const event = eventFunction.event || file.split('.')[0];
const emitter = (typeof eventFunction.emitter === 'string' ? client[eventFunction.emitter] : eventFunction.emitter) || client; /
const once = eventFunction.once;
try {
emitter[once ? 'once' : 'on'](event, (...args) => eventFunction.run(...args));
} catch (error) {
console.error(error.stack);
}
});
});
client.login(token);
The upper code block is not ready.js its avatar.js i think.

Resources