ChatterBot Django Sample Code

Note

Looking for the full example app? Check it out on GitHub: https://github.com/gunthercox/ChatterBot/tree/master/examples/django_example

Example API Views

ChatterBot’s Django example comes with an API view that demonstrates one way to use ChatterBot to create an conversational API endpoint for your application.

The endpoint expects a JSON request in the following format:

{"text": "My input statement"}
examples/django_example/django_example/views.py
class ChatterBotApiView(View):
    """
    Provide an API endpoint to interact with ChatterBot.
    """

    chatterbot = ChatBot(**settings.CHATTERBOT)

    def post(self, request, *args, **kwargs):
        """
        Return a response to the statement in the posted data.

        * The JSON data should contain a 'text' attribute.
        """
        input_data = json.loads(request.body.decode('utf-8'))

        if 'text' not in input_data:
            return JsonResponse({
                'text': [
                    'The attribute "text" is required.'
                ]
            }, status=400)

        response = self.chatterbot.get_response(**input_data)

        response_data = response.serialize()

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        """
        Return data corresponding to the current conversation.
        """
        return JsonResponse({
            'name': self.chatterbot.name
        })

Example Django Management Commands

ChatterBot’s Django example includes a management command that demonstrates a simple example of training. This can be used as a basis for other custom management commands used with other training options.

examples/django_example/django_example/management/commands/train.py
"""
This is an example of a custom Django management command that
trains a ChatterBot instance with specified data.

For more information on how to create custom management commands,
see the Django documentation:
https://docs.djangoproject.com/en/4.2/howto/custom-management-commands/

For details on the available training options for ChatterBot see:
http://docs.chatterbot.us/training/ 
"""

from django.core.management.base import BaseCommand
from django.conf import settings

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer


class Command(BaseCommand):
    help = 'Train a ChatterBot instance with specified data.'

    def handle(self, *args, **options):
        chatbot = ChatBot(**settings.CHATTERBOT)

        trainer = ListTrainer(chatbot)

        trainer.train([
            'Hello, how are you?',
            'I am good.',
            'That is good to hear.',
            'I am glad to hear that.',
            'Thank you.',
            'You are welcome.',
        ])

        self.stdout.write(
            self.style.SUCCESS('Training completed successfully')
        )