是否可以将异步函数作为可调用参数?

Is it possible to put an async function as a callable argument?

我正在为我的服务器编写一个音乐机器人,当队列用完时我需要断开连接(协程)。所以我使用 try:except 块来处理这个问题,但是,当使用 VoiceClient.play 时,是否可以将异步函数作为 after 参数? 仅使用 after=function 不起作用并且不会等待 raise 函数,但使用 after=await function 显示

TypeError: object function can't be used in 'await' expression

有什么方法可以从游戏中调用异步函数吗?调用不了协程怎么断线?

我的代码:

def playqueue(error):
    if error: print(error)
    # Next song
    try:
        vcc.play(discord.FFmpegOpusAudio(executable=r"ffmpeg.exe", source=queue[0]), after=playqueue)
    except IndexError:
        # How do I disconnect?

vcc.play(discord.FFmpegOpusAudio(executable=r"ffmpeg.exe", source=tfname), after=playqueue)

我想做什么:

async def playqueue(error):
    if error: print(error)
    # Next song
    try:
        vcc.play(discord.FFmpegOpusAudio(executable=r"ffmpeg.exe", source=queue[0]), after=playqueue #Somehow call the async function)
    except IndexError:
        await disconnect # I Have a disconnect function premade

vcc.play(discord.FFmpegOpusAudio(executable=r"ffmpeg.exe", source=tfname), after=playqueue #Somehow call the async function)

您可以定义一个回调函数,它将在您的事件循环中安排协程 运行,将其包装到 partial 中并将其传递给 play 方法。

from functools import partial

def _handle_error(loop, error):
    asyncio.run_coroutine_threadsafe(playqueue(error), loop) # playqueue should be an async function
    
vcc.play(discord.FFmpegOpusAudio(executable=r"ffmpeg.exe", source=tfname), after=partial(_handle_error, vcc.loop)) # vcc.loop is your event loop instance