How to Integrate Twilio in Django
Are you familiar with Twilio? If you aren’t, Twilio is a cloud communications platform, it lets developers add voice, video, and SMS messaging in their app.
Very convenient no? Since you won’t have to be on the phone 24/7 just to check for messages and send replies, replies now can be programmed, can make calls through your app, and add authentication. Remember when some services let you input your number and sends a code for verification, Twilio has that.
Twilio offers several functionalities, here are some of them:
Voice
API and SDKs to build calling capabilities within web and mobile apps. Connect to landlines, mobile devices or even WebRTC clients to make calls from apps or power multinational call centers.
Video
Real-time video infrastructure and SDKs to embed video collaboration and context-sharing into your web or mobile app. A global infrastructure that handles signaling, registration, and media relay.
Messaging
API and SDKs to send and receive SMS, MMS, and IP messages globally from your web and mobile app and use intelligent delivery features to ensure messages get through.
Authentication
Two-factor authentication service to strengthen — and even replace — traditional username and password login for websites, SaaS products, and mobile apps.
Am I keeping you interested? Let’s try sending a text using Twilio service. Well, let’s get started.
To get started with using Twilio, we will have to get a Twilio number. We’ll have to sign up, sign up here.
Just signup with Twilio normally like any other signups out there. Twilio will ask for your number and will send a code for verification. Check the option if you don’t want Twilio contacting you in your number. Then, done!
Next step is getting ourselves a Twilio number.
Twilio will provide you with a default one and you’ll have the option to accept it or look for another.
In my case, I had to look for another. It seems Twilio doesn’t support phone numbers from the Philippines that has SMS and voice capability. Number from Philippines only offer the voice(calls!) functionality but might change in the future.
There is a workaround for this situation though. We’ll have to get an international number. Twilio provides us a list of countries that is labeled with their available capabilities: domestic only, mobile or local, voice, and sms, take your pick. But for this blog I’m gonna pick a UK number, since it allows us to use SMS and voice functionality and it is a not a domestic only number, means it can send texts and call anywhere. This is a free trial tho which has limited usage and for development purposes only. Look up their page for their rates.
Go to Buy a Number tab in your dashboard, and search for a number(In my sample, I’m gonna use a UK number!) Don’t worry this is free IF for development purposes only.
Now we have our number, we’ll create a sample project that receives and responds to a text message!
First let’s set up our environment, to setup our virtual environment:
virtualenv {{name of virtualenv folder}}
Install dependencies but let’s not forget to activate our virtualenv:
source {{name of virtualenv folder}}/bin/activate
then, we install Django and Twilio:
pip install Django==1.11.5 twilio==6.7.0
After installing our dependencies, now let’s create Django project:
django-admin startproject SMSProject
Create an app for our sms function:
python manage.py startapp sms
Open our view in sms/views.py and add the following code:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exemptfrom twilio.twiml.messaging_response import MessagingResponse@csrf_exempt
def sms_response(request):
# Start our TwiML response
resp = MessagingResponse() # Add a text message
msg = resp.message(“Hello, you!”) return HttpResponse(str(resp))
Now add a route to this view by creating the file sms/urls.py and adding the following code:
from django.conf.urls import url
from . import viewsurlpatterns = [
url(r’^$’, views.sms_response, name=’sms’),
]
Next is to add our route for the sms app into the urls.py of our project, SMSProject. Navigate to SMSProject/urls.py and add this code:
from django.conf.urls import include, url
from django.contrib import adminurlpatterns = [
url(r’^sms/’, include(‘sms.urls’)),
url(r’^admin/’, admin.site.urls),
]
Let’s run our app by running the command in our terminal:
python manage.py runserver
But another thing, Twilio needs to see our app in the internet for it to manage our app, receive and send SMS. We can achieve this by running ngrok. Install ngrok if you don’t have it. You can see how to install it by visiting their site here.
We run ngrok by running this command in the terminal:
ngrok http 8000
Don’t forget to add ngrok to the ALLOWED_HOSTS in our settings. In our settings.py, make sure to add ‘.ngrok.io’ or simply ‘*’(asterisk) to allow all.
Let’s go back to running our app, copy the ngrok link, the https one, and append /sms/ in the url, since a while ago we created a route in our urls.py, so we add the ‘/sms/’ so the webhook will have access to our view.
It should look like this sample url:
https://{random-ngrok-url}/sms/
Look up the phone numbers in your Twilio dashboard, click on the number and it will direct you to the settings of that number. In the configure tab, scroll down and look for the messaging section and replace the default webhook, https://demo.twilio.com/welcome/sms/reply/.
Paste the URL in this section of the phone number configuration:
Let’s try sending a message to the number we picked, and TADAAA~!
We should receive a response containing “Hello, you!”. Rates apply depending on your service provider tho, so be careful you might use up your load!
This is just a simple app that receives and responds a message every time you send a message. It will always respond with a “Hello, you!”. Feel free to play with the code, and don’t forget to read their docs!
Photo by Jack Sharp on Unsplash