Discord机器人ctx.author.voice.channel无返回值问题求助
问题描述
希望Discord机器人在用户未加入语音频道时发送提示消息,编写了如下play异步函数:
async def play(self, ctx, *args): query = " ".join(args) voice_channel = ctx.author.voice.channel print(voice_channel) if voice_channel is None: print('test') #you need to be connected so that the bot knows where to go # await message.channel.send(response) await ctx.send("Connect to a voice channel!") elif self.is_paused: print('poop') self.vc.resume() else: print('hello') song = self.search_yt(query) if type(song) == type(True): await ctx.send("Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.") else: await ctx.send("Song added to the queue") self.music_queue.append([song, voice_channel]) if self.is_playing == False: await self.play_music(ctx)
但当未加入语音频道时,ctx.author.voice.channel无返回值,执行print(voice_channel)后Linux终端无任何输出(连None都没有),求解决思路。
解决思路
- 核心问题定位:当用户未加入语音频道时,
ctx.author.voice本身就是None,此时直接访问.channel会触发AttributeError异常,代码会直接中断,根本走不到print(voice_channel)这一步,所以终端没有输出。 - 修正逻辑顺序:先判断用户是否有语音状态(
ctx.author.voice是否存在),再获取频道:async def play(self, ctx, *args): query = " ".join(args) voice_state = ctx.author.voice # 先检查语音状态是否存在 if voice_state is None: print('test') await ctx.send("Connect to a voice channel!") else: voice_channel = voice_state.channel print(voice_channel) if self.is_paused: print('poop') self.vc.resume() else: print('hello') song = self.search_yt(query) if type(song) == type(True): await ctx.send("Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.") else: await ctx.send("Song added to the queue") self.music_queue.append([song, voice_channel]) if self.is_playing == False: await self.play_music(ctx) - 添加调试异常捕获:可以在关键代码块外包裹
try-except,捕获并打印异常信息,方便排查其他潜在问题:async def play(self, ctx, *args): try: query = " ".join(args) voice_channel = ctx.author.voice.channel print(voice_channel) # 后续原有逻辑... except AttributeError as e: print(f"Error accessing voice channel: {e}") await ctx.send("Connect to a voice channel!") - 分步调试:先单独打印
ctx.author.voice的值,确认其是否为None,再逐步排查后续逻辑,确保每一步的变量状态符合预期。
内容的提问来源于stack exchange,提问作者buttermilk
相关产品推荐
相关产品推荐

