Chat_message не работает в consumsers.py при изменении значения channel_name
Я создаю синхронный чат-бот AI, есть 7 разных моделей, каждая из которых служит для разных целей, поэтому я назначаю разное имя_канала при подключении(connect). Однако, когда я назначаю новое имя_канала, мое chat_message не работает вообще, но остальные функции (получение, подключение, отключение) работают нормально. Кроме того, я не вижу никаких сообщений в index.html, потому что chatSocket.onmessage не срабатывает.
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from .models import Message
from .contants import SendType
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.group_name = str(self.scope["user"].pk)
module_name = self.scope['url_route']['kwargs']['module']
self.channel_name = module_name
#self.channel_name = "something"
# print(self.scope)
# print("-------")
print(self.scope['url_route'])
print(self.channel_name)
self.user = self.scope["user"]
async_to_sync(self.channel_layer.group_add)(
self.group_name, self.channel_name
)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.group_name, self.channel_name
)
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json["message"]
event = {
'type':"chat.message",
"message":message
}
print(message)
print(self.channel_name)
print(self.scope['user'])
if len(message) > 0:
async_to_sync(self.channel_layer.group_send)(
self.group_name, event
)
def chat_message(self, event):
message = event["message"]
print("CHECKING\n")
message_obj = Message(text=message, user=self.user, sender_type=1)
message_obj.save()
self.send(text_data=json.dumps({"message": f"{self.user.username}: {message}"}))
consumers.py
from django.urls import re_path, path
from . import consumers
websocket_urlpatterns = [
#path("ws/chat/", consumers.ChatConsumer .as_asgi()),
re_path(r'ws/chat/(?P<module>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
routes.py
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
<script>
console.log("Script started.");
const chatSocket = new WebSocket(
'ws://' + window.location.host
+ '/ws/chat/'
// +'your_module_name/'
);
chatSocket.onmessage = function(e) {
console.log("Received message from server:", e.data);
try {
const data = JSON.parse(e.data);
console.log("Parsed data:", data);
document.querySelector('#chat-log').value += (data.message + '\n');
} catch (error) {
console.error("Error parsing JSON:", error);
console.log("Raw data:", e.data); // Add this line to see the raw data received
}
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
console.log("read");
if (e.key === 'Enter') {
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
console.log("Send button clicked.");
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
console.log(message)
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
console.log("Script loaded.");
</script>
</body>
</html>
index.html
from django.shortcuts import render, redirect
from rest_framework.response import Response
from django.urls import reverse
from .models import Message
def index(request):
if request.user.is_authenticated:
messages = Message.objects.filter(user=request.user).order_by('created')
return render(request, "main/index.html", {'messages': messages})
else:
url = reverse('rest_login')
return redirect(url)
views.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
urls.py
from django.db import models
from qazexpo.common.models import Base
from django.utils.translation import gettext_lazy as _
from qazexpo.user.models import User
from .contants import SendType, AIType
class Message(Base):
text = models.TextField(null=False, blank=False)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
sender_type = models.PositiveIntegerField( choices=SendType.choices, null=True)
ai_type = models.PositiveIntegerField(choices=AIType.choices, null=True)
audio_file = models.FileField(upload_to="audios/", blank=True, null=True)
def delete(self, *args, **kwargs):
self.audio_file.delete()
super().delete(*args, **kwargs)
class Meta:
verbose_name = 'message'
verbose_name_plural = 'messages'
models.py
Однако, когда я не присваиваю новое значение channel_name, chat_message работает.
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.group_name = str(self.scope["user"].pk)
#module_name = self.scope['url_route']['kwargs']['module']
#self.channel_name = module_name
#self.channel_name = "something"
# print(self.scope)
# print("-------")
print(self.scope['url_route'])
print(self.channel_name)
self.user = self.scope["user"]
async_to_sync(self.channel_layer.group_add)(
self.group_name, self.channel_name
)
self.accept()