如何通过斜杠命令让Discord机器人退出语音频道?
解决Discord机器人退出语音频道的AttributeError问题
你遇到的错误是因为**VoiceChannel对象并没有disconnect()方法**,这个方法属于机器人连接到语音频道后得到的VoiceClient实例。下面是正确的实现方式:
正确的退出语音频道命令
@Client.tree.command(name="leave", description="Leave VC") async def leave(interaction: discord.Interaction): # 获取当前服务器中机器人的语音客户端实例 voice_client = interaction.guild.voice_client # 先检查机器人是否已连接到语音频道 if voice_client and voice_client.is_connected(): await voice_client.disconnect() await interaction.response.send_message("已退出语音频道") else: await interaction.response.send_message("我当前不在任何语音频道里!")
错误原因说明
你之前调用的await channel.disconnect()是错误的逻辑:
channel.connect()方法会返回一个VoiceClient对象,这个对象才是机器人和语音频道的连接实例- 断开连接需要调用这个
VoiceClient实例的disconnect()方法,而不是原VoiceChannel对象的方法
如果是在join命令中需要后续断开,你可以保存连接后的VoiceClient:
@Client.tree.command(name="join", description="Join Vc") async def join(interaction: discord.Interaction): channel = interaction.user.voice.channel await interaction.response.send_message("Joining...") # 保存连接后的语音客户端实例 voice_client = await channel.connect() # 后续若要断开,调用 await voice_client.disconnect()
内容的提问来源于stack exchange,提问作者Callmemartin_
相关产品推荐
相关产品推荐

