I have a chat application in which I can send message in real time. I use Django channels for websocket connection.
Here is how it works: Let's say user1 is sending a message and five more people will see the message right away. This is because all the users are in the same room room_group_name which is added to the channel:
await self.channel_layer.group_add(
self.room_group_name, self.channel_name
)
and then as the result message is sent to them:
await self.channel_layer.group_send(
self.room_group_name,
{
"type": "chat_message",
"text": json.dumps(myresponse),
})
Now here is a scenario where I stuck:
when I send a message to chatroom#1 not only I want to update chtroom#1 (which I can), but also users in other chatrooms, need to be notified that chatroon#1 has 1 message.
as an example user one is member of chatroom#1 and chatroom#2. While he is active in chatroom#2, chatroom#1 receives some messages. currently there is no way for this user to be notified because according to above settings only one chatroom self.room_group_name is receiving update.
I wonder how should I add different rooms to my channel, so both chatroom#1 and #2 will be notified:
any hint is appreciated
Thanks,
What you have to do is store somewhere in your db the relation between room and user. Basically, you should store which user is part of which room. And when user connects to your websocket(in connect function in django-channels), you should connect the user to all the rooms it is part of as follow:
await self.accept()
self.joined_rooms = await self.get_rooms()
for room in self.joined_rooms:
await self.channel_layer.group_add(
'group_' + room.name,
self.channel_name
)
Basically, rather than connecting user to only the room user is currently active you can connect it to all the rooms user is part of, so that whenever there is any activity in any of the room/group, he will receive a websocket event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With