class ChatConsumer(AsyncWebsocketConsumer):

async def connect(self):
query_string_bytes = self.scope.get('query_string', b'') # 1. Get the raw query string from the scope
query_string_str = query_string_bytes.decode('utf-8') # 2. Decode it from bytes to string (UTF-8 is a common encoding)
query_params = parse_qs(query_string_str) # 3. Parse the query string into a dictionary
token_list = query_params.get('token', []) # 4. Extract the token value
token = token_list[0] if token_list else None
user = await get_user_from_token(token)

      self.room_name = self.scope['url_route']['kwargs']['room_name']
    self.room_group_name = f'chat_{self.room_name}'
    
    # Authenticate user
    if isinstance(user, AnonymousUser):
        await self.close()
    else:
        self.user = user

        # Join room group
        await self.channel_layer.group_add(
        self.room_group_name,
        self.channel_name
        )
        await self.accept()  # Accept the WebSocket connection
         

async def disconnect(self, close_code):
    # Leave room group
    await self.channel_layer.group_discard(
        self.room_group_name,
        self.channel_name
    )

async def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']
    print(f"Received message: {message} from user: {self.user.username}")

    # saving message to the database
    await save_message_to_db(self.room_name, self.user, message )
    
    # Send message to room group
    await self.channel_layer.group_send(
        self.room_group_name,
        {
            'type': 'chat_message',
            'message': message,
            'sender': self.user.username
        }
    )

async def chat_message(self, event):
    # Send message to WebSocket
    await self.send(text_data=json.dumps({
        'message': event['message'],
        'sender': event['sender']
    }))
    

the above is the existing chat consumer class and how it works is it receive and send to both user on same group but i don't know how to do for sending to only one user can you make it clear

Comments

Popular posts from this blog