[TUTORIAL] How to Build an Echo SMS Server Using Twilio API


twilio
Twilio is a SMS/Voice gateway that allows us to turn our app easily into a voice and SMS app without dealing with the service provider.
For instance, when a user text messages or calls the Twilio number, Twilio will make a request to your application and interact with the user based on the output of your application.

Here are the necessary steps to get started with Twilio:

1. Install Python
http://python.org/download/

2. Install one of the Python Frameworks (here we use Flask)
http://flask.pocoo.org/

3. Install the API Libraries(Twilio-Python) for Python
https://github.com/twilio/twilio-python#readme

4. Sign up for a Twilio account
http://www.twilio.com

5. Create a smsEcho.py file
Import the libraries and initiate the Twilio API.

from flask import Flask, request, redirect, session
from twilio.rest import TwilioRestClient
import twilio.twiml
import time
app = Flask(__name__)
@app.route("/")
def smsEcho():
    client = TwilioRestClient(SID,TOKEN)
    return "HelloWorld"
if __name__ == "__main__":
    app.run(debug=True)

6. Run Python and you should see HelloWorld on http://localhost:5000

python smsEcho.py

6. Config the API by Setting the Number, SID, TOKEN which can be found on the main page after you login to Twilio
SERVER_NUMBER = “YOUR NUMBER”
SID = “YOUR SID”
TOKEN = “YOUR TOKEN”

7. Obtain the sender’s number and the content.

clientNumber = request.args.get('From');
clientTextContent = request.args.get('Body').lower()

8. Now, we can echo back the message.

client.sms.messages.create(to=clientNumber, from_=SERVER_NUMBER, body= clientTextContent)

9. The source code is shown as below.

from flask import Flask, request, redirect, session
import twilio.twiml
from twilio.rest import TwilioRestClient
import time
SERVER_NUMBER = "YOUR NUMBER"
SID = "YOUR SID"
TOKEN = "YOUR TOKEN"
app = Flask(__name__)
@app.route("/")
def smsEcho():
     client = TwilioRestClient(SID,TOKEN)
	clientNumber = request.args.get('From');
	clientTextContent = request.args.get('Body').lower()
	client.sms.messages.create(to=clientNumber, from_=SERVER_NUMBER, body= clientTextContent)
    return "HelloWorld"
if __name__ == "__main__":
    app.run(debug=True)
Technology Tutorials:

Leave a comment