问题
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