1

I am using the discord.py to interact with discord.

def hi():
    await client.send_message(channel, message)

gets a syntax error, unless I write "async" when I the hi() function. I really don't understand this, pls help!

1 Answer 1

2

You can schedule a coroutine in an event loop. You can not call them or await them from inside a non coroutine.

Let's check the following code:

import asyncio


async def greetLater(name, delay):
    await asyncio.sleep(delay)
    print("Hello {}!".format(name))


def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(greetLater("masnun", 10))


if __name__ == '__main__':
    main()

In the above code, greetLater is a coroutine. We can't directly call it from the main function. What we need to do here is to create an event loop and then schedule the coroutine there. We use the asyncio module to help us create the event loop and run the coroutine.

Further references:

(Disclaimer: Links to my personal blog posts on the topic, you can google for more references)

Sign up to request clarification or add additional context in comments.

2 Comments

Is passing the loop into the function where it can then be closed okay? What I am making might be used by other people and I think you are more experienced than me.
I didn't fully understand the scenario but passing the loop in general is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.