From a188df3ae359ab770aac85d19d23739286ef6d41 Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Tue, 9 Jun 2026 22:53:50 +0200 Subject: Initial commit --- chat/consumers.py | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 chat/consumers.py (limited to 'chat/consumers.py') diff --git a/chat/consumers.py b/chat/consumers.py new file mode 100644 index 0000000..bfba381 --- /dev/null +++ b/chat/consumers.py @@ -0,0 +1,65 @@ +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"], + })) -- cgit v1.2.3