You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用discord.js实现成员加入欢迎消息功能遇阻求助

Discord机器人GuildMemberAdd欢迎消息不生效问题排查与修复

问题描述

使用discord.js开发Discord机器人,已完成事件处理部分开发,编写了GuildMemberAdd事件代码(welcome.js),期望成员加入服务器时在指定频道发送欢迎消息,但该功能未生效。目前斜杠命令(user、ping、server)和ClientReady事件均可正常运行。

原代码片段

welcome.js

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

module.exports = {
    name: Events.GuildMemberAdd,
    once: true,
    execute(client, member) {
        const channelID = '1194723491551912079';
        const channel = client.channels.cache.get(channelID);
        const message = `Welcome <@${member}>!`;
        channel.send(message);
    },
};

index.js

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

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

client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

// command handling
for (const folder of commandFolders) {
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            client.commands.set(command.data.name, command);
        } else {
            console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    }
}

// event handling
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));
    }
}

client.login(token);

问题排查与修复步骤

1. 补充必要的网关意图

GuildMemberAdd事件触发需要机器人拥有GuildMembers意图,发送消息需要GuildMessages意图。如果机器人加入的服务器超过100个,还需在Discord开发者门户开启成员特权网关意图。

修改index.js中的客户端初始化代码:

const client = new Client({ 
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMembers, // 监听成员相关事件
        GatewayIntentBits.GuildMessages, // 允许发送服务器消息
        GatewayIntentBits.MessageContent // 可选:部分场景需处理消息内容时添加
    ] 
});

2. 修正事件触发模式

once: true会让事件仅执行一次,后续成员加入不再触发。删除该配置或改为once: false(默认值):

module.exports = {
    name: Events.GuildMemberAdd,
    // 删除once: true,或改为once: false
    execute(member) {
        // ... 逻辑代码
    },
};

3. 调整事件回调参数顺序

GuildMemberAdd事件的回调参数只有member,而非client, member。通过member.client可获取客户端实例,同时添加错误处理避免崩溃:

async execute(member) {
    const channelID = '1194723491551912079';
    // 使用fetch确保能获取到频道(即使不在缓存)
    const channel = await member.client.channels.fetch(channelID).catch(err => {
        console.log('获取频道失败:', err);
        return null;
    });
    if (!channel) return;
    
    const message = `Welcome <@${member.id}>!`; // 使用member.id确保正确@成员
    channel.send(message).catch(err => {
        console.log('发送欢迎消息失败:', err);
    });
},

4. 额外检查项

  • 确认机器人在指定频道拥有发送消息和查看频道的权限;
  • 确保频道ID输入正确,无拼写错误。

内容的提问来源于stack exchange,提问作者Akito The Duck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:13:17