Skip to content

Instantly share code, notes, and snippets.

@randylubin
Last active July 24, 2017 22:47
Show Gist options
  • Save randylubin/ca7dc8a28d19fe55894bad85cbe3522a to your computer and use it in GitHub Desktop.
Save randylubin/ca7dc8a28d19fe55894bad85cbe3522a to your computer and use it in GitHub Desktop.
Send sweet nothings with Lambda and Twilio
import base64
import json
import os
import urllib
import random
from urllib import request, parse
TWILIO_SMS_URL = "https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json"
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")
MY_NUMBER = os.environ.get("MY_NUMBER")
PARTNERS_NUMBER = os.environ.get("PARTNERS_NUMBER")
def lambda_handler(event, context):
# this determines the average frequency of that that the message is sent .075 means that roughly 1/13 times it will send
send_this_time = random.random() < 0.075
to_number = PARTNERS_NUMBER
from_number = MY_NUMBER
# add your own sweet nothings to this array
message_list = [
"I love you!",
"I am so lucky to have you in my life!"
]
# put your own name, sign-offs, pet names in this list
sign_off_list = [
"Randy",
"Fiancee"
]
body = random.choice(message_list) + " -" + random.choice(sign_off_list)
if not send_this_time:
return "RNG says no"
elif 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."
# insert Twilio Account SID into the REST API URL
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 "SMS sent successfully!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment