0

Iìm triing to create a simple chat app usign django channels

i create a consumer on connect method i register all user to a personal group and when i sent a message the recieve method should sent it back to the target user group using the id of the target user included in the messagge. The action in not being triggered anyway

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.user = self.scope["user"]
        self.group_name = f"user_{self.user.id}_group"
        print("my group: ", self.group_name)
        self.accept()
        async_to_sync(self.channel_layer.group_add(self.group_name, self.channel_name))

    def disconnect(self, close_code):
         async_to_sync(self.channel_layer.group_discard(self.group_name, self.channel_name))

    def receive(self, text_data):
        self.chat_id = self.scope["url_route"]["kwargs"]["chat_id"]
        data = json.loads(text_data)

        message_content = data["message"]
        recipient_user_id = data["recipient_user_id"]

        recipient = User.objects.get(id=recipient_user_id)
        message = Message.objects.create(
            chat_id=self.chat_id, owner=self.user, content=message_content
        )
        message.recipients.add(recipient)
 
        recipient_group_name = f"user_{recipient_user_id}_group"
        async_to_sync(
            self.channel_layer.group_send(
                recipient_group_name,
                {
                    "type": "chat_message",
                    "message": message_content,
                    "owner": self.user.id,
                },
            )
        )

    def chat_message(self, event):
        message = event["message"]
        owner = event["owner"]

        self.send(
            text_data=json.dumps(
                {
                    "message": message,
                    "owner": owner,
                }
            )
        )

0

Browse other questions tagged or ask your own question.