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

如何查询已连接用户当前所在的语音频道名称

推荐方案:使用事件监听(无需轮询)

discord.py 原生提供语音状态变化事件,不需要通过定时轮询实现,延迟低、性能消耗小,是最优实现方式:

# 监听语音状态变化事件
@bot.event
async def on_voice_state_update(member, before, after):
    # 过滤机器人自身的状态变化
    if member.bot:
        return
    # 检测用户加入新语音频道
    if before.channel is None and after.channel is not None:
        # 直接获取加入的频道名称
        joined_channel_name = after.channel.name
        print(f"用户 {member.display_name} 加入语音频道:{joined_channel_name}")
        # 此处可添加自定义业务逻辑
    # 可选:检测用户离开语音频道
    elif after.channel is None and before.channel is not None:
        print(f"用户 {member.display_name} 离开语音频道:{before.channel.name}")
    # 可选:检测用户切换语音频道
    elif before.channel.id != after.channel.id:
        print(f"用户 {member.display_name} 从 {before.channel.name} 切换至 {after.channel.name}")

备选方案:修改现有轮询逻辑

如果你必须保留定时轮询的实现方式,需要新增状态对比逻辑,才能识别用户进出语音频道的变化:

# 全局变量存储上一轮的语音状态:格式为 {用户ID: 所在频道名称}
last_voice_state = {}

@tasks.loop(seconds=5)
async def join_party():
    global last_voice_state
    guild = bot.get_guild(config.guild_id)
    if not guild:
        return
    current_state = {}
    # 遍历所有语音频道的成员
    for voice_channel in guild.voice_channels:
        for member in voice_channel.members:
            if member.bot:
                continue
            current_state[member.id] = voice_channel.name
            # 识别新加入的用户
            if member.id not in last_voice_state:
                print(f"检测到用户 {member.display_name} 加入频道:{voice_channel.name}")
    # 识别离开的用户
    for member_id, old_channel in last_voice_state.items():
        if member_id not in current_state:
            member = guild.get_member(member_id)
            if member:
                print(f"检测到用户 {member.display_name} 离开频道:{old_channel}")
    # 更新状态缓存
    last_voice_state = current_state.copy()

# 轮询任务需要在机器人就绪后启动
@bot.event
async def on_ready():
    join_party.start()
    print(f"机器人已登录:{bot.user}")

注意事项

两种方案都需要提前完成两项配置:

  • 在 Discord 开发者后台的 Bot 管理页,开启 Server Members Intent 和 Voice States Intent 权限
  • 初始化机器人时传入对应权限配置:
import discord
intents = discord.Intents.default()
intents.members = True
intents.voice_states = True
# 如果使用commands扩展则替换为commands.Bot
bot = discord.Bot(intents=intents)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:27:03