Discord.js 未触发 guildCreate 和 guildDelete 事件

Discord.js guildCreate and guildDelete events are not fired

我的问题是什么? 有时我没有收到 guildCreateguildDelete 事件。

是不是每次都会出现这个问题? 没有。大约 40% 的时间它可以正常工作。

我会收到错误消息吗?不会。不会触发任何错误消息。

我的代码:

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)

看来您使用的意图是正确的。但是,您正在使用 client.once,它会为您的 guildCreateguildDelete 事件添加一个 one-time 侦听器。第一次触发事件时,将移除侦听器并触发回调函数。随着侦听器被移除,回调将不会再次 运行,除非您重新启动您的机器人。

如果想多次触发这些事件,可以使用.on()方法:

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

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