Discord JS机器人语音频道成员计数不更新问题求助
Discord机器人语音频道成员实时计数问题解决方法
问题核心原因
你的机器人无法实时更新语音频道成员数,根本原因是缺少语音状态相关的网关意图——Discord客户端没有权限接收语音频道成员变化的事件,导致缓存中的成员数据始终停留在机器人启动时的状态,重启才会重新拉取。
解决方案
1. 添加必要的网关意图
初始化Discord客户端时,必须补充GatewayIntentBits.GuildVoiceStates意图,这样客户端才能接收语音状态变更事件,自动更新缓存:
const { Client, GatewayIntentBits } = require('discord.js'); // 补充语音状态监听意图 const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates // 新增该意图 ] });
2. 替换轮询为事件监听(更高效的实现)
每秒轮询不是最优方案,直接监听voiceStateUpdate事件可以在成员加入/离开时立即触发逻辑,既高效又能精准推送提醒:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates ] }); const TARGET_CHANNEL_ID = '你的目标语音频道ID'; const YOUR_USER_ID = '你的Discord用户ID'; // 接收提醒的目标用户ID client.once('ready', () => { console.log(`Bot已登录:${client.user.tag}!`); }); // 监听语音状态变更事件 client.on('voiceStateUpdate', (oldState, newState) => { // 判断成员是否加入目标语音频道 if (!oldState.channel && newState.channel?.id === TARGET_CHANNEL_ID) { // 给你发送私信提醒 client.users.fetch(YOUR_USER_ID) .then(user => user.send(`提醒:${newState.member.user.tag} 加入了语音频道!`)) .catch(err => console.error('发送提醒失败:', err)); console.log(`当前频道成员数:${newState.channel.members.size}`); } // 可选:成员离开时的计数更新 if (oldState.channel?.id === TARGET_CHANNEL_ID && !newState.channel) { console.log(`当前频道成员数:${oldState.channel.members.size - 1}`); } }); client.login('你的机器人TOKEN');
3. 若坚持保留轮询逻辑的修改版本
添加GuildVoiceStates意图后,缓存会自动更新,轮询即可获取实时数据:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates ] }); client.once('ready', () => { console.log(`Bot已登录:${client.user.tag}!`); setInterval(() => { const voiceChannel = client.channels.cache.get('你的目标语音频道ID'); if (!voiceChannel) { console.log('无法找到目标语音频道'); return; } const memberCount = voiceChannel.members.size; console.log(`当前频道成员数:${memberCount}`); if (memberCount > 0) { console.log('频道内有人'); // 此处可添加给你发送提醒的逻辑 } else { console.log('频道内没人'); } }, 1000); }); client.login('你的机器人TOKEN');
关键说明
GuildVoiceStates意图是获取实时语音状态的核心,必须添加,否则Discord不会推送语音频道的成员变更事件。- 事件监听比轮询更高效,避免不必要的重复查询,还能第一时间触发提醒。
内容的提问来源于stack exchange,提问作者user3082438
相关产品推荐
相关产品推荐

