Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Await in a non async function?

I'm working on a discord bot and trying to solve this. I want to know how could I use await in non async function or if I can await a function in the lambda line the last line in the code.

I have tried doing asyncio.run with the player variable and I have tried asyncio.run_coroutine_threadsafe too and it didnt work.

Any ideas on how to make it work?

Code:

def queue_check(self, ctx):
    global queue_list
    global loop
    global playing


    if loop is True:
        queue_list.append(playing)
    elif loop is False:
        playing = ''

    if ctx.channel.last_message.content == '$skip' or '$s':
        return

    song = queue_list.pop(0)
    player = await YTDLSource.from_url(song, loop=self.client.loop, stream=True)

    
    ctx.voice_client.play(player, after= queue_check(self,ctx))





    @commands.command(aliases=['p'])
    @commands.guild_only()
    async def play(self, ctx, *, url):
        global queue_list
        global playing
            
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                return await ctx.send("> You are not connected to a voice channel.")



        async with ctx.typing():
                
            player = await YTDLSource.from_url(url, loop=self.client.loop, stream=True)
            await ctx.send(f'> :musical_note: Now playing: **{player.title}** ')
            
            playing = url


            await ctx.voice_client.play(player, after=lambda e: queue_check(self,ctx))
like image 587
Asforaa Avatar asked Jan 30 '26 22:01

Asforaa


1 Answers

Need to import asyncio

To actually run a coroutine, asyncio provides three main mechanisms:

  • The asyncio.run() function to run the top-level entry point “main()” function (see the above example.)
  • Awaiting on a coroutine. The following snippet of code will print “hello” after waiting for 1 second, and then print “world” after waiting for another 2 seconds:

Example

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

OutPut

started at 17:14:32
hello
world
finished at 17:14:34

Details here

like image 154
Cognisun Inc Avatar answered Feb 01 '26 11:02

Cognisun Inc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!