Skip to content

Instantly share code, notes, and snippets.

@TonyPythoneer
Created June 28, 2018 07:05
Show Gist options
  • Save TonyPythoneer/969879b01c854ce5359fe58ea6b7757f to your computer and use it in GitHub Desktop.
Save TonyPythoneer/969879b01c854ce5359fe58ea6b7757f to your computer and use it in GitHub Desktop.
import asyncio
import json
import aiohttp
import zlib
TOKEN = ""
URL = "https://discordapp.com/api"
async def api_call(path, method="GET", **kwargs):
"""Return the JSON body of a call to Discord REST API."""
defaults = {
"headers": {
"Authorization": f"Bot {TOKEN}",
"User-Agent": "DiscordBot (https://medium.com/@greut, 0.1)"
}
}
kwargs = dict(defaults, **kwargs)
async with aiohttp.ClientSession() as session:
async with session.request(method, f'{URL}{path}', **kwargs) as response:
assert 200 == response.status, response.reason
return await response.json()
async def identify(ws):
"""Tâche qui identifie le bot à la Web Socket (indispensable)."""
print('identify')
await ws.send_json({'op': 2, # Identify
'd': {'token': TOKEN,
'properties': {},
'compress': True, # implique le bout de code lié à zlib, pas nécessaire.
'large_threshold': 250}})
async def start(url):
async with aiohttp.ClientSession() as session:
async with session.ws_connect(f'{url}?v=6&encoding=json') as ws:
async for msg in ws:
# import ipdb; ipdb.set_trace()
if msg.type == aiohttp.WSMsgType.TEXT:
data = msg.json()
elif msg.type == aiohttp.WSMsgType.BINARY:
data = json.loads(zlib.decompress(msg.data))
else:
print("?", msg.type)
from pprint import pprint
pprint(msg.type)
pprint(data)
if data["op"] == 10: # Hello
print("hello")
asyncio.ensure_future(heartbeat(
ws,
data['d']['heartbeat_interval']))
await identify(ws)
elif data["op"] == 11: # Heartbeat ACK
pass
async def heartbeat(ws, interval):
"""Send every interval ms the heatbeat message."""
while True:
print('heartbeat')
await asyncio.sleep(interval / 1000) # seconds
await ws.send_json({
"op": 1, # Heartbeat
"d": 0
})
async def main():
"""Main program."""
response = await api_call("/gateway")
await start(response['url'])
print(response)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment