Build Your Own Smart Auto Response Bot with Python, Flask, Twilio SMS and the CleverBot API

September 17, 2018
Written by
Samantha Son
Contributor
Opinions expressed by Twilio contributors are their own

Cleverbot via SMS

If you are looking for a beginner Twilio project or a new texting buddy, this tutorial is for you!  Using the Twilio and CleverBot APIs you will make a Flask app that texts CleverBot, which is an AI you can chat with that learns from its conversations.

Getting Started

You will need a Twilio account with a phone number that can send and receive SMS.  In the console navigate to the "Buy a Number" page.  Make sure to check off SMS under capabilities and then hit the search button.  Any number will do, so feel free to pick one that speaks to you!

 

You will also need a CleverBot API key.  You will have to input payment information to use the API.  Luckily, the first month is free!  Just remember to cancel your subscription if you don't plan on using it after this project.

Next, you have to set up the environment for the project.  Create a project folder; mine is called cleverbot_text.  In this folder you will create a virtual environment.  This is important because it allows you to isolate your project so it does not interfere with others.

Create the virtual environment by using the virtualenv command which takes the name of the virtual environment as an argument.  Run the following in your terminal:

$  virtualenv cleverbot_text

If you have macOS or Linux, you can activate the virtual environment by running:

$  source cleverbot_text/bin/activate

For Windows users, run:

$  cleverbot_text\Scripts\activate

Now you need to install the libraries you will be using for the project in the virtual environment.  In your terminal, make sure you are in your project folder and type:

$  pip install twilio==6.14.9

$  pip install flask==1.0.2

$  pip install cleverwrap==0.2.3.6

Remember, every time you work on this project you must re-activate the virtual environment.  If you are interested, you can read more about setting up your development environment here.

The Code

Alright, now let’s get into some code!  In your folder, create your Flask app by making a file called app.py.  The first things you are going to add are (1) the libraries you will be using, (2) some Flask boilerplate, and (3) a line of code that will save your CleverBot API key.

Copy and paste the following into app.py. Be sure to copy and paste your own Cleverbot API key into the denoted field.

from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
from cleverwrap import CleverWrap


app = Flask(__name__)

cleverbot_API = CleverWrap("INSERT YOUR API KEY")


@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
    message_body = request.form['Body']
    cleverbot_response = cleverbot_API.say(message_body)

    resp = MessagingResponse()
    resp.message(cleverbot_response)
    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)

The first code block imports all of the libraries you need. After that, we have some Flask boilerplate and your Cleverbot API key. The next two lines define a route on your flask server that Twilio will call when your Twilio number receives a text message. Then, message_body = request.form['Body'] saves your text message from the request. The next line of code passes the message to CleverBot and saves its response to cleverbot_response. The following line of code creates a TwiML text message response object called resp. Its message is then set to CleverBot's response. The last two lines enable debug mode on Flask which gets the server to reload itself on code changes and shows debugging messages.

Running the Project

Next, you are going to use ngrok to create a public URL for your local server.  In other words, it creates a public address that the Twilio API can access.  Start by downloading it and unzipping it on your computer.  Then, in your terminal, type:

$ ./ngrok http 5000

Ngrok will generate a URL that forwards traffic to port 5000 on your localhost server.  Copy the URL found next to "Forwarding".  Keep in mind, the URL will change every time you run ngrok.

Go to your Twilio console and navigate to 'Manage Numbers'.  Click the number you will be using.  Scroll down until you see 'Messaging > A Message Comes In' and paste the ngrok URL into the field.  Be sure to add /sms to the end of the URL.

Now it is time to run your Flask app!  In your terminal enter the following commands:

$ export FLASK_APP=app.py
$ flask run

Windows users should use set instead of export.

You're Done!

At this point, you should be able to text the Twilio number you chose and receive replies from Cleverbot. I hope you enjoy your new texting buddy.  

If this piqued your interest in Cleverbot, you can check out this article on their website for more information. It gives you a full rundown of Cleverbot's history and how Cleverbot works. Good luck on adding Cleverbot to other projects you are working on!