是否可以将异步函数作为可调用参数? [英] Is it possible to put an async function as a callable argument?
问题描述
我正在为服务器编写音乐bot,并且在队列耗尽时需要断开连接(协程).因此,我尝试使用try:except块来处理该问题,但是,当使用 VoiceClient.play
时,是否可以将异步函数作为 after
参数放置?仅使用 after = function
不起作用,并且未等待提升函数,但是使用 after = await函数
显示
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:'await'表达式中不能使用对象函数
有什么方法可以从播放中调用异步功能吗?如果我不能给协程打电话,我该如何断开连接?
Is there any way to call an async function from play? How would I disconnect if I cannot call the coroutine?
我的代码:
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
方法.
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
这篇关于是否可以将异步函数作为可调用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!