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

DiscordJS v14:如何检测机器人是否已连接语音频道?

解决Discord.js机器人语音状态缓存不更新的问题

问题原因

直接调用interaction.member.guild.voiceStates.cache.get('BOT_ID')依赖本地缓存,而Discord.js的缓存不会自动实时同步所有语音状态变更(比如机器人被手动移动频道、断开连接这类非代码触发的操作),导致你拿到的始终是旧数据。

解决方案1:主动拉取最新语音状态

放弃直接依赖缓存,改用fetch()方法从Discord API获取实时语音状态,确保每次检查都是最新数据:

// 用fetch获取最新状态,请求失败则返回null
const botVoiceChannel = await interaction.member.guild.voiceStates.fetch('BOT_ID').catch(() => null);

if (botVoiceChannel) {
  const errEmbed = new EmbedBuilder()
    .setDescription("我已经连接到一个语音频道了")
  return interaction.reply({ embeds: [errEmbed] });
}

解决方案2:监听语音状态更新事件

如果需要持续跟踪机器人的语音状态,可以在客户端初始化时监听voiceStateUpdate事件,实时更新本地存储的状态:

// 全局变量存储机器人当前语音频道
let botCurrentVoiceChannel = null;

// 监听语音状态变更事件
client.on('voiceStateUpdate', (oldState, newState) => {
  // 判断是否是机器人自身的状态变化
  if (newState.member.id === 'BOT_ID') {
    botCurrentVoiceChannel = newState.channel;
  }
});

// 后续检查时直接使用全局变量
if (botCurrentVoiceChannel) {
  const errEmbed = new EmbedBuilder()
    .setDescription("我已经连接到一个语音频道了")
  return interaction.reply({ embeds: [errEmbed] });
}

注意事项

  • 使用fetch()时要加await,确保异步操作完成后再判断状态。
  • 监听事件的方式适合需要实时响应状态变化的场景,主动fetch更适合单次检查的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:25:02