Рассылаю сообщения в 3 комнаты с разным url, все работает но не уверен что код в consumers прописан адекватно и правильно с точки зрения написание кода.
consumers.py
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.chat_name = 'chat'
self.room_group_name = 'users_%s' % self.scope['url_route']['kwargs']['slug']
self.room_group_name_2 = 'users_%s' % self.scope["user"].id
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.channel_layer.group_add(
self.room_group_name_2,
self.channel_name
)
await self.channel_layer.group_add(
self.chat_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
await self.channel_layer.group_discard(
self.room_group_name_2,
self.channel_name
)
await self.channel_layer.group_discard(
self.chat_name,
self.channel_name
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
new_message = await self.create_new_message(message)
data = {
'author': new_message.author.username,
'created_at': new_message.created_at.strftime('%Y-%m-%d'),
'text': new_message.text,
'url': new_message.url
}
await self.channel_layer.group_send(
self.chat_name and self.room_group_name_2 and self.room_group_name,
{
'type': 'chat_message',
'message': data
}
)
async def chat_message(self, event):
message = event['message']
await self.send(text_data=json.dumps({
'message': message,
}))