I don't know why but it keeps disconnecting. Sometimes it works for 1 hour, sometimes less and sometimes 2.5 hour-ish
import aiohttp
import asyncio
import json
import datetime, time
token = "123"
payload = {
'op': 2,
"d": {
"token": token,
"properties": {
"$os": "windows",
"$browser": "chrome",
"$device": 'pc'
}
}
}
last_sequence = "null"
async def main():
global last_sequence
session = aiohttp.ClientSession()
async with session.ws_connect('wss://gateway.discord.gg/?v=9&encording=json') as ws:
async for msg in ws:
data = json.loads(msg.data)
if data["op"] == 10: # Hello
await ws.send_json(payload)
# (Keeps the connection alive!)
asyncio.ensure_future(heartbeat(ws, data['d']['heartbeat_interval']))
elif data["op"] == 11: # Heartbeat ACK
#print("Heartbeat Received")
pass
elif data["op"] == 0: # Dispatch
try:
if data['d']['guild_id']==("669653521007902751") and data['d']['channel_id']==("669653521007902766"):
print(f"{data['d']['content']}")
last_sequence = data['s']
#print(data)
except:
pass
elif data["op"] == 3: # Presence Update
print("This is OP 3", data)
elif data["op"] == 4: # Voice State Update
print("This is OP 4", data)
elif data["op"] == 6: # Resume
print("This is OP 6", data)
elif data["op"] == 7: # Reconnect, i don't know how this works. I was just testing it.
await ws.send_json(
{"op": 6,
"d": {
"token":token,
"session_id": "null",
"seq": last_sequence
}})
print("This is OP 7", data)
elif data["op"] == 8: # Request Guild Members
print("This is OP 8", data)
elif data["op"] == 9: # Invalid Session
print("This is OP 9", data)
else:
print("What happened?", data)
#await session.close()
async def heartbeat(ws, interval):
while True:
await asyncio.sleep(interval / 1000) # seconds
await ws.send_json({
"op": 1, # Heartbeat
"d": last_sequence
})
print("Heartbeat Sent", last_sequence, time.strftime("%H:%M:%S", time.localtime()))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
The error is
This is OP 7 {'t': None, 's': None, 'op': 7, 'd': None} Task was destroyed but it is pending! task: <Task pending name='Task-4' coro=<heartbeat() running at C:\Users\test\Desktop\Discord_Test\aio_test.py:83> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x00000214675B83D0>()]>>