'How to make discord bot disconnect from voice channel after playing?
I'm trying to get the discord bot to disconnect from the voice channel after it finishes playing, but I can't use "await" in a lambda expression.
I tried it:
voice_client.play(source=audio_source, after=lambda _: await voice_client.disconnect())
But the result is:
SyntaxError: 'await' outside async function
I tried it:
voice_client.play(source=audio_source, after=lambda _: voice_client.disconnect())
But the result is:
RuntimeWarning: coroutine 'VoiceClient.disconnect' was never awaited self.after(error)
I tried it:
voice_client.play(source=audio_source, after=voice_client.disconnect)
But the result is:
TypeError: disconnect() takes 1 positional argument but 2 were given
My solution:
voice_client.play(
source=audio_source,
after=lambda _: asyncio.run_coroutine_threadsafe(
coro=voice_client.disconnect(),
loop=voice_client.loop
).result()
)
Solution 1:[1]
RuntimeWarning: coroutine 'VoiceClient.disconnect' was never awaited self.after(error)
VoiceClient need to add await in front of it. This function is a coroutine.
voice_client.play(source=audio_source, after=lambda _: await voice_client.disconnect())
After that you will meet this error
SyntaxError: 'await' outside async function
You cant use await outside async function
async def func(): #must add async here
await func2()
Try to add async at the function of your music command.
@bot.commands() #i dont know what type of command you are using, it also can be cogs or slash command
async def yourcommand(args): #add `async` in front `def`
#your code.....
voice_client.play(source=audio_source, after=lambda _: await voice_client.disconnect())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
