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

Discord机器人无法加入语音频道:AttributeError报错求助

问题排查与解决

错误原因

你代码的核心问题是:当机器人还未加入任何语音频道时,ctx.voice_client返回值为None,此时调用它的connect()方法必然触发AttributeError。你错误地将ctx.voice_client当作用户所在的语音频道对象,但实际上它是机器人当前的语音客户端实例(仅当机器人已连接语音频道时才存在)。

修正后的代码

@client.command(pass_context=True)
async def join(ctx):
    user_voice = ctx.author.voice
    if user_voice:
        channel = user_voice.channel
        # 避免机器人重复连接或跨频道重复连接
        if ctx.voice_client is not None:
            await ctx.voice_client.move_to(channel)
        else:
            voice = await channel.connect()
        # 播放指定音频
        source = FFmpegPCMAudio('test.wav')
        voice.play(source)
    else:
        await ctx.send("Error: You are not in a voice channel.")

关键修改说明

  • 替换ctx.voice_client为ctx.author.voice.channel:直接获取用户当前所在的语音频道对象,这才是可调用connect()方法的正确对象。
  • 增加已连接状态判断:如果机器人已在其他语音频道,调用move_to()切换到用户所在频道;若未连接,则执行connect(),避免重复连接引发的错误。

额外注意事项

  • 确保test.wav文件路径正确,可与脚本放在同一目录,或使用绝对路径指定。
  • 若音频播放仍有问题,需确认FFmpeg已安装并添加到系统环境变量中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:44:53