Saturday, 17 September 2022

Python WebSocket Connection (maybe deflate compression)

I want to do the following thing: I want to make a websocket, which prints me all events about esports and I want to use https://sofascore.com I've inspected the network requests as usual and it seems that I need to send a Auth WebSocket Content first, then one for subscribing the right sport and then I will receive my events I need.

I've wrote the following code:

import websockets
import asyncio
from websockets.extensions import permessage_deflate


async def esports():
    async with websockets.connect('wss://ws.sofascore.com:9222/', compression='deflate') as websocket:
        msg = await websocket.recv()
        print(f"From Server: {msg}")
        t = await websocket.send(
            'CONNECT {"no_responders":true,"protocol":1,"verbose":false,"pedantic":false,"user":"none","pass":"none","lang":"nats.ws","version":"1.8.1","headers":true}')
        await websocket.send("PING")
        pong = await websocket.recv()
        print(f"From Server: {pong}")
        await websocket.send(
            'SUB sport.esports 6')
        while (True):
            msg = await websocket.recv()
            print(f"From Server: {msg}")



asyncio.get_event_loop().run_until_complete(esports())

I know that the websocket is compressed as permessage_deflate, when I saw into the request headers of the websocket.

But I still get an error:

Traceback (most recent call last):
  File "C:\Users\Coding\Desktop\websockett.py", line 23, in <module>
    asyncio.get_event_loop().run_until_complete(esports())
  File "C:\Users\Coding\AppData\Local\Programs\Python\Python39-32\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\Coding\Desktop\websockett.py", line 15, in esports
    await websocket.send(
  File "C:\Users\Coding\AppData\Roaming\Python\Python39\site-packages\websockets\legacy\protocol.py", line 620, in send
    await self.ensure_open()
  File "C:\Users\Coding\AppData\Roaming\Python\Python39\site-packages\websockets\legacy\protocol.py", line 921, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: received 1008 (policy violation) Authentication Timeout; then sent 1008 (policy violation) Authentication Timeout

Process finished with exit code 1


from Python WebSocket Connection (maybe deflate compression)

No comments:

Post a Comment