Kevin
Kevin

Reputation: 21

How to get SMS sender info using python?

I'm using Twilio and Django for an SMS application (I started learning Python yesterday, be gentle).

Here's what I need help with: When Twilio sends an incoming SMS message to my URL, I want my app to automatically add the incoming phone number, date/time, and incoming message to some lists. How do I do that?

Thanks!

Upvotes: 2

Views: 1444

Answers (2)

mcotton
mcotton

Reputation: 844

Twilio sends it as the 'From' parameter when it requests your URL. The documentation is at: http://www.twilio.com/docs/api/twiml/sms/message

It will be similar to this code, I wrote this in webapp with python (not Django).

class MainHandler(webapp.RequestHandler):  

  def get(self):
    model = Storage()
    from = self.request.get("From")
    if from is not '':
      model.sms_from = self.request.get("From")
      model.sms_body = self.request.get("Body")
      model.put()

    models = Storage.all()

    for i in models:
      self.response.out.write(i.sms_from + ' ' + i.sms_body +'<br>')

UPDATE:

When I get my phone and send a text to xxx-xxx-xxxx, twilio will receive that text and then make a request to the URL I configured.

From that point it looks exactly the same as a request from a web browser.

This question will help you with the specifics with Django Capturing url parameters in request.GET

There should be all the parameters you need from the sender.

Upvotes: 2

Kirsten Jones
Kirsten Jones

Reputation: 2706

I just wrote a sample app using Twilio and Django on GitHub, but here's the specific answer you're looking for.

For this example I'm using the '/reply/' URL on my server (and have told Twilio that's where to POST to)

In urls.py you're just going to do a standard mapping: url(r'^reply', 'twilio_sms.views.sms_reply'),

Here's a really basic response to the user, responding with what the Twilio server expects. def sms_reply(request): if request.method == 'POST': params = request.POST phone = re.sub('+1','',params['From'])

    response_message =  '<?xml version="1.0" encoding="UTF-8">'
    response_message += '<Response><Sms>Thanks for your text!</Sms></Response>'
    return HttpResponse(response_message)

In my code I actually build the XML response using a library, which I suggest in general, but for a code sample it's too much information.

Upvotes: 0

Related Questions