Implementing a Chatbot in Django

By Samuel Muiruri | Dec. 20, 2018 | Django


If you’ve been keeping current with current M.L. projects in NLP Natural Language Processing you know that there’s some that are impressive which returns “almost” intelligent response some just come out as incoherent even based on the question(s) asked.

There’s a repo on github that I like called Chatterbot it’s intelligent enough to use for demo purposes. If you’re interested in the repo or a live demo will keep it up for as long as possible.

Starting with the VueJS script code,the code is mostly similar to the other article I wrote on implementing a jokes list with Vue. Somessages is an empty list where the messages will be saved, input is linked to the textarea so it will have it’s content. send_blank default is false and I use it to check whether you’re trying to submit blank content.

placeholder will just have the placeholder content of the textarea.

add_message linked to the send button icon will add the message you types to the messages list and VueJS reactiveness will add it to the page. Also by setting input to a blank string I clear the field. It also sends an ajax request to the server with the message and gets back a response with the same format as the prior input added to the messages list. It’s also added to the list and you get to view the response from Chatterbot.

check_content bound to the textarea with “on change” will check to see if you have no content in the textarea to undo an error message if you tried to send blank content. Note this triggers on the field losing focus not on typing.

To show also how it’s bound to the html, here’s the home.html template

It uses a for loop to loop over the messages, and depending on the message’s fields like user and chat_bot will assign some classes to the div. Also you can look at the textarea to see how the various bindings are added to the field. The base html just import the needed css and js files like bootstrap and VueJS.

And finally the views file has the home function which simply returns the template and get_response get’s the message, passes it to chattebot, get’s the response and send it back additionally with the chat_bot key set to true so it get’s the class for the chatbot appears on the right of the page.

Version 2 uses websockets and jQuery. Starting with the code for the socket connection in python

You can also watch a video I made on both Version 1 and 2

This imports and uses Chatterbot as I did in Version 1 the main difference is how I route it to work with websockets. This is websockets in python which is a package you’ll need to pip install (the requirements file has it listed).

The function chat_receiver now handles the socket connection done here in jQuery

And finally the html content that’s the same only now using jQuery