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

Node.js开发Discord欢迎机器人遇阻:成员进出消息无法触发求助

问题解决步骤

1. 修正Intents引用错误

Discord.js v14+ 已弃用旧的Intents.FLAGS写法,改用GatewayIntentBits枚举。你之前的代码已经导入了GatewayIntentBits,但参考的旧示例用了过时语法,才导致Intents未定义。初始化客户端时需添加正确的意图:

  • 必须包含GatewayIntentBits.Guilds(基础服务器权限)
  • 必须包含GatewayIntentBits.GuildMembers(监听成员加入/离开事件,需对应开发者门户已开启的SERVER MEMBERS INTENT)
  • GatewayIntentBits.GuildMessages(用于发送消息,按需保留)

2. 修正事件绑定位置

guildMemberAdd事件不能嵌套在ready事件回调内,需直接绑定到client实例上,否则监听器无法正确注册生效。

3. 添加成员离开事件实现

新增guildMemberRemove事件监听,完成离开提示消息的功能。

4. 优化频道获取逻辑

添加频道存在性判断,避免因频道ID错误或机器人权限不足导致的报错。


完整修正代码
// Require the necessary discord.js classes
const { Client, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

// 定义固定频道ID常量,便于后续维护
const WELCOME_CHANNEL_ID = '1010768161349587035';
const RANDOM_MSG_CHANNEL_ID = '1006941719666905089';

// 初始化客户端,添加所需意图
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages
  ]
});

// 成员加入事件监听
client.on('guildMemberAdd', async (guildMember) => {
  const welcomeChannel = guildMember.guild.channels.cache.get(WELCOME_CHANNEL_ID);
  if (!welcomeChannel) {
    console.error('欢迎频道未找到或机器人无访问权限');
    return;
  }
  await welcomeChannel.send(`**Welcome to the discord server, <@${guildMember.user.id}>!**`);
});

// 成员离开事件监听
client.on('guildMemberRemove', async (guildMember) => {
  const welcomeChannel = guildMember.guild.channels.cache.get(WELCOME_CHANNEL_ID);
  if (!welcomeChannel) {
    console.error('欢迎频道未找到或机器人无访问权限');
    return;
  }
  await welcomeChannel.send(`**<@${guildMember.user.id}> 已离开服务器**`);
});

// 随机消息功能
const randomMsg = ['message 1', 'message 2', 'message 3'];
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const sendRandomMsg = async () => {
  const targetChannel = client.channels.cache.get(RANDOM_MSG_CHANNEL_ID);
  if (!targetChannel) {
    console.error('随机消息频道未找到或机器人无访问权限');
    return;
  }
  await targetChannel.send(randomMsg[random(0, randomMsg.length - 1)]);
};

// 客户端就绪事件
client.once('ready', () => {
  console.log('(。··)_且 - 机器人已上线');
  // 启动随机消息定时器
  setInterval(sendRandomMsg, 1000 * 60);
});

// 登录Discord
client.login(token);

额外注意事项
  • 确认Discord开发者门户的Bot页面,已开启SERVER MEMBERS INTENT
  • 确保机器人在服务器中拥有发送消息、查看频道的权限
  • 测试时使用未加入过服务器的小号,避免Discord缓存导致事件不触发

内容的提问来源于stack exchange,提问作者TOKI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:27:27