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

Discord JS技术求助:如何实现Bot跟随指定用户进入语音频道?

解决Discord Bot自动跟进指定用户语音频道的问题

1. 修复voiceStateUpdate事件不触发的问题

Discord.js v14及后续版本必须明确启用网关意图(Intents)才能接收语音状态更新事件。初始化客户端时,必须添加Guilds和GuildVoiceStates两个核心意图:

const { Client, GatewayIntentBits } = require('discord.js');

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

同时要在Discord开发者门户的Bot设置中,开启"Privileged Gateway Intents"下的"Voice States Intent"(若需获取成员详情,还需开启"Server Members Intent")。

2. 实现指定用户语音频道跟进逻辑

修改voiceStateUpdate监听代码,加入目标用户判断,并实现Bot自动加入频道的功能:

// 替换为你要跟踪的用户ID
const TARGET_USER_ID = '你的目标用户ID';

client.on('voiceStateUpdate', async (oldState, newState) => {
  // 过滤非目标用户的操作
  if (newState.member.id !== TARGET_USER_ID) return;

  // 用户加入/切换到新语音频道时,Bot跟进
  if (newState.channel && (!oldState.channel || oldState.channel.id !== newState.channel.id)) {
    try {
      await newState.channel.join();
      console.log(`已跟进目标用户加入频道: ${newState.channel.name}`);
    } catch (err) {
      console.error('加入频道失败:', err);
    }
  } 
  // 可选:用户离开语音频道时,Bot自动退出
  else if (!newState.channel && oldState.channel) {
    await oldState.channel.leave();
    console.log('目标用户离开频道,已退出');
  }
});

3. 解决Guild Member获取失败的问题

获取成员失败通常是意图未开启或缓存缺失导致,可通过以下方式处理:

  • 确保客户端初始化时添加GatewayIntentBits.GuildMembers意图,且开发者门户已开启对应特权意图
  • 缓存中无成员时,用fetch()主动获取:
async function getTargetMember(guildId) {
  const guild = client.guilds.cache.get(guildId);
  if (!guild) return null;

  // 优先从缓存取,缓存无则主动拉取
  let member = guild.members.cache.get(TARGET_USER_ID);
  if (!member) {
    try {
      member = await guild.members.fetch(TARGET_USER_ID);
    } catch (err) {
      console.error('获取成员失败:', err);
      return null;
    }
  }
  return member;
}

4. 权限检查

确保Bot拥有以下服务器权限:

  • Connect:允许加入语音频道
  • View Channel:能查看目标语音频道
  • Speak(可选):若Bot需要发声

邀请Bot时需包含上述权限。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:25:01