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"));
Related
I'm Currently trying to implement SlashCommandBuilder into my Discord Bot.
The bot is currently using prefix '!' and I want to remake it to work with the SlashCommandBuilder, The following code is what i have used and tested, as it pretty much works fine or looks like it's working fine I'm still having an issue caused when someone uses '/hello' It will give him Error 'The application did not respond'.
I did double check the API, Token and such using a Prefix as a check.
The Code does actually add the command to the discord and it looks in the lists of commands.
I'm also splitting the commands inside 'commands' folder.
index.js :
const Discord = require('discord.js');
const fs = require('fs');
const { Client, Collection } = require('discord.js');
const { REST } = require('#discordjs/rest');
const config = require('./config.json');
const { Routes } = require('discord-api-types/v9');
const client = new Client();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
client.commands = new Collection();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Bot is ready!');
const rest = new REST({ version: '9' }).setToken(config.token);
rest.put(
Routes.applicationCommands(client.user.id),
{ body: client.commands },
)
.then(() => console.log('Successfully registered commands'))
.catch(error => console.error(error));
});
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);
interaction.reply({ content: 'Error executing command', ephemeral: true });
}
});
client.login(config.token)
commands/hello.js
module.exports = {
name: 'hello',
description: 'Replys with Hi',
execute(interaction) {
interaction.reply({ content: 'Hi!' });
},
};
Please if anyone has information on why this was caused, i would love to listen.
Thank you for reading and appreciate any help or hints.
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.
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
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!');
}
});
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.