Discord.JS Events Handler Commands - node.js

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.

Related

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

message is not defined discord.js slashcommands

I'm getting an error saying that I'm not defining message
content: `🏓Latency is ${Date.now() - message.createdTimestamp}ms.`,
^
ReferenceError: message is not defined
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '.';
const fs = require('fs');
const guildId = ''
const getApp = (guildId) => {
const app = client.api.applications(client.user.id)
if (guildId) {
app.guilds(guildId)
}
return app
}
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', async () => {
console.log('HenBot Is Online!');
const commands = await getApp(guildId).commands.get()
console.log(commands)
await getApp(guildId).commands.post({
data: {
name: 'ping',
description: 'Bots Latency',
},
})
client.ws.on('INTERACTION_CREATE', async (interaction, message) => {
const slashCommmand = interaction.data.name.toLowerCase()
if(slashCommmand === 'ping') {
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: `🏓Latency is ${Date.now() - message.createdTimestamp}ms.`,
},
},
})
}
})
})
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);
}
})
It’s because message is not a valid parameter for interactionCreate.
As the discord.js docs implies, you can only pass in interaction in an interactionCreate event.
This should work for your code:
content: `🏓Latency is ${Date.now() - interaction.createdTimestamp}ms.`,
interactionCreate event cannot have message parameter...
client.on('interactionCreate', async interaction => {
// your code here
})

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.

Discordjs: How to fix execute is not defined?

I started making a music bot for my discord server when i input command for playing song it returns that execute is not defined i tried to fix but i had no success. That's why I am asking here.
Note: I made event and command handler but that is not the problem since it was also not working before implementing it.
Here is my code from event that happens on message aka starting command:
module.exports = (client, Discord, message)=>{
const prefix = '-';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split('/ +/');
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
//const ChannelName = message.channel.name;
try{
command.execute(args, cmd, client, Discord, message);
} catch(err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
And here is my code for play command:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
cooldown: 0,
description: 'Advanced music bot',
async execute(args, cmd, client, Discord, message){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`👍 **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue 😔`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}
I think that problem is in main part of code but I cant seem to find problem.
Here is code for command handling
const fs = require('fs');
module.exports = (client, Discord) =>{
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`../commands/${file}`);
if(command.name){
client.commands.set(command.name, command);
} else{
continue;
}
}
}
And here is my main file of the bot with commands collection
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
client.user.setStatus('online')
console.log('Bot is online!');
client.user.setActivity('Youtube',{
type:"LISTENING"
})
console.log('Servers:')
client.guilds.cache.forEach((guild) => {
console.log('-' + guild.name)
})
});
const fs = require('fs');
const message = require('./events/guild/message');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
['command_handler', 'event_handler'].forEach(handler =>{
require(`./handlers/${handler}`)(client, Discord);
})

Bot looping through directory for mp4 specific file

I'm trying to make a bot where it would upload a mp4 attachment with a specific command. What i wanted to know is if there was a way where the bot would cycle through the directory for the certain file instead of me writing like 600 lines worth of code.
const fs = require('fs');
const { Client, MessageAttachment } = require('discord.js');
const config = require('./config.json');
const { prefix, token } = require('./config.json');
const client = new Client();
const { MessageEmbed } = require('discord.js');
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.on('ready', () => {
console.log(`${client.user.tag} is now online!`);
client.user.setPresence({status: 'idle'});
client.user.setActivity('My Stokeley Playlist 🌙', { type: 'LISTENING' })
});
client.on('message', (message) => {
const { content, author, channel } = message
if (author.bot) {
return
}
const embeds = {
[`${prefix}snip kratos`]: {
title: 'Kratos',
attachmentPath: './snippets/kratos/Kratos.mp4',
},
[`${prefix}snip johnny bravo`]: {
title: 'Johnny Bravo',
attachmentPath: './snippets/Johnny_Bravo/Johnny_Bravo.mp4',
},
}
const embed = embeds[content]
if (embed) {
const { title, attachmentPath } = embed
channel.send(
new MessageEmbed()
.setColor('#ffb638')
.setTitle(title)
.setDescription('Sending 1 snippet...')
.setTimestamp()
.setFooter('SkiBot')
)
channel.send(new MessageAttachment(attachmentPath))
}
})
here's my current code, I'm trying to find an easier and cleaner way to go about this.
I think you have already used this in a part of your code
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
So try this
const musicFiles = fs.readdirSync('./snippets/kratos').filter(file => file.endsWith(".mp4"));

Resources