Receiving and processing an SMS with Twilio in Python

Question:

I’m learning python and as a project I’m trying to create a program that will recieve an SMS message, process it, and then depending on what is in that message, send back information.

I am using Twilio in python with Flask and ngrok to do all the SMS stuff, but I am still not sure how to actually receive an SMS as data that I can read and process, as there is no documentation that I can find on it. It would be great if someone could help me with this.

I already know how to receive and send SMS with Twilio, I just need to know how to get the precise message that was sent to my Twilio number.

Asked By: jaspar

||

Answers:

I believe you already know how to configure Twilio to hit your endpoint when a message comes in. If you configure at Twilio for a POST request, then the data passed to you from Twilio will be in request.form.

If you take a look at Twilio’s example here:
(https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-python)
indeed the example makes no use of the data that is coming in.

The modified code below shows some data that is available from the request (and you can write your code depending on what you’d like to do with it).

  • the number from where the message was sent request.form['From'],
  • your Twilio number request.form['To']
  • and the body of the message request.form['Body']


    from flask import Flask, request, redirect
    from twilio.twiml.messaging_response import MessagingResponse
    
    app = Flask(__name__)
    
    @app.route("/sms", methods=['POST'])
    def sms_reply():
        """Respond to incoming calls with a simple text message."""
        
        # Use this data in your application logic
        from_number = request.form['From']
        to_number = request.form['To']
        body = request.form['Body']
    
        # Start our TwiML response
        resp = MessagingResponse()
    
        # Add a message
        resp.message("The Robots are coming! Head for the hills!")
    
        return str(resp)
    
    if __name__ == "__main__":
        app.run(debug=True)


Some other parameters are also available in the request:

  • MessageSid
  • SmsSid
  • AccountSid
  • MessagingServiceSid
  • From
  • To
  • Body
  • NumMedia

Docs: (https://www.twilio.com/docs/sms/twiml#request-parameters)

Also you can find more examples if you google for "twilio blog python flask"

Answered By: Alex Baban

# Standard library import
import logging

# Third-party imports
from twilio.rest import Client
from decouple import config


# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = config("TWILIO_ACCOUNT_SID")
auth_token = config("TWILIO_AUTH_TOKEN")
client = Client(account_sid, auth_token)
twilio_number = config('TWILIO_NUMBER')

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Sending message logic through Twilio Messaging API
def send_message(to_number, body_text):
    try:
        message = client.messages.create(
            from_=f"whatsapp:{twilio_number}",
            body=body_text,
            to=f"whatsapp:{to_number}"
            )
        logger.info(f"Message sent to {to_number}: {message.body}")
    except Exception as e:
        logger.error(f"Error sending message to {to_number}: {e}")

Answered By: pavansai tadepalli
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.