[Answered ]-Django channels: notifications of message not working properly

1👍

It seems you are attempting to send the notification in two different ways but doing it the wrong way.

        # Send a notification to the recipient
        await self.channel_layer.send(
            recipient_user.username,
            {
                'type': 'notification',
                'message': message
            }
        )
        await self.send_notification(f'New message from {self.user_id}')
        print('notification has been created')

The first method attempts to send it through the channel layer which is the correct way given that the current channel is that of the sender, so you need to pipe it through the channel layer to the channel of the recipient. The issue is that you are not using the correct name of the handler. You are using notification as type instead of send_notification so it is never handled.
In the second case, you are calling the send_notification function directly in the current channel which is the sender’s channel so it will get sent to the sender instead of the intended receiver.
The entire code block above should be replaced with:

    # Send a notification to the recipient
    await self.channel_layer.send(
        recipient_user.username,
        {
            'type': 'send_notification',
            'message': f'New message from {self.user_id}'
        }
    )

0👍

In your receive function you only have a recipient and a connected user. This code takes the recipient that comes with the message and sends it to that user(the recipient) letting it know that it came from this user(the sender). The message already comes tagged with the recipient that it goes to when it hits the websocket. We need to get rid of that and keep track of all of our connected users within the ChatRoom object. You can simply handle this in the view or when the user connects to the websocket. When a message is sent, get each recipient user in the room, which should be every user except for the user that sent the object.

    print('ok2')
    await database_sync_to_async(chat.save)()
    print("ok3")
    # get the recipient user
    # database_sync_to_async function that gets the list of users
    # dont forget to call users.remove(sender)
    for each in users:
        recipient_user = each
        print("ok4")

        await sync_to_async(chat.recipient.add)(recipient_user.id)
        print("ok5")
    await database_sync_to_async(chat.save)()

Leave a comment