Home > Enterprise >  Discord.js guildCreate and guildDelete events are not fired
Discord.js guildCreate and guildDelete events are not fired

Time:06-02

What is my problem? Sometimes I don't get guildCreate and guildDelete events.

Does the problem occur every time? No. About 40% of the time it works without a problem.

Do I get an error message? No. No error message is fired.

My code:

const DiscordServer = require('./backend-lib/models/DiscordServer');

const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD ] });

client.once('ready', () => {
  console.log('ready');
});

/* It's listening to the event `guildCreate` and then it's creating a new document in the database. */
client.once('guildCreate', async (guild) => {
  console.log('create');
});

/* It's listening to the event `guildDelete` and then it's deleting the document in the database. */
client.once('guildDelete', async (guild) => {
  console.log('delete', guild.id);
});

/* It's connecting to SQS and listening to it. */
client.once('ready', async () => {
   require('./services/helper');
});

client.login(conf.discord.token)

CodePudding user response:

It seems you're using the correct intents. However, you're using client.once, that adds a one-time listener for your guildCreate and guildDelete events. The first time the event is triggered, the listener is removed and the callback function is fired. As the listener gets removed, the callback won't run again unless you restart your bot.

If you want to trigger these events more than once, you can use the .on() method:

client.on('guildCreate', async (guild) => {
  console.log('create');
});

client.on('guildDelete', async (guild) => {
  console.log('delete', guild.id);
});
  • Related