2023-11-27 09:10:06 -05:00
|
|
|
import json
|
|
|
|
from channels.generic.websocket import WebsocketConsumer
|
|
|
|
from asgiref.sync import async_to_sync
|
|
|
|
|
|
|
|
class ChatConsumer(WebsocketConsumer):
|
|
|
|
def connect(self):
|
2023-12-16 05:58:50 -05:00
|
|
|
self.room_group_name = 'test'
|
2023-11-27 09:10:06 -05:00
|
|
|
|
|
|
|
async_to_sync(self.channel_layer.group_add)(
|
|
|
|
self.room_group_name,
|
|
|
|
self.channel_name
|
|
|
|
)
|
|
|
|
|
|
|
|
self.accept()
|
|
|
|
|
|
|
|
|
2023-12-16 05:58:50 -05:00
|
|
|
def receive(self, text_data):
|
2023-11-27 09:10:06 -05:00
|
|
|
text_data_json = json.loads(text_data)
|
|
|
|
message = text_data_json['message']
|
|
|
|
|
2023-12-12 04:05:13 -05:00
|
|
|
user = self.scope["user"]
|
2023-12-16 05:58:50 -05:00
|
|
|
if user.is_anonymous:
|
|
|
|
return;
|
2023-12-12 04:05:13 -05:00
|
|
|
|
2023-11-27 09:10:06 -05:00
|
|
|
async_to_sync(self.channel_layer.group_send)(
|
|
|
|
self.room_group_name,
|
|
|
|
{
|
|
|
|
'type':'chat_message',
|
2023-12-16 05:58:50 -05:00
|
|
|
'username':user.username,
|
|
|
|
'message':message
|
2023-11-27 09:10:06 -05:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
def chat_message(self, event):
|
|
|
|
|
2023-12-12 04:05:13 -05:00
|
|
|
user = self.scope["user"]
|
2023-12-16 05:58:50 -05:00
|
|
|
if user.is_anonymous:
|
|
|
|
return;
|
2023-12-12 04:05:13 -05:00
|
|
|
|
2023-11-27 09:10:06 -05:00
|
|
|
self.send(text_data=json.dumps({
|
|
|
|
'type':'chat',
|
2023-12-16 05:58:50 -05:00
|
|
|
'username':event['username'],
|
|
|
|
'message':event['message']
|
2023-11-27 09:10:06 -05:00
|
|
|
}))
|