Создайте отдельную модель Room
class Room(models.model):
users = models.ManyToManyField(
"User",
related_name='rooms',
blank=True,
symmetrical=False)
Прежде чем перейти к consumer.py
, убедитесь, что ваша полезная нагрузка состоит из следующих трех элементов:
event_type
: Что вызвало это событие?пользователь отправляет сообщение?вы отправляете уведомление пользователю?Это предупреждение?
data
: Какие данные отправляются вместе?
errors
: есть ли ошибки?
Пример полезной нагрузки:
{
"event_type": "send_message",
"data": {
"message": "Hi",
"room": 143,
},
"errors": None
}
{
"event_type": "send_notif",
"data": {
"message": "You received a friend request from xxx",
"type": "friend_request",
},
"errors": None
}
Потребитель.py
class GroupMessageListConsumer(AsyncWebsocketConsumer):
user = None
async def connect(self):
self.user = self.scope["user"] #authenticated user either passed in through session or by token authentication
print("connection request received.")
await self.accept()
print("connection accepted")
#channel/channel_name is the current open socket connection between your browser and the server
# Join channel or user to his rooms
for room in self.user.rooms:
await self.channel_layer.group_add(
room.id,
self.channel_name
)
async def disconnect(self, close_code):
#remove current channel from listening to messages as it is closed or disconnected
# Leave channel from all rooms
for room in self.user.rooms:
await self.channel_layer.group_discard(
room.id,
self.channel_name
)
print("channel disconnected.")
raise StopConsumer()
async def receive(self,text_data):
print("message received.")
text_data_json = json.loads(text_data)
#always maintain payload with three main fields: "event_type", "data", "errors"
event_type = text_data_json['event_type']
data = text_data_json['data']
if event_type=="send_message":
#check whether user is allowed to send messages to room 143
#Then send the message to that room.
await self.channel_layer.group_send(
data["room"],
{
'type': "send_message", #call the respective event "async def send_message(self, event)" see below
'message': {
'event_type': event_type,
'data': {"message": data["message"], "user": self.user.id},
'errors': None
}
}
)
else:
print("event_type unknown")
async def send_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))