Django websocket channel message handler not executing after invocation in webhook
Objective - Setup and run django as asgi, have a websocket endpoint. Accept webhook request in django and send udpates to websocket so all clients listening to websocket will be notified.
Views.py
from django.shortcuts import render
from django.http import JsonResponse
from channels.layers import get_channel_layer
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
def websocket_notifications(request):
return render(request, 'my_app/notifications.html')
@csrf_exempt
@require_POST
def send_message_to_websocket(request):
message = request.POST.get('message', 'Hello, WebSocket clients!')
# Get the channel layer
channel_layer = get_channel_layer()
# Broadcast the message to the WebSocket group
channel_layer.group_send(
'notifications_notification_room', # The group name (matches your consumer)
{
'type': 'chat_message', # Type that the consumer will listen for
'message': message
}
)
return JsonResponse({'status': 'Message sent', 'message': message})
consumers.py
import json
import logging
import asyncio
from channels.generic.websocket import AsyncWebsocketConsumer
# Set up a logger
logger = logging.getLogger(__name__)
class MyWebSocketConsumer(AsyncWebsocketConsumer):
async def connect(self):
logger.debug(f"WebSocket connection attempt from {self.channel_name}")
print(f"WebSocket connection attempt from {self.channel_name}")
self.room_name = 'notification_room'
self.room_group_name = f'notifications_{self.room_name}'
# Log to confirm the WebSocket joins the group
logger.debug(f"Joining group: {self.room_group_name}")
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
# Start a task to send messages every 2 seconds
# self.message_task = asyncio.create_task(self.send_periodic_messages())
async def disconnect(self, close_code):
logger.debug(f"WebSocket connection closed for {self.channel_name} (Close code: {close_code})")
# Cancel the periodic message task
if hasattr(self, 'message_task'):
self.message_task.cancel()
# Leave the room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
logger.debug(f"Received message from WebSocket client: {text_data}")
# Receive message from room group
async def chat_message(self, event):
print('in chat message event')
logger.debug(f"Received message from group: {event['message']}")
message = event['message']
# Send message to WebSocket client
await self.send(text_data=json.dumps({
'message': message
}))
async def send_periodic_messages(self):
# This method sends a message to all WebSocket clients every 2 seconds
while True:
await asyncio.sleep(2) # Wait for 2 seconds
message = "This is an automatic message" # Change this to any message you want
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
logger.debug(f"Sent periodic message: {message}")
When I try using webhook control never goes in chat_message function, but if I use send_periodic_messages within same file to automate everything works fine. I can see websocket is always connecting and I can see json reponse from views.py webhook handler. Where is the issue then?
Everything Everything Everything