Building a Twilio Softphone With JavaScript, HTML, and Flask
Build a softphone using Twilio with JavaScript and HTML that has some amazing features, writing less code by replacing it with existing methods available.
Join the DZone community and get the full member experience.
Join For FreeBeing able to dial and receive calls right in our web browser has a huge value proposition today given the digital era we find ourselves living in. Whether you're creating a customer service dashboard or simply trying to add voice communication to your application, building a softphone is an excellent example of leveraging modern web technologies. In this article, I will show you how to build a softphone using Twilio with just plain JavaScript and HTML that has some amazing features, but writing less code by replacing it with existing methods available.
Prerequisites
First things first, make sure you have the following:
- Foundational knowledge in HTML, JavaScript, and Python
- You will need a Twilio account.
- Python 3.6 or later is installed on your computer
- Flask (Uses one of the lightest and simplest forms of web development framework for Python)
Step 1: Setting Up Python Flask Backend
1. Install Flask and Twilio Python Library
First, create a virtual environment and install Flask and the Twilio Python helper library:
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install Flask twilio
2. Create the Flask App
Create a file named app.py and configure the skeleton Flask application:
from flask import Flask, render_template, request, jsonify
from twilio.twiml.voice_response import VoiceResponse
from twilio.rest import Client
app = Flask(__name__)
# Your Twilio credentials
twilio_account_sid = 'your_twilio_account_sid'
twilio_auth_token = 'your_authenticatoin_token'
twilio_client = Client(twilio_account_si, twilio_auth_toke)
@app.route('/')
def index(): return render_template('index.html')
@app.route('/voice', methods=['POST'])
def voice():
response = VoiceResponse()
response.say('Hello, you are now connected!')
response.dial('+1234567890') # Replace with a valid phone number
return str(response)
@app.route('/token', methods=['POST'])
def token(): # Generate a Twilio capability token (for JS client)
# Example implementation will be added here
if __name__ == '__main__': app.run(debug=True)
This creates a base Flask application with a route for the home page, and a Twilio voice route to handle calls.
Step 2: Creating the HTML Frontend
1. Basic HTML Structure
Create a file named templates/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Softphone</title>
</head>
<body>
<h1>Twilio Softphone</h1>
<button id="callButton">Call</button>
<button id="hangupButton" disabled>Hang Up</button>
</body>
</html>
This is just a very basic HTML structure with two buttons to call and to hang up.
Step 3: Adding JavaScript To Handle Calls
1. JavaScript File for Handling Calls
Create a file named static/js/softphone.js
:
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
let device;
fetch('/token', {
method: 'POST'
}).then(response => response.json())
.then(data => {
Twilio.Device.setup(data.token);
});
Twilio.Device.ready(function() {
callButton.disabled = false;
});
callButton.addEventListener('click', () => {
const params = {
To: 'client:someone'
};
device = Twilio.Device.connect(params);
hangupButton.disabled = false;
callButton.disabled = true;
});
hangupButton.addEventListener('click', () => {
device.disconnectAll();
hangupButton.disabled = true;
callButton.disabled = false;
});
Twilio.Device.disconnect(function() {
hangupButton.disabled = true;
callButton.disabled = false;
});
This script sets up a Twilio client, handles the events for when the call is connecting, and when it is disconnecting, updates the UI accordingly.
Step 4: Implementing the Token Generation Endpoint
1. Generating a Twilio Token
Update the /token
route in app.py
to generate a token:
from twilio.jwt.client import ClientCapabilityToken
@app.route('/token', methods=['POST'])
def token():
capability = ClientCapabilityToken(account_sid, auth_token)
capability.allow_client_incoming('someone')
capability.allow_client_outgoing('your_twilio_app_sid')
token = capability.to_jwt()
return jsonify({'token': token.decode('utf-8')})
Replace 'your_twilio_app_sid'
with your actual Twilio Application SID. This endpoint will provide the JavaScript client with the necessary token to authenticate with Twilio.
Step 5: Running and Testing Your Softphone
1. Run Your Flask Application
Start your Flask app:
flask run
Navigate to http://localhost:5000
in your browser. You should see your softphone interface.
2. Test the Call Functionality
Click the "Call" button to initiate a call . You can easily alter the logic to dial different numbers or connect to specific Twilio clients.
Opinions expressed by DZone contributors are their own.
Comments