如何在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
相关产品推荐
相关产品推荐

