import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = f"chat_{self.room_name}" self.username = "Anonymous" async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "system.message", "text": f"{self.username} left the chat"}, ) def receive(self, text_data): text_data_json = json.loads(text_data) msg_type = text_data_json.get("type", "message") if msg_type == "join": self.username = text_data_json.get("username", "Anonymous") async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "system.message", "text": f"{self.username} joined the chat"}, ) return if msg_type == "rename": old_name = self.username self.username = text_data_json.get("username", self.username) async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "system.message", "text": f"{old_name} is now known as {self.username}"}, ) return message = text_data_json["message"] username = text_data_json.get("username", self.username) async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat.message", "message": message, "username": username}, ) def chat_message(self, event): self.send(text_data=json.dumps({ "message": event["message"], "username": event["username"], })) def system_message(self, event): self.send(text_data=json.dumps({ "type": "system", "text": event["text"], }))