1

So I am making this music discord bot on discord.py. This bot just plays a playlist from local mp3 files on my computer. So I have a function that plays the queue and it goes like this:

def play_song(ctx, voice):
    if len(queue) == 0:
        print('All the songs have been played')
        create_queue()
        return

    song_ = queue[0][len('songs/'):-16]
    voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: play_song(ctx, voice))
    print(f'Now playing {song_}')
    del queue[0]

And I want to convert this function to an async function because I want to be able to send messages and do other things in discord.py inside this function. The problem I'm facing is a result of this line:

voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: play_song(ctx, voice))

If I make this function an async function than I'll have to put an await statement, and If I do that it will be like this:

voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: await play_song(ctx, voice))

The problem with that is that it's giving me the error: "await outside of async function" So I also tried using asyncio.run(), and then after the first song it's giving me a huge scroll of errors, What do I do next?

Omer
  • 56
  • 5

2 Answers2

1

Try using async def play_song(ctx, voice): at the top. You can't await inside a non-async function.

Seth
  • 2,214
  • 1
  • 7
  • 21
  • The `await outside async function` error happens when the function is async, if it wasn't I wouldn't need the await, I think it is because the function `after` is non-async – Omer Dec 17 '20 at 14:19
  • The `await` is inside your lambda function which is not `async`. – herveRilos Dec 19 '20 at 10:01
1

I have found an answer to my own question. The answer is to use asyncio.Event() I did it like this:

async def play_song(ctx, voice):
    global stop_playing, pos_in_q, time_from_song
    event = asyncio.Event()
    event.set()
    while True:
        await event.wait()
        event.clear()
        if len(queue) == pos_in_q - 1:
            await ctx.send('Party is over! use the `.arse-play` to play again.')
            print('Party is over!')
            create_queue()
            break
        if stop_playing is True:
            stop_playing = False
            break

        song_ = queue[pos_in_q][len('songs/'):]
        voice.play(discord.FFmpegPCMAudio(queue[pos_in_q]), after=lambda e: event.set())
        print(f'Now playing {song_}')
        time_from_song = time.time()
        pos_in_q += 1
Omer
  • 56
  • 5