Chatbots are gaining popularity as a means for businesses to interact with their customers. Domino’s Pizza is one such company that has used a chatbot to improve its customer service. In this article, we’ll look at how to use Python to create a chatbot for Domino’s Pizza.
Tools and Technologies Used:
The chatbot for Domino’s Pizza will be built using Python. The libraries used in this project include:
- Flask: A web framework used for developing web applications.
- Twilio: A communication platform used for messaging, voice, and video calls.
- Requests: A library used to make HTTP requests.
Model Architecture:
The Domino’s Pizza chatbot will be built with a combination of natural language processing (NLP) and machine learning techniques. NLP will be used by the chatbot to understand customer queries and respond appropriately. The chatbot will be trained using the machine learning algorithm to recognise patterns in customer queries and provide appropriate responses.
Stepwise Implementation:
Step 1: Setting up a virtual environment
The first step is to set up a virtual environment to avoid dependency conflicts with other Python projects. To set up a virtual environment, run the following commands in your terminal:
pip install virtualenv virtualenv chatbot_env source chatbot_env/bin/activate
Step 2: Installing the necessary libraries
The next step is to install the libraries required for this project. Run the following command in your terminal:
pip install flask twilio requests
Step 3: Creating a Flask app
The next step is to create a Flask app. Create a new file called `app.py` and add the following code:
from flask import Flask, request
import twilio.twiml
app = Flask(__name__)
@app .route( "/" )
def hello():
return "Hello, World!"
if __name__ = = "__main__" :
app.run(debug = True )
|
Step 4: Creating a Twilio account
The next action is to open a Twilio account. With the help of the communication platform Twilio, you can make and receive voice, text, and video conversations. Visit Twilio’s website and register for a free account to get started.
Starting Over
Step 4.1: Create a Twilio account with the Twilio WhatsApp API.
Go to this link and click the signup and start building button, then enter your information and verify your email address and mobile number.
After logging in, select the Develop option from the left menu, then the Messaging subject, then the Try it out option, and finally Send a WhatsApp message. This will start taking you to a new page on which you can configure the WhatsApp Sandbox.
Step 4.2: Configure the Twilio WhatsApp Sandbox by sending a message to the following WhatsApp number with the secret unique security code:
Send the code in the format shown below to +14155238886.
secret code : join <secret-code>
Step 5: Adding Twilio credentials to the Flask app
After creating a Twilio account, you need to add your Twilio credentials to the Flask app. Open the `app.py` file and add the following code:
account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'
client = Client(account_sid, auth_token)
|
Getting Started with Twilio Credentials
Step 5.1: Go to your Twilio account Console and copy the Twilio credentials (i.e., Your Account SID, Your Auth Token)
Step 6: Setting up the chatbot
The next step is to set up the chatbot. Create a new file called `chatbot.py` and add the following code:
import requests
def get_response(query):
headers = {
'content-type' : 'application/json' ,
'Ocp-Apim-Subscription-Key' : 'YOUR_API_KEY'
}
data = {
'Text' : query
}
response = requests.post(url, headers = headers, json = data)
response_data = response.json()
return response_data[ 'Response' ]
|
This function sends a query to the Domino’s Pizza API and returns the response.
Getting started with how to get API Key in Twilio:
Step 6.1: Go to your Twilio account Console and select Account tab and then select API Keys and tokens
Step 6.2: Select create API Key
Step 6.3: Enter the API Key details and click on create API Key
Step 6.4: Copy the API Key and paste to ‘Ocp-Apim-Subscription-Key’: ‘YOUR_API_KEY’
Step 7: Updating the Flask app
The Flask app has to be updated in order to handle incoming Twilio messages and respond with the proper messages. Add the following code to the `app.py` file by opening it:
incoming_msg = request.values.get( 'Body' , '').lower()
resp = MessagingResponse()
msg = resp.message()
response_text = get_response(incoming_msg)
msg.body(response_text) return str (resp)
|
Twilio will use the route ‘/sms’ defined by this code to relay incoming messages to your Flask application. After extracting the message text from the incoming message and sending it to the `get_response` function to obtain the necessary response, the `sms+reply` function then replies to the user using Twilio’s Messaging Response class.
Step 8: Testing the chatbot
It’s time to put the chatbot to the test now that it’s been built. To test the chatbot, launch the Flask app in your terminal by typing the following command:
python app.py
This will launch the Flask application and make it accessible at http://localhost:5000.
Create a Twilio sandbox to receive messages next. To do so, open the Twilio console and navigate to the “Messaging” section. Then, under “Phone Numbers,” click “Try it out”. To generate a sandbox number, follow the steps below.
Finally, test the chatbot by sending a message to the Twilio sandbox number. You should receive a response from the chatbot containing the necessary information.
Examples of Chatbot Template:
The following is the final code template for the chatbot with comments:
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
import requests
# Initialize the Flask app app = Flask(__name__)
# Set up the Twilio credentials account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'
client = Client(account_sid, auth_token)
# Define a function to send a query to the Domino's API and return the response def get_response(query):
headers = {
'content-type' : 'application/json' ,
'Ocp-Apim-Subscription-Key' : 'YOUR_API_KEY'
}
data = {
'Text' : query
}
response = requests.post(url, headers = headers, json = data)
response_data = response.json()
return response_data[ 'Response' ]
# Define a route for the Twilio sandbox to send incoming messages to @app .route( "/sms" , methods = [ 'POST' ])
def sms_reply():
# Get the message body from the incoming message
incoming_msg = request.values.get( 'Body' , '').lower()
# Initialize a response object
resp = MessagingResponse()
msg = resp.message()
# Get the response from the chatbot and send it back to the user
response_text = get_response(incoming_msg)
msg.body(response_text)
return str (resp)
# Run the Flask app if __name__ = = "__main__" :
app.run(debug = True )
|
In the preceding code, we import the required libraries before starting the Flask app. The Twilio credentials are then configured, and a function is defined to send queries to Domino’s API.
The Twilio sandbox is then directed to a route that we define. The ‘sms_reply’ function extracts the message text from the incoming message, passes it to the ‘get_response’ function to retrieve the appropriate response, and then responds to the user using Twilio’s Messaging Response class.
Finally, we run the Flask app and point it to ‘http://localhost:5000‘.
Final Code:
from flask import Flask, request
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
# Twilio account details account_sid = 'ACe8ac186fa6a777d354417ce321deb2ce'
auth_token = '6dd08139c232f4aded689e091b431e22'
client = Client(account_sid, auth_token)
# Flask app app = Flask(__name__)
# Dictionary to store user's order order = {}
# Dictionary to store menu items menu_items = {
"1" : { "name" : "Pepperoni Pizza" , "price" : 12.99 },
"2" : { "name" : "Hawaiian Pizza" , "price" : 14.99 },
"3" : { "name" : "Meat Lovers Pizza" , "price" : 16.99 }
} @app .route( "/" , methods = [ "POST" ])
def sms_reply():
"""Respond to incoming messages with a friendly SMS."""
# Get the incoming message
incoming_msg = request.values.get( "Body" , "").lower()
resp = MessagingResponse()
# Check for specific keywords and respond accordingly
if "menu" in incoming_msg:
# Send back a list of menu items
msg = "Here are our menu items: \n\n1. Pepperoni Pizza - $12.99 \n2."
+ "Hawaiian Pizza - $14.99 \n3. Meat Lovers Pizza - $16.99"
resp.message(msg)
elif "order" in incoming_msg:
# Start the order process
order.clear() # Clear any previous orders
resp.message(
"Great! Let's get started with your order."
+ " What type of pizza would you like? " +
"(Please reply with the number)" )
elif "1" in incoming_msg:
# Add pepperoni pizza to the order
order[ "Pepperoni Pizza" ] = { "price" : 12.99 , "quantity" : 0 }
resp.message(
"You've selected Pepperoni Pizza. How many would you like?" )
elif "2" in incoming_msg:
# Add hawaiian pizza to the order
order[ "Hawaiian Pizza" ] = { "price" : 14.99 , "quantity" : 0 }
resp.message(
"You've selected Hawaiian Pizza. How many would you like?" )
elif "3" in incoming_msg:
# Add meat lovers pizza to the order
order[ "Meat Lovers Pizza" ] = { "price" : 16.99 , "quantity" : 0 }
resp.message(
"You've selected Meat Lovers Pizza. How many would you like?" )
elif "done" in incoming_msg:
# Check if there are any items in the order
if not order:
resp.message(
"You haven't ordered anything yet."
+ " Please reply with 'order' to start your order." )
else :
# Complete the order and send the final message
total = sum ([item[ "price" ] * item[ "quantity" ]
for item in order.values()])
order_summary = "\n" .join(
[f "{k}: {v['quantity']}" for k, v in order.items()])
msg = f "Thanks for your order!"
+ "Here's a summary:\n{order_summary}\nTotal: ${total:.2f}"
resp.message(msg)
# Reset the order dictionary for the next customer
order.clear()
elif any (pizza in incoming_msg for pizza in [ "pepperoni" , "hawaiian" , "meat lovers" ]):
# Check if the user mentioned a pizza by name instead of number
if "pepperoni" in incoming_msg:
pizza_number = "1"
pizza_name = "Pepperoni Pizza"
pizza_price = 12.99
elif "hawaiian" in incoming_msg:
pizza_number = "2"
pizza_name = "Hawaiian Pizza"
pizza_price = 14.99
elif "meat lovers" in incoming_msg:
pizza_number = "3"
pizza_name = "Meat Lovers Pizza"
pizza_price = 16.99
# Add the pizza to the order
order[pizza_name] = { "price" : pizza_price, "quantity" : 0 }
resp.message(
f "You've selected {pizza_name}. How many would you like to order?" )
elif incoming_msg.isdigit() and int (incoming_msg) in range ( 1 , 4 ):
# Check if the user has already added the pizza to the order
pizza_number = int (incoming_msg)
pizza_name, pizza_price = menu_items[pizza_number - 1 ]
if pizza_name in order:
resp.message(
f "You've already added {pizza_name} to your order"
+ f "How many {pizza_name}"
+ "would you like?" )
else :
# Add the pizza to the order
order[pizza_name] = { "price" : pizza_price, "quantity" : 0 }
resp.message(
f "You've selected {pizza_name}. How many would you like to order?" )
elif incoming_msg.isdigit():
# Check if the user has already selected a pizza
if not order:
resp.message( "Please select a pizza from the menu first." )
else :
# Update the quantity of the selected pizza
pizza_name = list (order.keys())[ 0 ]
order[pizza_name][ "quantity" ] = int (incoming_msg)
# Check if the user wants to add another pizza or complete the order
msg = "You've ordered:\n"
for pizza, details in order.items():
quantity = details[ "quantity" ]
price = details[ "price" ]
msg + = f "{quantity} {pizza} - ${price:.2f} each\n"
msg + = "\nReply with 'menu' "
+ "to add another pizza or 'done' to complete your order."
resp.message(msg)
elif "done" in incoming_msg:
# Complete the order and send the final message
total = sum ([item[ "price" ] * item[ "quantity" ]
for item in order.values()])
order_summary = "\n" .join(
[f "{k}: {v['quantity']}" for k, v in order.items()])
msg = f "Thanks for your order!"
+ "Here's a summary:\n{order_summary}\nTotal: ${total:.2f}"
resp.message(msg)
# Reset the order dictionary for the next customer
order.clear()
else :
# Handle any other messages
resp.message( "I'm sorry, I didn't understand your message. "
+ "Please reply with 'menu' to see our menu, 'order' to start your order,"
+ " or done to complete your order." )
return str (resp)
if __name__ = = "__main__" :
app.run(debug = True )
|
This is a Python program that uses the Flask web framework and the Twilio messaging API to create a simple pizza ordering system. The program is designed to run as a web service that receives customer messages via the Twilio API and sends automated responses based on the message content.
The program generates a Flask application and configures routes to handle incoming messages. It also generates a dictionary for storing menu items and another for storing the customer’s order.
The program responds to specific keywords in the message from the customer. If a customer sends the word “menu,” the program will respond with a list of menu items. If the customer sends an “order,” the program will begin the order process by asking what type of pizza they want to order. The program will then add the chosen pizza to the order and ask the customer how many they want. After selecting all of their pizzas and quantities, the customer can send “done” to complete the order. The program will calculate the total cost of the order and send it to the customer as a summary.
The program also handles variations in the messages of the customers. For example, if a customer sends the name of a pizza rather than the number, the program will still place the order for the correct pizza. If the customer sends a number that does not correspond to a pizza, the program will respond with an error message.
Output:
Terminal Screen
WhatsApp Bot