Websocket transport session does not exist or has already disconnected - Python

Writing a websocket client and eventsub subscription request in python, websocket recieves welcome message and functions seemingly correctly, but returns error 400, seen above, upon sending the subscription request:

async def listen():
  url = "wss://eventsub.wss.twitch.tv/ws"

  async with websockets.connect(url) as websocket: 
    msg = await websocket.recv()
    msg_dic = json.loads(msg)
    seshId = (msg_dic["payload"]["session"]["id"])
    global sessionID 
    sessionID = seshId

async def post_request():
  async with aiohttp.ClientSession() as session:
      response = await session.post(url="https://api.twitch.tv/helix/eventsub/subscriptions",
                                         "version": "1",
                                           "broadcaster_user_id": "------"},
                                    headers={'Authorization': 'Bearer ---------',
                                             'Client-Id': '----------',
                                            "Content-Type": "application/json",})
      print(await response.json())

Based on my limited knowledge of python

Looks like your post_request runs before you connect to the websocket.

You are supposed to

  • connect to the websocket
  • recieve a session_welcome message over the websocket
  • that session_welcome provides the socket ID to use to make subscriptions with

I don’t see anything processing a session_welcome

I think your code is loading one message from the websocket and assuming it’s the session_welcome.

But your subscription request seems to run at the same time as connecting to the socket so things are in the wrong order. (Based on line indentation)

1 Like

5 posts were split to a new topic: Python: websocket transport session does not exist or has already disconnected - due to send