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
  
asyncio.get_event_loop().run_until_complete(listen())

async def post_request():
  async with aiohttp.ClientSession() as session:
      response = await session.post(url="https://api.twitch.tv/helix/eventsub/subscriptions",
                                    data=json.dumps({"type":"stream.online",
                                         "version": "1",
                                         "condition":{
                                           "broadcaster_user_id": "------"},
                                         "transport":{
                                           "method":"websocket",
                                           "session_id":sessionID}}),                                                            
                                    headers={'Authorization': 'Bearer ---------',
                                             'Client-Id': '----------',
                                            "Content-Type": "application/json",})
      print(await response.json())
asyncio.run(post_request())

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

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.