from django.contrib.auth.mixins import LoginRequiredMixin from django.views import View from django.shortcuts import render from django.http import JsonResponse from .chatbot_logic import get_gpt4_response import json class ChatbotView(LoginRequiredMixin, View): """ Represents a view for handling chatbot interactions. This class handles GET and POST requests for a chatbot interface. It leverages `LoginRequiredMixin` to ensure that only authenticated users can access it. On GET requests, it renders the chatbot interface, while on POST requests, it interacts with a chatbot backend to process user messages and return responses. :ivar request: The HTTP request object, providing metadata about the current session and user. :type request: HttpRequest """ def get(self, request): return render(request, "haikalbot/chatbot.html") def post(self, request): dealer = request.user.dealer try: data = json.loads(request.body) user_message = data.get("message", "").strip() if not user_message: return JsonResponse({"error": "Message cannot be empty."}, status=400) chatbot_response = get_gpt4_response(user_message, dealer) return JsonResponse({"response": chatbot_response}, status=200) except json.JSONDecodeError: return JsonResponse({"error": "Invalid JSON format."}, status=400)