Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
Instagram Bot using Python and InstaPy
Next article icon

Dominos Chatbot using Python

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Flask: A web framework used for developing web applications.
  2. Twilio: A communication platform used for messaging, voice, and video calls.
  3. 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:

Python3
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.

Sign-up

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.

Setup Whatsapp messaging

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>
Setup Sandbox

 

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:

Python3
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)

Getting Twilio Credentials

 

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:

Python3
import requests   def get_response(query):     url = "https://api.dominos.com.au/api/OnlineOrdering/v2/Store/"     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 

Go to API

Step 6.2: Select create API Key

Create API

Step 6.3: Enter the API Key details and click on create API Key

New API

Step 6.4: Copy the API Key and paste to 'Ocp-Apim-Subscription-Key': 'YOUR_API_KEY'  

COPY API

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:

Python3
    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:

Python3
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):     url = "https://api.dominos.com.au/api/OnlineOrdering/v2/Store/"     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:

Python3
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


Next Article
Instagram Bot using Python and InstaPy
author
vikasharma005
Improve
Article Tags :
  • Python
  • Python Flask
Practice Tags :
  • python

Similar Reads

  • Deploy a Chatbot using TensorFlow in Python
    In this article, you'll learn how to deploy a Chatbot using Tensorflow. A Chatbot is basically a bot (a program) that talks and responds to various questions just like a human would. We'll be using a number of Python modules to do this.  This article is divided into two sections:  First, we'll train
    9 min read
  • Instagram Bot using Python and InstaPy
    In this article, we will design a simple fun project “Instagram Bot” using Python and InstaPy. As beginners want to do some extra and learning small projects so that it will help in building big future projects. Now, this is the time to learn some new projects and a better future. This python projec
    3 min read
  • Build a QnA ChatBot using Gemini Pro
    A chatbot is a computer program designed to simulate human conversation, usually through text or voice interactions. They use natural language processing (NLP) and machine learning algorithms to understand and respond to user queries, providing a personalized experience. Gemini is an AI model made b
    5 min read
  • Build an AI Chatbot in Python using Cohere API
    A chatbot is a technology that is made to mimic human-user communication. It makes use of machine learning, natural language processing (NLP), and artificial intelligence (AI) techniques to comprehend and react in a conversational way to user inquiries or cues. In this article, we will be developing
    4 min read
  • How to Use ChatGPT API in Python?
    ChatGPT and its inevitable applications. Day by Day everything around us seems to be getting automated by several AI models using different AI and Machine learning techniques and Chatbot with Python , there are numerous uses of Chat GPT and one of its useful applications we will be discussing today.
    6 min read
  • Voice Assistant for Movies using Python
    In this article, we will see how a voice assistant can be made for searching for movies or films. After giving input as movie name in audio format and it will give the information about that movie in audio format as well. As we know the greatest searching website for movies is IMDb. IMDb is an onlin
    6 min read
  • Joke App using Bottle Framework - Python
    There are many frameworks in python which allows you to create webpage like bottle, flask, django. In this article you will learn how to create simple app bottle.Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no depende
    2 min read
  • How to Make a Chatbot in Python using Chatterbot Module?
    A ChatBot is basically a computer program that conducts conversation between a user and a computer through auditory or textual methods. It works as a real-world conversational partner. ChatterBot is a library in python which generates a response to user input. It used a number of machine learning al
    4 min read
  • Simple Chat Room using Python
    This article demonstrates - How to set up a simple Chat Room server and allow multiple clients to connect to it using a client-side script. The code uses the concept of sockets and threading. Socket programming Sockets can be thought of as endpoints in a communication channel that is bi-directional
    8 min read
  • Python A-Z Quick Notes
    Python is a general-purpose, high-level, interpreted programming language that supports multiple programming paradigms, including procedural, object-oriented, and functional programming, and is widely used among the developers’ community. Python was mainly developed for emphasis on code readability,
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences