Discord.py执行join命令报错:'NoneType'对象无connect属性如何解决?
问题原因
- 核心报错原因:当机器人从未加入过当前服务器的任意语音频道时,
ctx.voice_client默认值为None,你的代码仅处理了ctx.voice_client不为空的场景,直接对None调用connect()方法触发了属性错误。 - 附加兼容问题:discord.py v1.5+ 版本中,用户所在语音频道的属性为
ctx.author.voice.channel,而非你代码中写的ctx.author.voice_channel,如果修改核心逻辑后仍有报错可优先核对该属性名。 - 隐藏问题:你原有逻辑中先断开再连接的操作会导致不必要的重连开销,逻辑合理性不足。
修复方案
直接替换你的join命令代码为以下版本即可:
@commands.command() async def join(self, ctx): # 校验用户是否加入语音频道 if ctx.author.voice is None: return await ctx.send("You are not connected to a voice channel") target_channel = ctx.author.voice.channel # 若你当前版本确实用voice_channel可改回 # 处理机器人语音连接状态 if ctx.voice_client is None: # 机器人未加入频道时直接连接目标频道 await target_channel.connect() else: # 机器人已在其他频道时直接移动,无需断开重连 await ctx.voice_client.move_to(target_channel) await ctx.send(f"Connected to {target_channel}")
额外校验项
如果修改后仍有异常,检查bot初始化时是否开启了语音相关权限:
import discord from discord.ext import commands # 开启voice_states intent intents = discord.Intents.default() intents.voice_states = True bot = commands.Bot(command_prefix="你的命令前缀", intents=intents)
内容的提问来源于stack exchange,提问作者dogluva
相关产品推荐
相关产品推荐

