chat/apps/chat/websocket/consumers.py

23 lines
881 B
Python

import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.chat_id = self.scope["url_route"]["kwargs"]["chat_id"]
self.group_name = f"chat_{self.chat_id}"
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def receive(self, text_data=None, bytes_data=None):
# Frontend receives only; messages are sent via HTTP API
pass
async def chat_message(self, event):
"""Handle chat.message events forwarded from the channel layer."""
payload = {k: v for k, v in event.items() if k != "type"}
await self.send(text_data=json.dumps(payload))