Uncaught ReferenceError: command is not defined - javascript

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).

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);
}

Discord bot not show "success message" in Visual Studio Code

const Discord = require('discord.js');
// fs
const fs = require('fs');
// path
const path = require('path');
// config
const config = require('./config.json');
// config.json
const token = config.token;
// config config.json
const PREFIX = config.prefix;
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: \[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES\] })
client.commands = new Discord.Collection();
// message
client.on('message', message =\> {
// message not sent by bot
if (!message.author.bot) {
// if the message starts with the prefix
if (message.content.startsWith(PREFIX)) {
// split the message into an array
const args = message.content.slice(PREFIX.length).split(/ +/);
// command is the first element of the array
const command = args.shift().toLowerCase();
// ping command
if (command === 'ping') {
// send a message to the channel
message.channel.send('pong');
}
// success message after login
client.on('ready', () =\> {
console.log(`Logged in as ${client.user.tag}!`);
})
// token config file
client.login(config.token);
so I run node index.js it's supposed to shown Logged in as "my bot name here" on the VSC terminal and should be online on the discord, but it doesn't and I can't figure it out, mind anyone help
Formatting will save your life, Bro:
Also, I'd recommend less comments. It's a lot of noise. I refactored this stuff out. Look how much nicer your code looks:
const { token, prefix: PREFIX } = require('./config.json');
const { Collection, Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
client.commands = new Collection();
client.on('message', message => {
if (message.author.bot) return
if (!message.content.startsWith(PREFIX)) return
const args = message.content.slice(PREFIX.length).split(' ');
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('pong');
}
})
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
})
client.login(token);

Discord.js - ReferenceError: DiscordCollection is not defined

I was coding a bot using Discord.js, following Codelyon's code, and I am stuck with this error:
ReferenceError: DiscordCollection is not defined at Object.<anonymous>
const {Client, Intents, DiscordAPIError, Collection} = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const prefix = '-';
const fs = require('fs');
client.commands = new DiscordCollection();
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('Ceeby 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);
}
})
client.login('TOKEN')
There are 2 common methods to import and use a libraries such as discord.js: importing the whole module or object destructuring- examples of both below. You seem to be trying to do both at the same time, you destructor the object but use Discord.Client and Discord.Collection instead of just Client and Collection.
Whole Module
const Discord = require('discord.js');
...
const client = new Discord.Client({ intents: ['GUILDS', 'GUILD_MESSAGES'] });
...
client.commands = new Discord.Collection();
Object Destructuring
const { Client, Collection, DiscordAPIError } = require('discord.js');
...
const client = new Client({ intents: ['GUILDS', 'GUILD_MESSAGES'] });
...
client.commands = new Collection();

Discord.js starting two bots

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.

Getting ReferenceError: (token) is not defined JavaScript Discord

Recently, I've been working on a bot called Music Bot. And, it showed up with this error message:
C:\Users\yuhao\Desktop\discord-bot-master\index.js:51
client.login(token);
^
ReferenceError: token is not defined
at Object.<anonymous> (C:\Users\yuhao\Desktop\discord-bot-master\index.js:51:14)
at Module._compile (internal/modules/cjs/loader.js:1144:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)
at Module.load (internal/modules/cjs/loader.js:993:32)
at Function.Module._load (internal/modules/cjs/loader.js:892:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
C:\Users\yuhao\Desktop\discord-bot-master>
My token format have lots of dots, but, at ReferenceError, it showed up with no dots and the one before the dot.
This the the script for index.js:
const fs = require('fs')
const Discord = require('discord.js');
const Client = require('./client/Client');
const {
prefix,
token,
} = require('./config.json');
const client = new Client();
client.commands = new Discord.Collection();
const queue = new Map();
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);
}
console.log(client.commands);
client.once('ready', () => {
console.log('Ready!');
});
client.once('reconnecting', () => {
console.log('Reconnecting!');
});
client.once('disconnect', () => {
console.log('Disconnect!');
});
client.on('message', async message => {
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName);
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
try {
command.execute(message);
} catch (error) {
console.error(error);
message.reply('There was an error trying to execute that command!');
}
});
client.login(token);
And this is config.json:
{
"prefix": "!",
"token": "token"
}
Thats all. Help me please on reply section, thx!
Your problem is that you haven't populated your token or prefix. You need to parse your JSON like this for the object in question to be populated.
JS:
const fs = require('fs')
...
const config = JSON.parse(fs.readFileSync(filename, "UTF-8");
client.login(config.token);
TS (with a class so you don't have to worry about mistyping values, as you will get autocompletion):
export default class Settings {
public token: String;
public prefix: String;
}
...
const config: Settings = JSON.parse(fs.readFileSync(filename, "UTF-8");
client.login(config.token);
use like this
const fs = require('fs')
const Discord = require('discord.js');
const Client = require('./client/Client');
const config = require('./config.json');
const client = new Client();
client.commands = new Discord.Collection();
const queue = new Map();
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);
}
console.log(client.commands);
client.once('ready', () => {
console.log('Ready!');
});
client.once('reconnecting', () => {
console.log('Reconnecting!');
});
client.once('disconnect', () => {
console.log('Disconnect!');
});
client.on('message', async message => {
const args = message.content.slice(config.prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName);
if (message.author.bot) return;
if (!message.content.startsWith(config.prefix)) return;
try {
command.execute(message);
} catch (error) {
console.error(error);
message.reply('There was an error trying to execute that command!');
}
});
client.login(config.token);

Categories

Resources