Error: guild is not defined | discord.js

Having trouble with a ReferenceError that says guild is not defined? I recently encountered a similar issue with members but managed to fix it by adding a constant. As someone new to javascript and node.js, I could use some assistance. I've even tried checking index.js and copying the constants above without success.

const member = guild.member.first(message.author);
               ^

ReferenceError: guild is not defined
    at Object.<anonymous> (C:\bot1\commands\prune.js:7:16)
[90m    at Module._compile (internal/modules/cjs/loader.js:1138:30)[39m
[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)[39m
[90m    at Module.load (internal/modules/cjs/loader.js:986:32)[39m
[90m    at Function.Module._load (internal/modules/cjs/loader.js:879:14)[39m
[90m    at Module.require (internal/modules/cjs/loader.js:1026:19)[39m
[90m    at require (internal/modules/cjs/helpers.js:72:18)[39m
    at Object.<anonymous> (C:\bot1\index.js:11:18)
[90m    at Module._compile (internal/modules/cjs/loader.js:1138:30)[39m
[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)[39m
const Discord = require('discord.js');
const Client = new Discord.Client();

const client = new Discord.Client();
client.commands = new Discord.Collection();

const member = guild.member.first(message.author);
const { Permissions } = require('discord.js');

const permissions = new Permissions([
    'MANAGE_MESSAGES',
]);

module.exports = {
    name: 'prune',
    description: 'prune up to 99 messages.',
    execute(message, args) {
        const amount = parseInt(args[0]) + 1

        if (member.hasPermission('MANAGE_MESSAGES')) 
        {

            if (isNaN(amount)) {
                return message.channel.send('That\'s not a valid number');
            } else if (amount <= 1 || amount > 100) {
                return message.channel.send('You need to input a number between 1 and 99.');
            }

            message.channel.bulkDelete(amount, true).catch(err => {
            console.error(err);
            message.channel.send('There was an error trying to prune messages in this channel.');
        })

        if (!member.hasPermission('MANAGE_MESSAGES'))
        {
            message.channel.send("You dont have the required permissions to execute this command")
        }

        };
    }
};

Answer №1

To access the GuildMember object from message, it is necessary to define member within the execute() function.

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

const client = new Discord.Client();
client.commands = new Discord.Collection();

const { Permissions } = require('discord.js');

const permissions = new Permissions([
    'MANAGE_MESSAGES',
]);

module.exports = {
    name: 'prune',
    description: 'prune up to 99 messages.',
    execute(message, args) {
        const member = message.member;
        const amount = parseInt(args[0]) + 1
    
        if (member.hasPermission('MANAGE_MESSAGES')) 
        {

            if (isNaN(amount)) {
                return message.channel.send('That\'s not a valid number');
            } else if (amount <= 1 || amount > 100) {
                return message.channel.send('You need to input a number between 1 and 99.');
            }

            message.channel.bulkDelete(amount, true).catch(err => {
            console.error(err);
            message.channel.send('There was an error trying to prune messages in this channel.');
        })

        if (!member.hasPermission('MANAGE_MESSAGES'))
        {
            message.channel.send("You dont have the required permissions to execute this command")
        }

        };
    }
};

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

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...

Shade within the autocomplete

Is there a way to make the color property warning work on my autocomplete element at all times, rather than just on focus? Any suggestions or workarounds? Check out this code sandbox for reference. I really want the warning color to be visible constantly ...

What is the best way to trigger UseEffect when new data is received in a material table?

I was facing an issue with calling a function in the material table (https://github.com/mbrn/material-table) when new data is received. I attempted to solve it using the following code. useEffect(() => { console.log(ref.current.state.data); ...

I encounter an issue when attempting to fetch data from multiple tables

I'm facing an issue with my query const a = await prisma.$queryRaw` SELECT r.name as name, r.profileId as profile, o.lastName as lastName FROM UserSetting r , User o WHERE r.userId=o.id ` After running the query, I am getting an error message stating ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

What is the best way to locate the final text node within the <p> element?

Looking at the code below, my goal is to identify and retrieve the text node that serves as the last child element. <p class="western" style="margin-bottom: 0.14in"> <font color="#000000"> <font face="Arial, serif"> <font ...

Fixed position not being maintained after clicking the button

Looking for some help with a fixed header issue on my website. The header is supposed to stay at the top while scrolling, which works well. However, when I switch to responsive view, click the menu button, and then go back to desktop view, none of the po ...

Encountering 'Element not found' error when automating Flight Booking on MakeMyTrip.com using Selenium WebDriver, specifically while trying to select a flight after conducting a search

Currently in the process of automating the flight booking feature on MakeMyTrip.com using Selenium WebDriver. I have implemented separate classes for Page Object Model (POM) and TestNG. The code successfully automates the process up to the point of clicki ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...

Is there a way to retrieve a collection of files with a particular file extension by utilizing node.js?

The fs package in Node.js provides a variety of methods for listing directories: fs.readdir(path, [callback]) - This asynchronous method reads the contents of a directory. The callback function receives two arguments (err, files), with files being an arra ...

Pressing the 'Enter' key within a textarea in a JQuery

This question seems fairly straightforward. I have a text area where hitting "enter" submits the content. Even though I reset the text to "Say something..." after submission, the cursor continues to blink. Is there a way to require the user to click on ...

Create a debounced and chunked asynchronous queue system that utilizes streams

As someone who is new to the concept of reactive programming, I find myself wondering if there exists a more elegant approach for creating a debounced chunked async queue. But what exactly is a debounced chunked async queue? While the name might need some ...

Customizing ExtJS 4.1: Mastering field overrides

Seeking guidance on applying a plugin to all fields(numberfield, textfield, datefield, etc.) within the ExtJS 4.1 library. Does anyone have suggestions on how to achieve this? I understand that all fields are derived from BaseField. I attempted the follow ...

Determining the worth of radio buttons, dropdown menus, and checkboxes

I am working on designing a menu for a pizza place as part of a learning project. The menu allows users to select their pizza size from small, medium, and large using radio buttons, and then customize it further with three select boxes where each selection ...

Having trouble with serving static assets in nested routes?

I am facing an issue with my express app where the static assets are not serving on the specified 'something/something' path. /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path. ...

The method of pausing a function until the result of another function is returned

There is a function named 'updateProfile()' that includes a condition, which checks for the value of variable 'emailChangeConfirm' obtained from another function called 'updateEmailAllProcessing()'. The issue lies in the fact ...

Arranging objects in an array based on a separate array of strings

Here is an array of objects that I need to rearrange: var items = [ { key: 'address', value: '1234 Boxwood Lane' }, { key: 'nameAndTitle', value: 'Jane Doe, Manager' }, { key: 'contactEmail', value: ...

Ways to discover the titles of every sub-directory

Suppose I have the absolute path of a directory. Is there a method in JavaScript (Node.js) to determine how many sub-directories it has, and retrieve the names of all its sub-directories? I searched online but didn't come across any solution. ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Can anyone help me troubleshoot my node.js stream code?

I currently have a m4a audio file stored on my server, but I am encountering issues when trying to play it on both my phone and PC after downloading it using the provided code. I suspect that the file may not have been transferred correctly. Can anyone of ...