Search code examples
javascriptnode.jsdiscord.js

ReferenceError: Discord is not defined, at new Discord.Collection



I have been following a tutorial to create a Discord bot by CodeLyon. I am up to the point of organizing commands into files. The 'ping' command worked when I was using the basic method in the tutorial, but after trying to use this method my command prompt threw this error when I tried to run it:

client.commands = new Discord.Collection();
                      ^

    ReferenceError: Discord is not defined
        at Object.<anonymous> (C:\Users\name\OneDrive\Desktop\VSC 
    Project 1\main.js:10:23)
←[90m    at Module._compile (node:internal/modules/cjs/loader:1101:14)←[39m
←[90m    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)←[39m
←[90m    at Module.load (node:internal/modules/cjs/loader:981:32)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39m
←[90m    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)←[39m
←[90m    at node:internal/main/run_main_module:17:47←[39m

I have definitely installed node.js and discord.js, which were issues I saw other people had. However looking around I didn't see anyone with quite my issue so I decided to ask. I am pretty new to applying JavaScript but I know the syntax and some of the basics so I don't think it's that after reading through a few times.
Here is the general area where the error was thrown, it starts at line 1 and the error is at line 10.
const { Client, Intents, DiscordAPIError } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
// Lines 1 & 2 were changed from original tutorial in order to fix the Intents not defined error

const prefix = '-';

const fs = require('fs');


client.commands = new Discord.Collection(); // * Error is thrown here *


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

I can share any of the other code if it's needed. Any help appreciated, since I don't know what's wrong :)


Solution

  • This was caused as you have not required your package discord.js as to a single constant Discord, you see every package is a module which has various properties and functions as displayed below:

    components of discord.js


    At the very top of your file you are destructuring these components from the module discord.js so you very well need to destructure the Collection too! like so:
    
        const { Client, Intents, DiscordAPIError, Collection } = require('discord.js');     
        // then you may define it like so    
        client.commands = new Collection()    
    
    

    This would be absolutely valid as you can see here: display