Django Channels sending multiple messages to same channel
Referring to documentation here
I'm sending messages to the single fetched channel_name I'm able to successfully send messages to the specific channel
Issues I'm facing On the channels it's sending messages multiple times
For Example - When I send first message, I receive 1 time. On second message, I'm getting same messages twice. On third message, I'm geting same message 3 times. and so on...
class ChatConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.user_id = self.scope['url_route']['kwargs']['user_id']
await self.save_user_channel()
await self.accept()
async def disconnect(self, close_code):
await self.disconnect()
async def receive_json(self, text_data=None, byte_data=None):
message = text_data['message']
to_user = text_data['to_user']
to_user_channel, to_user_id = await self.get_user_channel(to_user)
channel_layer = get_channel_layer()
await channel_layer.send(
str(to_user_channel), {
'type': 'send.message',
'from_user': self.user_id,
'to_user': str(to_user_id),
'message': message,
}
)
await channel_layer.send(
str(self.channel_name), {
'type': 'send.message',
'from_user': self.user_id,
'to_user': str(to_user_id),
'message': message,
}
)
async def send_message(self, event):
from_user = event['from_user']
to_user = event['to_user']
message = event['message']
await self.send(text_data=json.dumps({
'from_user': from_user,
'to_user': to_user,
'message': message,
}))
@database_sync_to_async
def get_user_channel(self, to_user):
try:
self.send_user_channel = ChatParticipantsChannel.objects.filter(
user=to_user).latest('id')
channel_name = self.send_user_channel
user_id = self.send_user_channel.user.user_uid
except Exception as e:
self.send_user_channel = None
channel_name = None
return channel_name, user_id
@database_sync_to_async
def save_user_channel(self):
self.user = User.objects.get(user_uid=self.user_id)
ChatParticipantsChannel.objects.create(
user=self.user,
channel=self.channel_name
)
@database_sync_to_async
def delete_user_channel(self):
ChatParticipantsChannel.objects.filter(user=self.user).delete()