0

I made a live chat application with Fastapi websocket, but I want to learn the message read status and add it to the interface. How can I get whether the message has been read or not.

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)


manager = ConnectionManager()


@app.get("/")
async def get():
    return HTMLResponse(html)


@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(f"You wrote: {data}", websocket)
            await manager.broadcast(f"Client #{client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client #{client_id} left the chat")

I want to get the read information of messages sent with websocket. Like whatsapp, which will show users the message as read or unread

  • Websocket messages have no concept of "reading information". If you want that, you're gonna have to implement it yourself. Something like storing all your messages in a database with a read/unread flag, and send a message from the frontend when you want to mark a message as read. – M.O. Feb 24 '23 at 12:25
  • It occurred to me to handle this job in the database, but how do I determine the read or unread flag? – RunCoderRun Feb 24 '23 at 12:30
  • What makes a message read or unread? I'm assuming it's somehow related to the user interacting with it. When that happens, send a message (either over websocket or as a POST request) from the frontend that "message with ID xyz was read". – M.O. Feb 24 '23 at 12:41

0 Answers0