I wrote these codes with Django Channels, but it gives me an error: These codes used to work correctly, but I don't know why they went wrong.
def receive(self, text_data=None, bytes_data=None):
text_data_json = json.loads(text_data)
message_type = text_data_json["type"]
message = text_data_json["message"]
if message_type == 'providerToAdmin':
chat = Chats.objects.get(user=self.sender)
Message.objects.create(text=message, date=datetime.datetime.now(), user_type=0, chat=chat)
group_name = f'chat_{self.admin.username}'
# self.send(text_data=json.dumps({'check': True, 'message': message}))
async_to_sync(self.channel_layer.group_send)(
group_name, {"userType": 0, "data": message, 'chatId': chat.id}
)
if message_type == 'adminToUsers':
chat = Chats.objects.get(user=self.sender)
Message.objects.create(text=message, date=datetime.datetime.now(), user_type=1, chat=chat)
group_name = f'chat_{self.admin.username}'
async_to_sync(self.channel_layer.group_send)(
group_name, {"userType": 0, "data": message, 'chatId': chat.id}
)
if message_type == 'providerToStore':
receiver = text_data_json["receiver"]
receiver = Store.objects.get(user__username=receiver)
provider = Provider.objects.get(user__username=self.sender)
chat = ChatsSP.objects.get(store=receiver, provider=provider)
MessageSP.objects.create(text=message, date=datetime.datetime.now(), user_type=1, chat=chat)
group_name = f'chat_{receiver.user.username}'
async_to_sync(self.channel_layer.group_send)(
group_name, {"userType": 0, "data": message, 'chatId': chat.id}
)
def chat_message(self, event):
message = event["data"]
name = event["name"]
userName = event["userName"]
chatId = event["chatId"]
self.send(text_data=json.dumps({"message": message, 'name': name, 'userName': userName,
'chatId': chatId
}))
but it raised this error:
aise ValueError("Incoming message has no 'type' attribute")