Attempting to develop a Discord bot equipped with commands that are restricted by permissions. Upon testing the functionality, I encountered an unexpected error

  if(command.permissions.length){
    let invalidPerms = []
    for(const perm of command.permissions){
      if(!validPermissions.includes(perm)){
        return console.log(`Invalid Permissions ${perm}`);
      }
      if(!message.member.hasPermission(perm)){
        invalidPerms.push(perm);
        break;
      }
    }
    if (invalidPerms.length){
      return message.channel.send(`Missing Permissions: \`${invalidPerms}\``);
    }
  }

Error: ReferenceError: command is not defined Can anyone tell me why I'm facing this issue? I reviewed my code thoroughly and it appears to be correct.

Main.js Code

const Discord = require('discord.js');

const client = new Discord.Client({intents: ["GUILDS","GUILD_MESSAGES"]});

const prefix = '-';

const fs = require('fs');
const event_handler = require('./handlers/event_handler');

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

['command_handler', 'event_handler'].forEach(handler =>{
    require(`./handlers/${handler}`)(client, Discord);
})


client.login('Discord Login ID');

Event Handler Code

const fs = require('fs');

module.exports = (client, Discord) =>{
    const load_dir = (dirs) =>{
        const event_files = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith('.js'));

        for(const file of event_files){
            const event = require(`../events/${dirs}/${file}`);
            const event_name = file.split('.')[0];
            client.on(event_name, event.bind(null, Discord, client))
        }
    }
    
    ['client', 'guild'].forEach(e => load_dir(e));

}

Command Handler Code

const fs = require('fs');

module.exports = (client, Discord) =>{
    const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

    for(const file of command_files){
        const command = require(`../commands/${file}`);
        if(command.name){
            client.commands.set(command.name, command); 
        }   else{
            continue;
        }
    }
}

Message Guild Code

module.exports = (Discord, client, 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);

    if(command) command.execute(client, message, args, Discord);
}

^This includes the command permissions

Added additional sections of my code. Can anyone identify the issue? I have double-checked everything, and it seems to be correct. Please take a look, but I believe the problem lies within the code itself, not a typo.

Answer №1

The problem lies in the fact that command is scoped within the module export, making it inaccessible in the top section of the code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to send a POST variable to PHP without refreshing the webpage

Is there a way to pass a simple variable from a text-box on a different page to PHP without reloading it? I've been informed that Ajax is required for this task, but I'm unsure of how to go about implementing it. Can someone provide me with a sam ...

I am encountering an issue where req.body is returning as undefined

After creating a controller with the code below: app.post('/users', (req, res) => { console.log(req.body); const user = new User({ name: req.body.name, email: req.body.email }); user.sa ...

Finding queries in MongoDB collections seem to be stalling

I have been attempting to create a search query to locate a user by their username. Here is the code: userRouter.get('/user/:user_username', function(req, res) { console.log("GET request to '/user/" + req.params.user_username + "'"); ...

Creating TypeScript domain objects from JSON data received from a server within an Angular app

I am facing a common challenge in Angular / Typescript / JavaScript. I have created a simple class with fields and methods: class Rectangle { width: number; height: number; area(): number { return this.width * this.height; } } Next, I have a ...

Setting up Node.js for production on Nginx: A comprehensive guide

I am working on developing a chat system using angularjs and nodejs. To enable message sending and receiving, I have implemented socket.io. Initially, I set up a node.js server using localhost cmd. Everything is functioning properly, but now I need to dep ...

What's the alternative now that Observable `of` is no longer supported?

I have a situation where I possess an access token, and if it is present, then I will return it as an observable of type string: if (this.accessToken){ return of(this.accessToken); } However, I recently realized that the of method has been deprecated w ...

Show a modal when the axios request is finished

EDIT: After some exploration, I've shared the solution I found in case it helps others facing a similar issue. I'm currently working on building a reusable Bootstrap 5 modal child component within Vue3. The goal is to pass an ID as a prop from t ...

Integrate Geometric Information into PostGIS

Hi there! I'm currently using a combination of postgresql and node.js for my backend operations. I've been trying to insert a point into the database from the frontend, but unfortunately, I keep encountering an error message stating "value too lo ...

Ensure that all items retrieved from the mongoDB query have been fully processed before proceeding further

In the midst of a challenging project that involves processing numerous mongoDB queries to display data, I encountered an issue where not all data was showing immediately upon page load when dealing with large datasets. To temporarily resolve this, I imple ...

Concentrate and select non-interactive elements with your mouse

Is it possible to set tab index on non-form elements like the div tag? I tried using tab index, but when the div is focused and the enter button is tapped, the ng-click event associated with the div tag is not triggered. <div tabindex="0" role="butto ...

Having trouble retrieving data about my marker through react-leaflet

Hello, I am currently working on accessing information about my marker using React and react-leaflet, which is a library based on Leaflet. I initially tried to utilize useRef, but unfortunately it did not provide the expected results. When attempting to us ...

Utilizing Vue.js with Firestore: Retrieve information from Firestore without rendering any data on the screen

When attempting to display my data from Firestore, I encountered an issue where the data was retrieved successfully when hovering over the <td> tag but not actually displayed. Here is my file for fetching data from Firestore: <template> & ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

What could be causing vertices in Three.js to not update?

I currently have a loop of circles that are moving independently. My goal is to draw lines from the center of the canvas to each circle's location. The issue I am facing is that the lines are not updating their vertices correctly during rendering, eve ...

AngularJS dual-stage resolution for resolving dependencies

I am facing a scenario where I must resolve one item before obtaining the data necessary to resolve another: .state('addtrip', { url: '/addtrip', templateUrl: 'views/addtrip.html', controller: &a ...

Is it possible to dynamically close the parent modal based on input from the child component?

As I follow a tutorial, I am working on importing the stripe function from two js files. The goal is to display my stripe payment in a modal. However, I am unsure how to close the modal once I receive a successful payment message in the child. Below are s ...

Prevent Android WebView from attempting to fetch or capture resources such as CSS when using loadData() method

Context To many, this situation might appear to be repetitive. However, I assure you that it is not. My objective is to import html data into a WebView, while being able to intercept user hyperlink requests. During this process, I came across this helpfu ...

Is there a way to implement an onclick event on a specific line of text that triggers a popup box only when the text is clicked, without the popup appearing automatically when

I received assistance from a fellow user to customize a popup that turned out great. However, I'm having trouble getting the onclick function to work properly so that the popup only appears when the phone number is clicked. Ideally, I want the phone n ...

Display two images consecutively within a single img tag

My goal is to display two images using a single <img /> tag. The first small image will be loaded and shown using the src attribute, while the second large image will be contained within the data-src attribute. Only one image will be displayed at a t ...

How can I utilize jQuery to save a simple text string in a mySQL database?

Seeking guidance on this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('im ...