Python Websockets Connection Error

Question:
My code keeps returning the error

  File "/home/runner/OWOTSocket/main.py", line 15, in <module>
    asyncio.run(say("Hey guys."))
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/home/runner/OWOTSocket/main.py", line 11, in say
    response = await chat.recv()
  File "/home/runner/OWOTSocket/.pythonlibs/lib/python3.10/site-packages/websockets/legacy/protocol.py", line 568, in recv
    await self.ensure_open()
  File "/home/runner/OWOTSocket/.pythonlibs/lib/python3.10/site-packages/websockets/legacy/protocol.py", line 944, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: received 1005 (no status code [internal]); then sent 1005 (no status code [internal])

after connecting for a few seconds. Why is this happening and how do I fix this?
Repl link:
https://replit.com/@dgrilawidbanana/OWOTSocket#main.py

import asyncio
import json
import websockets as ws

OWOT = "wss://ourworldoftext.com/ws/"

async def say(message):
  async with ws.connect(OWOT) as chat:
    await chat.send(f"{{kind: \"chat\", nickname: \"Dat_Hack3r\", message: \"{message}\", location: \"global\", color: \"#ff0000\"}}")
    while True:
      response = await chat.recv()
#      print(json.loads(response)["kind"])#  == "chat":
      print(response)

asyncio.run(say("Hey guys."))

Kinda hard tell what it is with this.
Also put a check in your code

import asyncio
import json
import websockets as ws

OWOT = "wss://ourworldoftext.com/ws/"

async def say(message):
    async with ws.connect(OWOT) as chat:
        await chat.send(f'{{kind: "chat", nickname: "Dat_Hack3r", message: "{message}", location: "global", color: "#ff0000"}}')
        
        while chat.open:  # just a check to see if the connection is open
            response = await chat.recv()
            print(response)

asyncio.run(say("Hey guys."))

You might consider doing proper error handling too.

1 Like

I believe there might be an issue with the website. I just attempted to make my own, and it appears that the site might be terminating connections when accessed through a script or bot, rather than when connecting manually.