Last active
June 8, 2023 10:45
-
-
Save DarkcoderSe/d49fb2685ff6cc3d991dc8db07512c85 to your computer and use it in GitHub Desktop.
Django Channels Chat Exmaple with DB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# routing.py file | |
# room_name is consist of conversation.id where sender and receiver is saved | |
path(r"ws/chat/<str:room_name>", consumers.ChatConsumer.as_asgi()), | |
# consumers.py file | |
class ChatConsumer(WebsocketConsumer): | |
def connect(self): | |
print("here") | |
self.room_name = self.scope["url_route"]["kwargs"]["room_name"] | |
self.room_group_name = f"chat_{self.room_name}" | |
# Join room group | |
async_to_sync(self.channel_layer.group_add)( | |
self.room_group_name, self.channel_name | |
) | |
self.accept() | |
def disconnect(self, close_code): | |
# Leave room group | |
async_to_sync(self.channel_layer.group_discard)( | |
self.room_group_name, self.channel_name | |
) | |
def receive(self, text_data=None, bytes_data=None): | |
# parse the json data into dictionary object | |
print("TEXT_DATA=", text_data) | |
text_data_json = json.loads(text_data) | |
conversation = Conversation.objects.get(id=int(self.room_name)) | |
sender = self.scope['user'] | |
_message = Message.objects.create( | |
sender=sender, | |
text=text_data_json["message"], | |
conversation_id=conversation, | |
is_delivered=True, | |
) | |
print("SENDING TO GROUP") | |
async_to_sync(self.channel_layer.group_send)( | |
self.room_group_name, | |
{ | |
"type": "chat_message", | |
"message": text_data_json["message"], | |
"_message": MessageSerializer(_message).data, | |
}, | |
) | |
def chat_message(self, event): | |
text_data_json = event.copy() | |
text_data_json.pop("type") | |
message, _message = ( | |
text_data_json["message"], | |
text_data_json["_message"], | |
) | |
# create a copy of the message payload without the sender's name | |
broadcast_data = {k: v for k, v in text_data_json.items() if k != "sender_name"} | |
# Send message to WebSocket | |
self.send( | |
text_data=json.dumps( | |
{**_message, **broadcast_data} | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment