aboutsummaryrefslogtreecommitdiff
path: root/chat/consumers.py
diff options
context:
space:
mode:
authorBobby <[email protected]>2023-05-15 07:30:20 -0400
committerBobby <[email protected]>2023-05-15 07:30:20 -0400
commit394d74b553360a82f803a34205a8df609777fdff (patch)
tree8e78eb5214a47eb5fa46d7400cea192ed6b3aa94 /chat/consumers.py
parent4cbc1c64b3f5f7bc6f6f9744dd09828d7e79d65d (diff)
downloadthatcomputerscientist-394d74b553360a82f803a34205a8df609777fdff.tar.xz
thatcomputerscientist-394d74b553360a82f803a34205a8df609777fdff.zip
Simple working live chat
Diffstat (limited to 'chat/consumers.py')
-rw-r--r--chat/consumers.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/chat/consumers.py b/chat/consumers.py
new file mode 100644
index 00000000..be1cf265
--- /dev/null
+++ b/chat/consumers.py
@@ -0,0 +1,40 @@
+import json
+from channels.generic.websocket import WebsocketConsumer
+from asgiref.sync import async_to_sync
+
+class ChatConsumer(WebsocketConsumer):
+ def connect(self):
+ self.room_group_name = 'chat'
+ async_to_sync(self.channel_layer.group_add)(
+ self.room_group_name,
+ self.channel_name
+ )
+ self.accept()
+
+ def receive(self, text_data):
+ text_data_json = json.loads(text_data)
+ message = text_data_json['message']
+ username = text_data_json['username']
+ async_to_sync(self.channel_layer.group_send)(
+ self.room_group_name,
+ {
+ 'type': 'chat',
+ 'message': message,
+ 'username': username
+ }
+ )
+
+ def chat(self, event):
+ message = event['message']
+ username = event['username']
+ self.send(text_data=json.dumps({
+ 'message': message,
+ 'username': username
+ }))
+
+ def disconnect(self, close_code):
+ async_to_sync(self.channel_layer.group_discard)(
+ self.room_group_name,
+ self.channel_name
+ )
+