from django.views import View from django.shortcuts import render from django.http import JsonResponse from .chatbot_logic import get_response import json class ChatbotView(View): """ Class-based view to handle chatbot template rendering (GET) and GPT-4-based chatbot API responses (POST). """ def get(self, request): """ Render the chatbot interface template. """ return render(request, "haikalbot/chatbot.html") def post(self, request): """ Handle chatbot API requests and return responses as JSON. """ try: # Parse JSON payload from the request body data = json.loads(request.body) user_message = data.get("message", "").strip() if not user_message: return JsonResponse({"error": "Message cannot be empty."}, status=400) # Get GPT-4 response chatbot_response = get_response(user_message) return JsonResponse({"response": chatbot_response}, status=200) except json.JSONDecodeError: return JsonResponse({"error": "Invalid JSON format."}, status=400)