Last active
February 11, 2016 12:53
-
-
Save greut/f9e90822e34a1aeb8791 to your computer and use it in GitHub Desktop.
AsyncIO based bot for Slack
This file contains hidden or 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
# -*- encoding: utf-8 -*- | |
import json | |
import asyncio | |
import requests | |
import websockets | |
TOKEN="xoxb-..." | |
async def producer(): | |
await asyncio.sleep(5) | |
return json.dumps({"type": "ping"}) | |
async def consumer(message): | |
print(message) | |
async def bot(token): | |
# Authentication | |
response = request.post('https://slack.com/api/rtm.start', data=dict(token=TOKEN)) | |
rtm = response.json() | |
# Connection | |
async with websockets.connect(rtm['url']) as ws: | |
while True: | |
listener_task = asyncio.ensure_future(ws.recv()) | |
producer_task = asyncio.ensure_future(producer()) | |
done, pending = await asyncio.wait([listener_task, producer_task], | |
return_when=asyncio.FIRST_COMPLETED) | |
for task in pending: | |
task.cancel() | |
if listener_task in done: | |
message = listener_task.result() | |
await consumer(message) | |
if producer_task in done: | |
message = producer_task.result() | |
await ws.send(message) | |
loop = asyncio.get_event_loop() | |
loop.set_debug(True) | |
loop.run_until_complete(bot(TOKEN)) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment