Как Я Могу Заставить Работать Глобальные Уведомления Django По Каналам?

Я потратил последний месяц или около того, пытаясь заставить работать уведомления django channels. Я не могу заставить уведомления работать, но чат работает, как ожидалось. Вот мой код...

Consumers.py

Мой базовый файл...

        var wsScheme = window.location.protocol == "https:" ? "wss" : "ws";
        var wsPath = wsScheme + "://" + window.location.host + "/ws/notifications/";

        var socket = new WebSocket(wsPath);

        socket.onopen = function() {
            console.log('WebSocket connection established.');
        };

        socket.onmessage = function(event) {
            console.log('Message received from WebSocket: ', event.data);  // Log the message
            var data = JSON.parse(event.data);

            // If there's a message, display it
            if (data.message && data.sender) {
                alert("New notification from " + data.sender + ": " + data.message); // Display an alert
            } else {
                console.log('No message data in received WebSocket message.');
            }
        };

        socket.onclose = function() {
            console.log('WebSocket connection closed.');
        };

Мой URLs.py

websocket_urlpatterns = [
    re_path(r'LevelSet/Chat/ws/group/(?P<group_name>[^/]+)/$', consumers.ChatConsumer.as_asgi()),  # Match group names with spaces
    re_path(r'LevelSet/Chat/ws/direct/(?P<recipient_username>[^/]+)/$', consumers.ChatConsumer.as_asgi()),  # Direct message route
    re_path(r'LevelSet/Chat/ws/notifications/$', consumers.GlobalNotificationConsumer.as_asgi()),
]

Мой ASGI-файл...

application = ProtocolTypeRouter(
    {
        'http': get_asgi_application(),
        'websocket': AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(Chat.routing.websocket_urlpatterns))
        )
    }
)

И в моем view...as примере...Я пытаюсь выполнить это...

def send_test_notification(user):
channel_layer = get_channel_layer()

# Create a test notification
notification = "This is a test message sent to the WebSocket."
print("driver")
# Send message to the user's WebSocket group
async_to_sync(channel_layer.group_send)(
    f"chat_notifications_{user.id}",
    {
        'type': 'chat_message',
        'notification': notification
    }
)

return HttpResponse("Test notification sent to WebSocket.")  I see the driver print in my console....but the chat_message notification is not popping up or showing on my page...Thanks in advance for any thoughts...
Вернуться на верх