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

如何在Discord.py中获取命令用户的语音频道ID?

获取Discord命令用户的语音频道ID

要获取使用命令的用户所在的语音频道ID,可直接通过interaction.user.voice属性访问用户的语音状态,再从中提取频道信息。

关键说明:

  • interaction.user.voice返回一个VoiceState对象,若用户未加入任何语音频道,该值为None,需先判断避免报错。
  • 从VoiceState的channel属性拿到语音频道对象后,通过.id即可获取频道ID。

修改后的完整代码:

@tree.command(guild=discord.Object(id=secrets.get('discordsv')), name='randomteam', description='We randomly assign people in the current call room.')
async def randomTeamSet(interaction: discord.Interaction, count: int):
    if count <= 1:
        await interaction.response.send_message(f"The number of teams is 2 or more.", ephemeral=True)
    else:
        # 获取命令用户的语音频道
        voice_state = interaction.user.voice
        if voice_state and voice_state.channel:
            voice_channel_id = voice_state.channel.id
            print(f"player voice channel is {voice_channel_id}")
            # 后续可添加处理频道成员的逻辑(比如随机组队)
        else:
            await interaction.response.send_message("你当前没有加入任何语音频道,请先进入语音频道再使用该命令。", ephemeral=True)

补充提示:

  • 必须处理用户未在语音频道的场景,否则直接访问voice_state.channel会触发AttributeError。
  • 若要实现随机组队功能,可通过voice_state.channel.members获取当前频道的所有成员列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:06:42