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

Nextcord音乐Bot首次+play正常,二次执行报'voice_channel'属性缺失错

解决Nextcord音乐Bot第二次执行+play指令时的AttributeError问题

问题定位

你遇到的错误AttributeError: 'Member' object has no attribute 'voice_channel',根源在play命令的分支判断里:

  • 首次执行时,ctx.voice_client不存在,走第一个分支,使用ctx.author.voice.channel是正确的,所以Bot能正常工作;
  • 第二次执行时,ctx.voice_client已存在,进入elif分支,这里错误使用了旧版discord.py的属性名voice_channel,而Nextcord中Member对象的语音频道属性是voice.channel,因此触发属性错误。

另外原逻辑还有漏洞:如果用户未加入语音频道,直接访问ctx.author.voice.channel会抛出额外的属性错误,需要先判断用户的语音状态是否存在。

修复方案

修改play命令的逻辑,调整判断顺序并修正属性调用:

@client.command()
async def play(ctx: commands.Context, *, search: wavelink.YouTubeTrack):
    # 优先检查用户是否在语音频道
    if not ctx.author.voice or not ctx.author.voice.channel:
        return await ctx.send("你不在任何语音频道里,请先加入一个语音频道!")
    
    # 处理Bot的语音连接状态
    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    else:
        vc: wavelink.Player = ctx.voice_client

    await vc.play(search)

修改说明

  1. 修正属性名:将错误的voice_channel替换为Nextcord规范的voice.channel,并增加ctx.author.voice的判断,避免用户无语音状态时的属性错误;
  2. 调整逻辑顺序:先检查用户的语音状态,再处理Bot的连接情况,逻辑更严谨,减少分支混乱;
  3. 简化分支:去掉冗余的elif判断,让代码更易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:20:28