Joy Singh
Joy Singh

Reputation: 375

Python: Coroutine was never awaited

I'm using await to then send a websocket message when connected but it keeps giving me "was never awaited" and doesn't send and I've tried to add await to the .send() function like this answer below asks me to, however it throws a TypeError: data is a dict-like object.

import asyncio
import websockets

logging.basicConfig()
IPAddress = input("Configure IP Address")
Port = input("Configure Port")
P1_UserID = ""
P2_UserID = ""
USERS = set()

async def register_player(websocket):
    global P1_UserID, P2_UserID
    if not P1_UserID:
        P1_UserID = websocket
        P1_UserID.send({"Player": 1})
    elif not P2_UserID:
        P2_UserID = websocket
        P2_UserID.send({"Player": 2})
    print(P1_UserID)
    print(P2_UserID)


async def server(websocket, path):
    await register(websocket)
    try:
        await register_player(websocket)
        async for e in websocket:
            print(e)
    finally:
        pass


start_server = websockets.serve(server, IPAddress, Port)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Upvotes: 1

Views: 1984

Answers (1)

Paul P
Paul P

Reputation: 3907

Looking at the websockets module documentation, it seems like you must await on websocket.send().

However, in your register_player() function, where you assign P1_UserID = websocket, you don't await on send() in the line below.

Apart from that, the message passed to websocket.send() cannot be a dict, see here.

Try changing register_player() to the following:

async def register_player(websocket):
    global P1_UserID, P2_UserID

    if not P1_UserID:
        P1_UserID = websocket
        await P1_UserID.send(json.dumps({"Player": 1}))
#       ^^^^^                ^^^^^^^^^^
#       This is missing      The message cannot be a
#       in your code.        dict, hence convert it to str.
    elif not P2_UserID:
        P2_UserID = websocket
        await P2_UserID.send(json.dumps({"Player": 2}))
#       ^^^^^                ^^^^^^^^^^
#       Same as above.       Same as above.

Upvotes: 1

Related Questions