Creating an automated menu system can enhance customer service for small businesses. In this article, we will explore how to build a simple menu system using Twilio, Python, and an SQLite database. We will set up a webhook that interacts with Twilio to read and process user input. Each menu option will be connected to a cell phone number stored in the SQLite database. Finally, we will discuss how to host the application on a VPS server.
Requirements
To get started, you’ll need:
- A Twilio account
- Python 3 installed
- An SQLite database
- A VPS server (e.g., DigitalOcean or AWS)
Setting Up the SQLite Database
First, create an SQLite database to store cell phone numbers. This database will be used to look up phone numbers based on the menu options.
import sqlite3
# Create a database and table
conn = sqlite3.connect('menu.db')
cursor = conn.cursor()
# Create a table to store menu options and phone numbers
cursor.execute('''
CREATE TABLE IF NOT EXISTS menu_options (
id INTEGER PRIMARY KEY,
option INTEGER UNIQUE,
phone_number TEXT NOT NULL
)
''')
# Insert some sample data
cursor.execute('INSERT OR IGNORE INTO menu_options (option, phone_number) VALUES (?, ?)', (1, '+1234567890'))
cursor.execute('INSERT OR IGNORE INTO menu_options (option, phone_number) VALUES (?, ?)', (2, '+0987654321'))
cursor.execute('INSERT OR IGNORE INTO menu_options (option, phone_number) VALUES (?, ?)', (3, '+1123456789'))
conn.commit()
conn.close()
Setting Up the Twilio Webhook
Twilio uses webhooks to communicate with your server. When someone interacts with your Twilio number, it will send an HTTP request to the webhook URL you specify. Let’s create a Python Flask application to handle these requests.
- Install Flask and Twilio Libraries
pip install Flask twilio
2. Create a Flask Application
Create a file named app.py
and add the following code:
from flask import Flask, request, jsonify
from twilio.twiml.voice_response import VoiceResponse
import sqlite3
app = Flask(__name__)
# Function to get phone number based on menu option
def get_phone_number(option):
conn = sqlite3.connect('menu.db')
cursor = conn.cursor()
cursor.execute('SELECT phone_number FROM menu_options WHERE option = ?', (option,))
result = cursor.fetchone()
conn.close()
return result[0] if result else None
# Webhook to handle incoming calls
@app.route('/voice', methods=['POST'])
def voice():
response = VoiceResponse()
response.say("Welcome to our menu system. Press 1 for Sales, Press 2 for Support, Press 3 for Billing.")
response.gather(
action='/handle_key',
num_digits=1,
timeout=5
)
return str(response)
# Webhook to handle key presses
@app.route('/handle_key', methods=['POST'])
def handle_key():
selected_option = request.form.get('Digits')
response = VoiceResponse()
if selected_option:
phone_number = get_phone_number(int(selected_option))
if phone_number:
response.dial(phone_number)
response.say("Connecting you now.")
else:
response.say("Invalid option. Please try again.")
else:
response.say("No input received. Goodbye!")
return str(response)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
This code creates a simple menu. When someone calls your Twilio number, they are prompted to press 1, 2, or 3. Based on their input, the application will look up the phone number from the database and connect the call.
Configuring Twilio
- Go to your Twilio Console.
- Navigate to Phone Numbers and select the number you want to use.
- In the Voice & Fax section, set the Webhook URL to
http://your-server-ip:5000/voice
. - Save the configuration.
Hosting on a VPS Server
To run your Flask application on a VPS, follow these steps:
- Log in to your VPS using SSH.
ssh user@your-server-ip
2. Transfer your files to the server using SCP or any other method.
scp app.py menu.db user@your-server-ip:~
3. Install Python and required libraries on the server.
sudo apt update
sudo apt install python3 python3-pip
pip3 install Flask twilio
4. Run the Flask Application
python3 app.py
5. To keep the application running in the background, use a process manager like screen
or tmux
.
screen -S menu-app
python3 app.py
Press Ctrl + A
, then D
to detach the screen session.
You’re done — with this setup, you now have a simple menu system for your small business. When someone calls your Twilio number, they will be able to navigate through the menu options. Each option connects them to a different phone number stored in your SQLite database. This is a basic example, but you can expand it to include more complex logic, additional options, or even text message responses.
Thank you for following along with this tutorial. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!
You can find the same tutorial on Medium.com.