You know how to receive and reply to incoming SMS messages. What if you receive an MMS message containing an image you'd like to download? Let's learn how we can grab that image and any other incoming MMS media using Django.
When Twilio receives a message for your phone number, it can make an HTTP call to a webhook that you create.
Twilio expects, at the very least, for your webhook to return a 200 OK
response if everything is peachy. Often, however, you will return some TwiML in your response as well. TwiML is just a set of XML commands telling Twilio how you'd like it to respond to your message. Rather than manually generating the XML, we'll use the twilio.twiml.messaging_response
module in the helper library to facilitate generating TwiML and the rest of the webhook plumbing.
To install the library, run:
pip install twilio
Add a new route in your urls.py file that handles incoming SMS requests.
1from django.conf import settings2from django.conf.urls import url3from django.conf.urls.static import static45from . import views67urlpatterns = [8url(r'^$', views.index, name='index'),9url(r'^config/$', views.config, name='config'),10url(r'^images/$', views.get_all_media, name='images'),11url(r'^images/(?P<filename>[0-9A-Za-z\.]{0,50})$', views.handle_delete_media_file, name='delete_image'),12url(r'^incoming/$', views.handle_incoming_message, name='incoming'),13]1415if settings.DEBUG:16urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
When Twilio calls your webhook, it sends a number of parameters about the message you just received. Most of these, such as the To
phone number, the From
phone number, and the Body
of the message are available as properties of the request body.
Since an MMS message can have multiple attachments, Twilio will send us form variables named MediaUrlX
, where X is a zero-based index. So, for example, the URL for the first media attachment will be in the MediaUrl0
parameter, the second in MediaUrl1
, and so on.
In order to handle a dynamic number of attachments, we pull the URLs out of the request body like this:
1import os2import sys3import logging4import mimetypes5import requests67from django.core import serializers8from django.http import HttpResponse, JsonResponse9from django.shortcuts import render10from django.views.decorators.csrf import csrf_exempt11from core.receive_mms import *121314logger = logging.getLogger(__name__)151617def index(request):18return render(request, 'receive_mms/index.html')192021def config(_):22return JsonResponse({'twilioPhoneNumber': os.getenv('TWILIO_NUMBER', '')})232425# /images/26def get_all_media(_):27return JsonResponse({'data': fetch_all_media()})282930# /images/:filename31@csrf_exempt32def handle_delete_media_file(_, filename=None):33try:34media_content, mime_type = delete_media_file(filename)35return HttpResponse(media_content, content_type=mime_type)36except MMSMedia.DoesNotExist as err:37logger.error(err)38return JsonResponse({39'status': False,40'message': 'Could not find any media file with name: {}'.format(filename)41}, status=404)424344# /incoming/45@csrf_exempt46def handle_incoming_message(request):47message_sid = request.POST.get('MessageSid', '')48from_number = request.POST.get('From', '')49num_media = int(request.POST.get('NumMedia', 0))5051media_files = [(request.POST.get("MediaUrl{}".format(i), ''),52request.POST.get("MediaContentType{}".format(i), ''))53for i in range(0, num_media)]5455response = reply_with_twiml_message(message_sid, from_number, num_media, media_files)56return HttpResponse(response, content_type='application/xml')
Attachments to MMS messages can be of many different file types. JPG and GIF images as well as MP4 and 3GP files are all common. Twilio handles the determination of the file type for you and you can get the standard mime type from the MediaContentTypeX
parameter. If you are expecting photos, then you will likely see a lot of attachments with the mime type image/jpeg
.
1import os2import mimetypes3import requests45from twilio.rest import Client6from twilio.twiml.messaging_response import MessagingResponse7from core.models import MMSMedia89# Python 2 and 3: alternative 410try:11from urllib.parse import urlparse12except ImportError:13from urlparse import urlparse141516def reply_with_twiml_message(message_sid, from_number, num_media, media_files):17if not from_number or not message_sid:18raise Exception('Please provide a From Number and a Message Sid')1920for (media_url, mime_type) in media_files:21file_extension = mimetypes.guess_extension(mime_type)22media_sid = os.path.basename(urlparse(media_url).path)23content = requests.get(media_url).text24filename = '{sid}{ext}'.format(sid=media_sid, ext=file_extension)2526mms_media = MMSMedia(27filename=filename,28mime_type=mime_type,29media_sid=media_sid,30message_sid=message_sid,31media_url=media_url,32content=content)33mms_media.save()3435response = MessagingResponse()36message = 'Send us an image!' if not num_media else 'Thanks for the {} images.'.format(num_media)37response.message(body=message, to=from_number, from_=os.getenv('TWILIO_NUMBER'))38return response394041def delete_media_file(filename=None):42m = MMSMedia.objects.get(filename=filename)43_twilio_client().api.messages(m.message_sid) \44.media(m.media_sid) \45.delete()46m.delete()4748return m.content, m.mime_type495051def fetch_all_media():52return map(lambda mms: mms.filename, MMSMedia.objects.all())535455def _twilio_client():56account_sid = os.getenv('TWILIO_ACCOUNT_SID')57auth_token = os.getenv('TWILIO_AUTH_TOKEN')5859return Client(account_sid, auth_token)
Depending on your use case, storing the URLs of the images (or videos or whatever) may be all you need. There are two key features to these URLs that make them very pliable for your use in your apps:
For example, if you are building a browser-based app that needs to display the images, all you need to do is drop an <img src="twilio url to your image">
tag into the page. If this works for you, then perhaps all you need is to store the URL in a database character field.
If you want to save the media attachments to a file, then you will need to make an HTTP request to the media URL and write the response stream to a file. If you need a unique filename, you can use the last part of the media URL. For example, suppose your media URL is the following:
https://api.twilio.com/2010-04-01/Accounts/ACxxxx/Messages/MMxxxx/Media/ME27be8a708784242c0daee207ff73db67
You can use that last part of the URL as a unique filename and look up the corresponding file extension for the mime type.
1import os2import mimetypes3import requests45from twilio.rest import Client6from twilio.twiml.messaging_response import MessagingResponse7from core.models import MMSMedia89# Python 2 and 3: alternative 410try:11from urllib.parse import urlparse12except ImportError:13from urlparse import urlparse141516def reply_with_twiml_message(message_sid, from_number, num_media, media_files):17if not from_number or not message_sid:18raise Exception('Please provide a From Number and a Message Sid')1920for (media_url, mime_type) in media_files:21file_extension = mimetypes.guess_extension(mime_type)22media_sid = os.path.basename(urlparse(media_url).path)23content = requests.get(media_url).text24filename = '{sid}{ext}'.format(sid=media_sid, ext=file_extension)2526mms_media = MMSMedia(27filename=filename,28mime_type=mime_type,29media_sid=media_sid,30message_sid=message_sid,31media_url=media_url,32content=content)33mms_media.save()3435response = MessagingResponse()36message = 'Send us an image!' if not num_media else 'Thanks for the {} images.'.format(num_media)37response.message(body=message, to=from_number, from_=os.getenv('TWILIO_NUMBER'))38return response394041def delete_media_file(filename=None):42m = MMSMedia.objects.get(filename=filename)43_twilio_client().api.messages(m.message_sid) \44.media(m.media_sid) \45.delete()46m.delete()4748return m.content, m.mime_type495051def fetch_all_media():52return map(lambda mms: mms.filename, MMSMedia.objects.all())535455def _twilio_client():56account_sid = os.getenv('TWILIO_ACCOUNT_SID')57auth_token = os.getenv('TWILIO_AUTH_TOKEN')5859return Client(account_sid, auth_token)
Another idea for these image files could be uploading them to a cloud storage service like Azure Blob Storage or Amazon S3. You could also save them to a database, if necessary. They're just regular files at this point - let your DevOps creativity run free! In this case, we are saving them to the public directory in order to serve them later.
If you are downloading the attachments and no longer need them to be stored by Twilio, you can delete them by sending an HTTP DELETE
request to the media URL. You will need to be authenticated to do this. The code below demonstrates how to make this request.
1import os2import mimetypes3import requests45from twilio.rest import Client6from twilio.twiml.messaging_response import MessagingResponse7from core.models import MMSMedia89# Python 2 and 3: alternative 410try:11from urllib.parse import urlparse12except ImportError:13from urlparse import urlparse141516def reply_with_twiml_message(message_sid, from_number, num_media, media_files):17if not from_number or not message_sid:18raise Exception('Please provide a From Number and a Message Sid')1920for (media_url, mime_type) in media_files:21file_extension = mimetypes.guess_extension(mime_type)22media_sid = os.path.basename(urlparse(media_url).path)23content = requests.get(media_url).text24filename = '{sid}{ext}'.format(sid=media_sid, ext=file_extension)2526mms_media = MMSMedia(27filename=filename,28mime_type=mime_type,29media_sid=media_sid,30message_sid=message_sid,31media_url=media_url,32content=content)33mms_media.save()3435response = MessagingResponse()36message = 'Send us an image!' if not num_media else 'Thanks for the {} images.'.format(num_media)37response.message(body=message, to=from_number, from_=os.getenv('TWILIO_NUMBER'))38return response394041def delete_media_file(filename=None):42m = MMSMedia.objects.get(filename=filename)43_twilio_client().api.messages(m.message_sid) \44.media(m.media_sid) \45.delete()46m.delete()4748return m.content, m.mime_type495051def fetch_all_media():52return map(lambda mms: mms.filename, MMSMedia.objects.all())535455def _twilio_client():56account_sid = os.getenv('TWILIO_ACCOUNT_SID')57auth_token = os.getenv('TWILIO_AUTH_TOKEN')5859return Client(account_sid, auth_token)
Twilio supports HTTP Basic and Digest Authentication. Authentication allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them. Learn more about HTTP authentication and validating incoming requests here.
All the code, in a complete working project, is available on GitHub. If you need to dig a bit deeper, you can head over to our API Reference and learn more about the Twilio webhook request and the REST API Media resource. Also, you will want to be aware of the pricing for storage of all the media files that you keep on Twilio's servers.
We'd love to hear what you build with this.