Skip to content

Instantly share code, notes, and snippets.

@pwilken
Created July 1, 2019 13:27
Show Gist options
  • Save pwilken/e184418c07f6ab92cad13df5cf3cfff7 to your computer and use it in GitHub Desktop.
Save pwilken/e184418c07f6ab92cad13df5cf3cfff7 to your computer and use it in GitHub Desktop.
Use Twilio API with lambda function over AWS API Gateway.
import base64
import json
import os
import urllib
from urllib import request, parse
TWILIO_SMS_URL = "https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json"
TWILIO_CALL_URL = "https://api.twilio.com/2010-04-01/Accounts/{}/Calls.json"
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")
def lambda_handler(event, context):
# json body
to_number = event['To']
from_number = event['From']
body = event['Body']
action = event['Action']
if not TWILIO_ACCOUNT_SID:
return "Unable to access Twilio Account SID."
elif not TWILIO_AUTH_TOKEN:
return "Unable to access Twilio Auth Token."
elif not to_number:
return "The function needs a 'To' number in the format +12023351493"
elif not from_number:
return "The function needs a 'From' number in the format +19732644156"
elif not body:
return "The function needs a 'Body' message to send."
elif not action:
return "The function needs a 'Action' SMS/WhatsApp/Call."
if action == "WHATSAPP":
from_number = "whatsapp:" + from_number
to_number = "whatsapp:" + to_number
# insert Twilio Account SID into the REST API URL
if action == "CALL":
populated_url = TWILIO_CALL_URL.format(TWILIO_ACCOUNT_SID)
post_params = {"To": to_number, "From": from_number, "Url": body}
else:
populated_url = TWILIO_SMS_URL.format(TWILIO_ACCOUNT_SID)
post_params = {"To": to_number, "From": from_number, "Body": body}
# encode the parameters for Python's urllib
data = parse.urlencode(post_params).encode()
req = request.Request(populated_url)
# add authentication header to request based on Account SID + Auth Token
authentication = "{}:{}".format(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
base64string = base64.b64encode(authentication.encode('utf-8'))
req.add_header("Authorization", "Basic %s" % base64string.decode('ascii'))
try:
# perform HTTP POST request
with request.urlopen(req, data) as f:
print("Twilio returned {}".format(str(f.read().decode('utf-8'))))
except Exception as e:
# something went wrong!
return e
return action + " successfully!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment