Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
How do I pass the guild variable to an event file in discord.js?

I am using the guide in discordjs.guide to have separate event listener files, and was trying to add another one. Specifically, the guildCreate event. In the index.js file, I have this:

const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const event = require(`./events/${file}`);
    if (event.once) {
        client.once(event.name, (message, guild, ...args) => event.execute(message, guild, ...args));
    } else {
        client.on(event.name, (message, guild, ...args) => event.execute(message, guild, ...args));
    }
}

And on the event side, I have this:

const Discord = require('discord.js');
const prefix = require('../config.json')

module.exports = {
    name: 'guildCreate',
    once: true,
    async execute(client, guild) {
        console.log(guild)
        const introembed = new Discord.MessageEmbed()
        .setTitle('Hiya!')
        .setColor('RANDOM')
        .setDescription(`Long description here`)
        const owner = await guild.fetchOwner();
        owner.send({ embeds: [introembed]}).catch(console.error())
        console.info(`I just joined a new server! I am now a member of ${guild.name}`)
    },
};

When the guildCreate event is emitted, I get the error: TypeError: Cannot read properties of undefined (reading 'fetchOwner') because of await guild.fetchOwner();. I have tried passing the variable from the index side: client.on(event.name, (message, guild, ...args) => event.execute(message, guild, ...args));, as you can see, I added the guild variable to be passed, and on the event file side: async execute(client, guild) { I added the guild variable to be executed with. Even with adding the variables in those places, I still get the error saying guild is undefined. Any idea what is wrong? Any help is appreciated.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Note: This is optimized for Discord.js v13.3.0


Passing in Empty Variables

As pointed out by @Elitezen, passing in message and guild have no value as they are never defined in your code anywhere. This can lead to Errors being thrown due to undefined variables (Unless you have error handlers in your code elsewhere). As stated in the guide, the ...args argument will pass in any arguments received from the event. This is how something like that would work:

  • An event is received (Let's use guildCreate)
  • The process searches your files
discord-bot/
├── node_modules
├── config.json
├── index.js
├── package-lock.json
├── package.json
└── events
    └ guildCreate.js
  • Once it finds a match, it executes the code. In the documentation, it is noted that only a guild is sent when the event is fired. This means that ...args will only contain one argument, which is a Guild. Arguments from events do not have names, the ones in the documentation are recommended.

The issue with your code is that you have sent an empty variable called guild to the execution file.

async execute(client, guild) {

The code looks at this line and uses the empty variable you sent called guild. This is why you're receiving a TypeError.

Single Argument Events

To fix this, all you need to do is remove the two arguments client and guild from your index.js file and remove the client from your guildCreate.js file. The result will look something like this:

// index.js
if (event.once) {
 client.once(event.name, (...args) => event.execute(...args));
} else {
 client.on(event.name, (...args) => event.execute(...args));
}

// guildCreate.js
async execute(guild) {

Multiple Argument Events

Sometimes, you'll receive events that have multiple arguments, such as messageReactionAdd. That event will give you two (Unnamed) arguments in this order: a MessageReaction and a User. This is how that'd look:

// index.js
if (event.once) {
 client.once(event.name, (...args) => event.execute(...args));
} else {
 client.on(event.name, (...args) => event.execute(...args));
}

// messageReactionAdd.js
async execute(messageReaction, user) {

Take note that I haven't defined any arguments in index.js and only defined them in messageReactionAdd.js.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!