Last active
December 31, 2017 02:17
-
-
Save AileenLumina/7112dce2851bf00fe42c50005f067d2f to your computer and use it in GitHub Desktop.
Pausable coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ... | |
def pausable(pause, resume_check=None, delay_start=None, delay_resume=None): | |
def inner_wrapper(coro): | |
@asyncio.coroutine | |
def replacement_coro(*args, **kwargs): | |
for x in coro(*args, **kwargs): | |
try: | |
if delay_start is not None: | |
if asyncio.iscoroutinefunction(delay_start): | |
yield from delay_start() | |
else: | |
raise TypeError("delay_start must be a coroutine function") | |
yield x | |
yield from pause() | |
# catch exceptions the regular discord.py user might not catch | |
except (OSError, | |
HTTPException, | |
GatewayNotFound, | |
ConnectionClosed, | |
aiohttp.ClientError, | |
asyncio.TimeoutError, | |
websockets.InvalidHandshake, | |
websockets.WebSocketProtocolError) as e: | |
if any(resume_check() if resume_check is not None else False or | |
# clean disconnect | |
(isinstance(e, ConnectionClosed) and | |
e.code == 1000) or | |
# connection issue | |
not isinstance(e, ConnectionClosed)): | |
if delay_resume is not None: | |
yield from delay_resume() | |
else: | |
raise | |
return replacement_coro | |
return inner_wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment