Don't be Afraid of Async

Automate Mundane Tasks using Discord.py

https://slides.com/cheukting_ho/dont-be-afraid-of-async

What is Discord     ?

Think about Slack + Zoom

Discord API

Discord provide API for you to create bots, apps or event games (that you can sell).

The API can almost do everything on Dicord.

Check the documentation if you are interested: https://discord.com/developers/docs/intro 

The API can almost do everything on Dicord.

There was a big rewirte and I was using the v1.0

https://discordpy.readthedocs.io/en/latest/

Discord.py

Discord.py let you use the Discord API easily in Python

It uses Async (which was new to me)

 

code walkthrough

Let's continue our story...

📖
Once upon a time there are Generators

Sending to generator

 

The send() method resumes the generator and sends a value that will be used to continue with the next yield. The method returns the new value yielded by the generator.

- https://stackabuse.com/python-generators/

def numberGenerator(n):
     number = yield
     while number < n:
         number = yield number 
         number += 1

g = numberGenerator(10)    # Create our generator
next(g)                    # 
print(g.send(5))

Python 3.3 : yield from

def generator1():
    for item in generator2():
        yield item
def generator1():
    yield from generator2()

Python 3.3+ : yield from

def bottom():
    # Returning the yield lets the value
    # that goes up the call stack
    # to come right back down.
    return (yield 42)

def middle():
    return (yield from bottom())

def top():
    return (yield from middle())

# Get the generator.
gen = top()
value = next(gen)
print(value)  # Prints '42'.
try:
    value = gen.send(value * 2)
except StopIteration as exc:
    value = exc.value
print(value)  # Prints '84'.

Event Loop 🙆🏻‍♀️

and

Coroutine 🙋🏻‍♀️

Event Loop 🙆🏻‍♀️

 

An event loop is a loop that can register tasks to be executed, execute them, delay or even cancel them and handle different events related to these operations.

 

 

...like a

Task manager 👩🏻‍💼

Coroutine 🙋🏻‍♀️

 

Coroutines are computer program components that generalize subroutines for nonpreemptive multitasking, by allowing multiple entry points for suspending and resuming execution at certain locations

- wikipedia

 

...like a

YouTube video 🎬

Python 3.4: asyncio

import asyncio

# Borrowed from http://curio.readthedocs.org/en/latest/tutorial.html.
@asyncio.coroutine
def countdown(number, n):
    while n > 0:
        print('T-minus', n, '({})'.format(number))
        yield from asyncio.sleep(1)
        n -= 1

loop = asyncio.get_event_loop()
tasks = [
    asyncio.ensure_future(countdown("A", 2)),
    asyncio.ensure_future(countdown("B", 3))]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

Python 3.5: async await

async def py35_coro():
    await stuff()

Python 3.4: asyncio

@asyncio.coroutine
def py34_coro():
    yield from stuff()

Mixing sync code with async code

 

1. Can I call a sync function in an async function?

 

2. Can I have an async "for-loop"?

Calling sync function in async

 

Becareful if you mix them:

 

Warning!! Cannot await if it's not async function

 

https://stackoverflow.com/a/54685298

Async for-loop

 

For-loop: one after another...

How can it be Async?

 

Remember, async was from interator!

 

https://stackoverflow.com/a/48052347

Don't be Afraid of Async

By Cheuk Ting Ho

Don't be Afraid of Async

  • 1,634