Codementor Events

Using Twilio APIs- I: SMS texting

Published May 07, 2019

I used Twilio SMS API for my web app which sends text notifications to prompt users to fill new information in their dashboards when a particular event has been updated in the database. The app is written in Python Flask and uses a Postgres relational database. Here is a link to the github code for the app. The following part of the code and explanation specific to the Twilio SMS API can be found in module- send_twilio.py.

Twilio Python Helper library

To interact with Twilio API first a Twilio Helper Library needs to be downloaded. I use the python version of the library- twilio-python which is a module for using the Twilio REST API and generating valid TwiML for SMS interaction with users. The most recent version of the library can be found on PyPi and it can be installed using the command-

pip install twilio

The following import command can be used inside your python module to access the library.

from twilio.rest import TwilioRestClient 

Twilio Registration

To use Twilio SMS APIs to send messages, you need to sign up for a Twilio account and purchase a Twilio phone number. On signing up an SID and Auth Token is assigned which can be used in your python module to login to the Twilio server. I started with a free trial but later on bought a phone no with SMS capabilities. The prices are affordable for light use apps like mine which are not yet scaled to a large no of users.

ACCOUNT_SID = "AC85250cc80055bfd5dfe95eb9072eaa65"
AUTH_TOKEN = "8de0e1f992ca4f46499ec975a6d8c142"

#Twilio client is invoked to create an HTTP message
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

SMS notifications to my app users using Twilio API

Once your app has registered with Twilio, you will have an SID and token as above. Twilio provides APIs to allow third party apps to interface with the My app uses DB tables 'Users' and 'Events'- the Users table contains users phone noes which are to be notified in case of an event update and Events table contains information about event status (CREATED/UPDATED/DELETED) pertaining to different events for each user. A cron job is setup to run this module- an SMS scheduler which monitors the database for any updated events and sends a notification to the user to prompt for updating the event info. The scheduler sends a trigger msg to Twilio to send reminder SMSes to users whose events have expired prompting them to fill in information in their app dashboards.

SQL queries- SELECT and UPDATE are used to find users and update relevant events in the tables. If a Twilio request returns with a valid Sid (smsid returned by Twilio) the Sid is saved in a log file for future and the event status is updated to TWILIO_SMS_SENT.

#Twilio message schedule in the python module
def twilio_sms_scheduler():
        import random
        from random import randrange
        batchid = randrange(0,10000)
        
        marked_for_sms_events = models.Event.query.filter(and_(
                                             models.Event.status==STATUS_CREATED,
                                   models.Event.datetime<=datetime.datetime.now(),                           models.Event.batchid==0)).update(dict(batchid=batchid))
        models.db.session.commit()
        
        sms_events = models.Event.query.join(models.User).filter(and_(
                                               models.Event.batchid==batchid,                                      models.Event.userid==models.User.userid)).all()                                           
#An HTTP POST message is sent to /2019-04-01/Accounts/{AccountsSid}/Message             for event in sms_events:
            if event.user.phone: 
                      message = client.messages.create(
                      to=event.user.phone, from_="+19193733763", 
                      body="This is a reminder to update the event desc here-     
                      http://www.satiapp.com/twilio/encrypted_eventid", 
                      statuscallback="http://satiapp.com/twiliosmsresponses")

If valid Sid is received for the SMS from Twilio, update event status.

      if (message.sid is not None):     
                         models.Event.query.filter_by(eventid=event.eventid).
                         update(dict(status=SATIAPP_STATUS_SENT_SMS))
                         models.db.session.commit()
              
      return None
      
Discover and read more posts from Arch B
get started
post commentsBe the first to share your opinion
Show more replies