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

能否在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 00:33:01