能否在Python lambda函数中使用await?Discord机器人开发语法报错求助
问题解答
1. lambda中能否使用await?
不能。Python目前不支持异步lambda表达式,await关键字只能在async def声明的异步函数内部使用,在同步lambda里写await会直接触发语法错误。
2. 报错解决方案
discord.py中voice_client.play的after参数要求传入同步回调函数,该回调会在音频播放结束后在独立子线程触发。要调用异步的nextSong方法,你需要将异步协程提交到discord.py的主事件循环中调度执行,具体修改如下:
- 首先导入
asyncio标准库 - 替换play方法中的after回调逻辑,用
asyncio.run_coroutine_threadsafe调度异步任务
修改后的代码示例:
import asyncio # 其余原有代码保持不变 async def playSong(self, ctx, link, name): self.ctx = ctx ctx.voice_client.play(discord.FFmpegPCMAudio(link, **self.ffmpeg_options), # 替换原有lambda逻辑 after=lambda l: asyncio.run_coroutine_threadsafe(self.nextSong(), ctx.bot.loop) ) ctx.voice_client.source = discord.PCMVolumeTransformer(ctx.voice_client.source) ctx.voice_client.source.volume = 0.50 em = discord.Embed(title="Queue", description=("You are listening to " + name)) await ctx.send(embed=em)
补充说明
如果需要捕获nextSong运行时的异常,避免错误静默,可以单独写同步包装函数处理任务返回结果:
def after_callback(self, error): if error: print(f"播放出错: {error}") future = asyncio.run_coroutine_threadsafe(self.nextSong(), self.ctx.bot.loop) try: future.result() except Exception as e: print(f"切歌出错: {e}") # 调用play时直接传入该方法即可 after=self.after_callback
内容的提问来源于stack exchange,提问作者tonno7103
相关产品推荐
相关产品推荐

