Discord.js starting two bots - javascript

I just made a command handler, but for some reason it starts two bots (I used the same commands I used before, I just put them inro a different file). I tried generating new token but that did not help. I rebooted my pc but nothing. This is my code:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
const fs = require("fs");
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("message", (message) => {
let args = message.content.substring(prefix.length).split(" ");
switch (args[0]) {
case "kick":
client.commands.get("kick").execute(message, args);
break;
case "serverinfo":
client.commands.get("serverinfo").execute(message, args);
break;
}
});
client.login(token);
}

The commands were in the for loop.

Related

Listing all the declared slash command to a json file Discord js

I'm building a discord bot using discord.js. All of my source code is from the official discord.js guide website, and I'm wondering how I could list all declared slash commands to a JSON file commands.json.
Here is my code:
deploy_commands.js:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
const commands = [];
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);
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);
index.js:
const { Client, Collection, Intents } = require("discord.js");
const client = new Client({intents: [Intents.FLAGS.GUILDS]});
const config = require("./config.json");
const { guildId, clientId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
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('ready', () => {
console.log(`user : ${client.user.tag}\nguildid : ${guildId}\nclientid : ${clientId}`);
});
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: 'Sorry, there was a problem while executing this command, maybe try again later?', ephemeral: true});
}
});
client.login(token);
deploy_commands.js is a file for deploying commands, and what I want to do is to save all the declared slash commands and transfer all of them to a JSON file.
I personally suggest you the usage of map() to manage the array where you store every command inside deploy_commands.js.
Following you can find a solution that worked for me:
const fs = require('fs');
const commands = [...commandBuilders...].map(command => command.toJSON());
const commandsToString = JSON.stringify(commands);
fs.writeFile('commands.json', commandsToString, (e, res) =>{
if (e) console.log('ERROR: ' + e);
}

Uncaught ReferenceError: command is not defined

I'm trying to do a command handler on a discord bot (with discord.js) but when I start the bot I get an error:
ReferenceError: command is not defined
This is the error I get
const discord = require('discord.js');
const intents = new discord.Intents();
const client = new discord.Client({ intents: 32767 });
const fs = require('fs');
const { readdirSync } = require('fs');
client.commands = new discord.Collection();
const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./comandos/${file}`);
client.commands.set(command.name, command);
}
let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
if(!cmd){
cmd.execute(client, message, args);
} else {
if(!cmd){
return;
}
}
const config = require('./config.js');
const prefix = config.prefix;
client.login(config.token);
That must be in a messageCreate event:
client.on("messageCreate", message => {
const [ command, ...args ] = message.content.split(/ +/g);
let cmd = client.commands.get(command) || client.commands.find((c) => c.alias?.includes(command));
if (cmd) { //you also made a mistake here, remove the "!"
cmd.execute(client, message, args);
}
})
The problem is that you're using const to define command inside the loop. You need to replace it with var and it should work fine:
const discord = require('discord.js');
const intents = new discord.Intents();
const client = new discord.Client({ intents: 32767 });
const fs = require('fs');
const { readdirSync } = require('fs');
client.commands = new discord.Collection();
const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
var command = require(`./comandos/${file}`);
client.commands.set(command.name, command);
}
let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
if(!cmd){
cmd.execute(client, message, args);
} else {
if(!cmd){
return;
}
}
const config = require('./config.js');
const prefix = config.prefix;
client.login(config.token);
(using "let" won't work either because it is not in the global scope).

How do you make your bot's command in different files?

I have a few files right now, but the main file is main.js. . . and I want each of my bot's commands in different files. How do I connect those files to main.js? This is my main.js file:
const Discord = require('discord.js');
const { token, prefix } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Dr. Gamer is now online!');
});
client.login(token);
You need to write what is called a "Command Handler" to do this.
Basically, you check the command name to a list of imported commands and call it.
Here's a very simple command handler which imports files from commands/
const discord = require('discord.js');
const fs = require('fs');
const { token, prefix } = require('./config.json');
const client = new discord.Client();
client.commands = new discord.Collection();
client.once('ready', () => {
console.log('Dr. Gamer is now online!');
fs.readdirSync('./commands/').forEach(file => {
if (!file.endsWith('.js')) return;
const f = require(`./commands/${file}`);
client.commands.set(file.replace('.js', ''), f);
});
});
client.on('message', (message) => {
// assuming ! is the prefix
if (!message.content.startsWith('!')) return;
let args = message.content.slice(/ +/g);
let command = args.shift();
if (client.commands.get(command)) {
client.commands.get(command).run(client, message, args);
}
});
client.login(token);
An example command:
// ping.js
exports.run = (client, message, args) => {
message.reply("Pong!");
}
Take a look at https://anidiots.guide/ for beginner Discord.js stuff, it's a great resource.

How to make the bot's status a variable

here's my code:
//All of the constants
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./myconfig10.json');
const client = new Discord.Client();
const cheerio = require('cheerio');
const request = require('request');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
//Telling the bot where to look for the commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
let activities = [
'with ur dad',
'with ur mom',
]
const pickedActivity = Math.floor(Math.random() * (activities.length - 1) + 1)
//Once the bot is up and running, display 'Ready' in the console
client.once('ready', () => {
client.user.setPresence({
status: 'online',
activity: {
name: (pickedActivity),
type: 'STREAMING',
url: 'https://www.twitch.tv/monstercat'
}
})
console.log('Ready!');
//Seeing if the message starts with the prefix
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
//Telling the bot what arguments are
const args = message.content.slice(prefix.length).trim().split(/ +/)
const commandName = args.shift().toLowerCase();
//Checking to see if the command you sent is one of the commands in the commands folder
if (!client.commands.has(commandName)) return;
console.log(`Collected 1 Item, ${message}`)
const command = client.commands.get(commandName);
//Try to execute the command.
try {
command.execute(message, args);
//If there's an error, don't crash the bot.
} catch (error) {
console.error(error);
//Sends a message on discord telling you there was an error
message.reply('there was an error trying to execute that command!');
}})})
client.login(token);
but when i try this, i get the error:
UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied name is not a string.
I know this means that the name of the status needs to be a string, so how would I be able to make it a variable?
I'm pretty new to this so it would be appreciated if your answer was in simple enough terms.
Thanks!
I think this should do the trick. Replace:
const pickedActivity = Math.floor(Math.random() * (activities.length - 1) + 1)
with:
const pickedActivity = activities[Math.floor(Math.random() * activities.length)]

My Discord bot reponds multiple time to one command and I want to know if there's a way to send it only once

When I make a command, my discord bot will respond multiple time instead of once. I'm using JavaScript and can't find any ways to make it work.
Here's my part of my main script:
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require("fs");
const 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.categories = fs.readdirSync("./commands/");
client.once('ready', () => {
console.log('Bot is online!');
});
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);
}
}
Here's my subfolder for the command ping:
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args){
message.channel.send('pong!')
}
}
Thanks for helping
Currently writing one too and I dont see anything wrong with this, is it possible your node is running twice?

Categories

Resources