Created
October 12, 2018 05:21
-
-
Save Sazpaimon/8f621179c6b07e97cb086c8e6bf6d567 to your computer and use it in GitHub Desktop.
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 disconnect(self): | |
self._aborted.set() | |
log.debug('(%s) Killing hooks handler', self.name) | |
try: | |
# XXX: queue.Queue.queue isn't actually documented, so this is probably not reliable in the long run. | |
with self._hooks_queue.mutex: | |
self._hooks_queue.queue[0] = None | |
except IndexError: | |
self._hooks_queue.put(None) | |
log.debug('(%s) Sending Discord logout', self.name) | |
call_result = concurrent.futures.Future() | |
def run_in_thread(): | |
# Create a new event loop to run the disconnect from | |
loop = asyncio.new_event_loop() | |
asyncio.set_event_loop(loop) | |
try: | |
# Close the WS client first and catch the error about it trying to use a different event loop. | |
# It already has closed the connection by then, so it's safe to cancel | |
try: | |
loop.run_until_complete(self.client.ws.close()) | |
except RuntimeError: | |
self.client.ws.worker_task.cancel() | |
# Send the logout command and store it's result into a completed Future | |
loop.run_until_complete(self.do_logout(call_result)) | |
finally: | |
loop.close() | |
# Create a new thread in order to create a new event loop | |
thread = threading.Thread(target=run_in_thread) | |
thread.start() | |
thread.join() | |
return call_result.result() | |
async def do_logout(self, call_result): | |
""" | |
Wraps the awaitable with something that puts the result into the | |
result/exception future. | |
""" | |
try: | |
result = await self.client.logout() | |
except Exception as e: | |
call_result.set_exception(e) | |
else: | |
call_result.set_result(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment