【问题标题】:Discord.js - Events Handler : Why is my module not executing the code?Discord.js - 事件处理程序:为什么我的模块不执行代码?
【发布时间】:2022-12-19 00:18:27
【问题描述】:

我正在尝试为我的个人服务器编写一个 Discord 机器人。我正在使用 Discord.js 并且我一直在关注 discord.js 指南。

我现在有一个事件处理程序,但是当我为另一个事件添加一个文件时,这个模块的代码没有执行。我试图触发的事件是新成员加入我的服务器。

我有 2 个重要文件:index.js 运行我的代码的主体和 guildMemberAdd.js 这是我的事件模块,当新成员加入服务器时。

index.js:

// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    const event = require(filePath);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    } else {
        client.on(event.name, (...args) => event.execute(...args));
    }
}

// Log in to Discord with your client's token
client.login(token);

guildMemberAdd.js:

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

module.exports = {
    name: Events.GuildMemberAdd,
    async execute(member) {
        console.log(member);
    },
};

【问题讨论】:

    标签: javascript node.js module discord.js event-handling


    【解决方案1】:

    如果您只启用了 GatewayIntentBits.Guilds 意图,则不会触发 GuildMemberAdd 事件。您还需要添加 GatewayIntentBits.GuildMembers(可能还有 GatewayIntentBits.GuildPresences):

    const { Client, GatewayIntentBits } = require('discord.js');
    
    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildPresences,
      ],
    });
    

    在 discord.js v13 中,它应该是:

    const { Client, Intents } = require('discord.js');
    
    const client = new Client({
      intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MEMBERS,
        Intents.FLAGS.GUILD_PRESENCES,
      ],
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2015-08-29
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多