1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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"],
}))
|