discord.Interaction中替代ctx.voice_client的方法及报错修复
解决Discord机器人退出语音频道的AttributeError问题
问题原因
你用的是Slash命令(@bot.tree.command),但错误地将参数类型声明为commands.Context——Slash命令的回调参数实际是discord.Interaction对象,它本身没有voice_client属性,也不存在ctx.client这种用法,这是报错的核心原因。
修正后的代码
import discord import wavelink from discord import app_commands @bot.tree.command(name="disconnect", description="Disconnect from a vc", guild=guild) async def disconnect(interaction: discord.Interaction): # 检查机器人是否在语音频道 bot_vc = interaction.guild.voice_client if not bot_vc: return await interaction.response.send_message("我不在语音频道里") # 检查用户是否在语音频道 user_vc = interaction.user.voice if not user_vc or not user_vc.channel: return await interaction.response.send_message("你不在语音频道里") # 获取Wavelink播放器实例 vc: wavelink.Player = bot_vc await vc.disconnect() vc.queue.clear() await interaction.response.send_message("Bye-bye")
关键修正点
- 参数类型替换:将
ctx: commands.Context改为interaction: discord.Interaction,匹配Slash命令的回调参数类型 - 获取机器人语音客户端:通过
interaction.guild.voice_client获取机器人当前所在的语音客户端,替代错误的ctx.client - 用户语音状态检查:补充判断
user_vc.channel,避免用户存在语音状态但未在频道的异常情况 - 响应方式调整:Slash命令必须用
interaction.response.send_message来回复,原代码的ctx.send在Interaction对象中也会报错(你之前没触发到这一步)
内容的提问来源于stack exchange,提问作者MrPepe
相关产品推荐
相关产品推荐

