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

老子叫甜甜 提交于 2021-01-28 05:10:08

问题


I'm coding a music bot for my server, and I need to disconnect (a coroutine) when the queue is exhausted. So I use a try: except block to handle that, however, when using VoiceClient.play, is it possible to put an asynchronous function as the after parameter? Just using after=function does not work and would raise function was not awaited, but using after=await function shows

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

Is there any way to call an async function from play? How would I disconnect if I cannot call the coroutine?

My code:

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)

What I'm trying to do:

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)

回答1:


You can define a callback function that will schedule a coroutine to run on your event loop, wrap it into a partial and pass that to the play method instead.

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


来源:https://stackoverflow.com/questions/64758815/is-it-possible-to-put-an-async-function-as-a-callable-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!