Slide 1

Slide 1 text

text me MAYBE smarter real-world integrations with python Mike Pirnat ··· @mpirnat ··· http://mike.pirnat.com

Slide 2

Slide 2 text

– my wife (more or less) Hey–you just left work And this is crazy But it’s your drive home So text me maybe?” “

Slide 3

Slide 3 text

It’s Simple, Right? • Buy a domain • Set up a server • Build a TCPA-compliant SMS integration • Write and deploy a REST API • Write a geofenced mobile app and get it deployed to your device • Write the code you actually care about • Probably more things you don’t care about

Slide 4

Slide 4 text

It’s Simple, Right? • Buy a domain • Set up a server • Build a TCPA-compliant SMS integration • Write and deploy a REST API • Write a geofenced mobile app and get it deployed to your device • Write the code you actually care about • Probably more things you don’t care about X

Slide 5

Slide 5 text

+ + https://ifttt.com mobile app - geofence trigger Maker channel - HTTP POST action https://aws.amazon.com/lambda AWS API Gateway - instant HTTP API AWS Lambda - serverless Python 2.7 https://www.twilio.com send SMS messages Python SDK

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

123abcCopyThisButKeepItSecret 456CopyThisTooButDoNotShareIt

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

Python! the fun part:

Slide 12

Slide 12 text

Project Setup

Slide 13

Slide 13 text

Virtualenv Create and activate a virtual environment: $ virtualenv textmemaybe $ cd textmemaybe $ source bin/activate Or perhaps: $ mkvirtualenv textmemaybe $ workon textmemaybe

Slide 14

Slide 14 text

config.py # Twilio account data... account_sid = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" from_phone = "+1XXXXXXXXXXXX" # Log level import logging log_level = logging.DEBUG

Slide 15

Slide 15 text

messages.py GOT_EVENT = "got event {}" IN_WINDOW = "current time within window, will attempt to send message" NOT_IN_WINDOW = "current time not within window, ignoring message" SENT = "sent" NOT_SENT = "unsent"

Slide 16

Slide 16 text

textmemaybe.py """ Your screen was glowing New files Vim was loading Late night Brain was rolling Where you think you're coding baby? """

Slide 17

Slide 17 text

API Definition

Slide 18

Slide 18 text

POST some JSON: { "to_phone": "+19995551234", "message": "Mike has left the office", "t1": "1500", "t2": "2200", "tz": "US/Eastern", "days": "12345" } Get some JSON back: { "result": "sent" }

Slide 19

Slide 19 text

POST some JSON: { "to_phone": "+19995551234", "message": "Mike has left the office", "t1": "1500", "t2": "2200", "tz": "US/Eastern", "days": "12345" } Get some JSON back: { "result": "sent" }

Slide 20

Slide 20 text

POST some JSON: { "to_phone": "+19995551234", "message": "Mike has left the office", "t1": "1500", "t2": "2200", "tz": "US/Eastern", "days": "12345" } Get some JSON back: { "result": "sent" }

Slide 21

Slide 21 text

POST some JSON: { "to_phone": "+19995551234", "message": "Mike has left the office", "t1": "1500", "t2": "2200", "tz": "US/Eastern", "days": "12345" } Get some JSON back: { "result": "sent" }

Slide 22

Slide 22 text

Sending a Message

Slide 23

Slide 23 text

from twilio.rest import TwilioRestClient from config import account_sid, auth_token, from_phone client = TwilioRestClient(account_sid, auth_token) def send_sms(to_phone, from_phone, body): """ Send an SMS message containing a particular body to a phone number from a phone number. """ return client.messages.create(to=to_phone, from_=from_phone, body=body) message = send_sms(to_phone, from_phone, message_body)

Slide 24

Slide 24 text

from twilio.rest import TwilioRestClient from config import account_sid, auth_token, from_phone client = TwilioRestClient(account_sid, auth_token) def send_sms(to_phone, from_phone, body): """ Send an SMS message containing a particular body to a phone number from a phone number. """ return client.messages.create(to=to_phone, from_=from_phone, body=body) message = send_sms(to_phone, from_phone, message_body)

Slide 25

Slide 25 text

from twilio.rest import TwilioRestClient from config import account_sid, auth_token, from_phone client = TwilioRestClient(account_sid, auth_token) def send_sms(to_phone, from_phone, body): """ Send an SMS message containing a particular body to a phone number from a phone number. """ return client.messages.create(to=to_phone, from_=from_phone, body=body) message = send_sms(to_phone, from_phone, message_body)

Slide 26

Slide 26 text

from twilio.rest import TwilioRestClient from config import account_sid, auth_token, from_phone client = TwilioRestClient(account_sid, auth_token) def send_sms(to_phone, from_phone, body): """ Send an SMS message containing a particular body to a phone number from a phone number. """ return client.messages.create(to=to_phone, from_=from_phone, body=body) message = send_sms(to_phone, from_phone, message_body)

Slide 27

Slide 27 text

Checking the Time

Slide 28

Slide 28 text

def is_time_between(now, t1, t2): """ Is a time (from a datetime) between two other times (as 24-hour 'HHMM' strings)? """ # Convert HHMM strings into tuples hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) hhmm2 = tuple([int(x) for x in [t2[:2], t2[2:]]]) hhmm = now.hour, now.minute # Start time before end time; span stays within day if hhmm1 <= hhmm2: return hhmm1 <= hhmm <= hhmm2 # End time before start time; span crosses midnight else: return (hhmm1 <= hhmm <= (23, 59)) or \ ((0, 0) <= hhmm <= hhmm2) import datetime now = datetime.datetime.utcnow() if is_time_between(now, t1, t2): message = send_sms(to_phone, from_phone, message_body)

Slide 29

Slide 29 text

def is_time_between(now, t1, t2): """ Is a time (from a datetime) between two other times (as 24-hour 'HHMM' strings)? """ # Convert HHMM strings into tuples hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) hhmm2 = tuple([int(x) for x in [t2[:2], t2[2:]]]) hhmm = now.hour, now.minute # Start time before end time; span stays within day if hhmm1 <= hhmm2: return hhmm1 <= hhmm <= hhmm2 # End time before start time; span crosses midnight else: return (hhmm1 <= hhmm <= (23, 59)) or \ ((0, 0) <= hhmm <= hhmm2) import datetime now = datetime.datetime.utcnow() if is_time_between(now, t1, t2): message = send_sms(to_phone, from_phone, message_body)

Slide 30

Slide 30 text

def is_time_between(now, t1, t2): """ Is a time (from a datetime) between two other times (as 24-hour 'HHMM' strings)? """ # Convert HHMM strings into tuples hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) hhmm2 = tuple([int(x) for x in [t2[:2], t2[2:]]]) hhmm = now.hour, now.minute # Start time before end time; span stays within day if hhmm1 <= hhmm2: return hhmm1 <= hhmm <= hhmm2 # End time before start time; span crosses midnight else: return (hhmm1 <= hhmm <= (23, 59)) or \ ((0, 0) <= hhmm <= hhmm2) import datetime now = datetime.datetime.utcnow() if is_time_between(now, t1, t2): message = send_sms(to_phone, from_phone, message_body)

Slide 31

Slide 31 text

def is_time_between(now, t1, t2): """ Is a time (from a datetime) between two other times (as 24-hour 'HHMM' strings)? """ # Convert HHMM strings into tuples hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) hhmm2 = tuple([int(x) for x in [t2[:2], t2[2:]]]) hhmm = now.hour, now.minute # Start time before end time; span stays within day if hhmm1 <= hhmm2: return hhmm1 <= hhmm <= hhmm2 # End time before start time; span crosses midnight else: return (hhmm1 <= hhmm <= (23, 59)) or \ ((0, 0) <= hhmm <= hhmm2) import datetime now = datetime.datetime.utcnow() if is_time_between(now, t1, t2): message = send_sms(to_phone, from_phone, message_body)

Slide 32

Slide 32 text

def is_time_between(now, t1, t2): """ Is a time (from a datetime) between two other times (as 24-hour 'HHMM' strings)? """ # Convert HHMM strings into tuples hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) hhmm2 = tuple([int(x) for x in [t2[:2], t2[2:]]]) hhmm = now.hour, now.minute # Start time before end time; span stays within day if hhmm1 <= hhmm2: return hhmm1 <= hhmm <= hhmm2 # End time before start time; span crosses midnight else: return (hhmm1 <= hhmm <= (23, 59)) or \ ((0, 0) <= hhmm <= hhmm2) import datetime now = datetime.datetime.utcnow() if is_time_between(now, t1, t2): message = send_sms(to_phone, from_phone, message_body)

Slide 33

Slide 33 text

Anatomy of a Shortcut hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]])

Slide 34

Slide 34 text

Anatomy of a Shortcut hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) get the first 2 characters

Slide 35

Slide 35 text

Anatomy of a Shortcut hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) get the first 2 characters get the last 2 characters

Slide 36

Slide 36 text

Anatomy of a Shortcut hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) get the first 2 characters get the last 2 characters put them in a list

Slide 37

Slide 37 text

Anatomy of a Shortcut hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) get the first 2 characters get the last 2 characters list comprehension: turn everything into a list of integers put them in a list

Slide 38

Slide 38 text

Anatomy of a Shortcut hhmm1 = tuple([int(x) for x in [t1[:2], t1[2:]]]) get the first 2 characters get the last 2 characters list comprehension: turn everything into a list of integers turn the list into a tuple put them in a list

Slide 39

Slide 39 text

Checking the Day

Slide 40

Slide 40 text

def is_day_allowed(now, days): """ Is a day (from a datetime) among particular ISO 8601 (Monday = 1) days? """ return not days or now.isoweekday() in days now = datetime.datetime.utcnow() days = [1, 2, 3, 4, 5] if (is_time_between(now, t1, t2) and is_day_allowed(now, days)): message = send_sms(to_phone, from_phone, message_body)

Slide 41

Slide 41 text

def is_day_allowed(now, days): """ Is a day (from a datetime) among particular ISO 8601 (Monday = 1) days? """ return not days or now.isoweekday() in days now = datetime.datetime.utcnow() days = [1, 2, 3, 4, 5] if (is_time_between(now, t1, t2) and is_day_allowed(now, days)): message = send_sms(to_phone, from_phone, message_body)

Slide 42

Slide 42 text

def is_day_allowed(now, days): """ Is a day (from a datetime) among particular ISO 8601 (Monday = 1) days? """ return not days or now.isoweekday() in days now = datetime.datetime.utcnow() days = [1, 2, 3, 4, 5] if (is_time_between(now, t1, t2) and is_day_allowed(now, days)): message = send_sms(to_phone, from_phone, message_body)

Slide 43

Slide 43 text

Lambda Integration

Slide 44

Slide 44 text

def lambda_handler(event, context): """ AWS Lambda handler function; accepts an event (dict) and context (LambdaContext) and sends an SMS message to the specified phone number(s) if the time is within the specified window. """ now = datetime.datetime.utcnow() t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] if (is_time_between(now, t1, t2) and is_day_allowed(now, days)): to_phone = event['to_phone'] message = send_sms(to_phone, from_phone, event['message']) return {'result': messages.SENT} else: return {'result': messages.NOT_SENT}

Slide 45

Slide 45 text

def lambda_handler(event, context): """ AWS Lambda handler function; accepts an event (dict) and context (LambdaContext) and sends an SMS message to the specified phone number(s) if the time is within the specified window. """ now = datetime.datetime.utcnow() t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] if (is_time_between(now, t1, t2) and is_day_allowed(now, days)): to_phone = event['to_phone'] message = send_sms(to_phone, from_phone, event['message']) return {'result': messages.SENT} else: return {'result': messages.NOT_SENT}

Slide 46

Slide 46 text

def lambda_handler(event, context): """ AWS Lambda handler function; accepts an event (dict) and context (LambdaContext) and sends an SMS message to the specified phone number(s) if the time is within the specified window. """ now = datetime.datetime.utcnow() t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] if (is_time_between(now, t1, t2) and is_day_allowed(now, days)): to_phone = event['to_phone'] message = send_sms(to_phone, from_phone, event['message']) return {'result': messages.SENT} else: return {'result': messages.NOT_SENT}

Slide 47

Slide 47 text

def lambda_handler(event, context): """ AWS Lambda handler function; accepts an event (dict) and context (LambdaContext) and sends an SMS message to the specified phone number(s) if the time is within the specified window. """ now = datetime.datetime.utcnow() t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] if (is_time_between(now, t1, t2) and is_day_allowed(now, days)): to_phone = event['to_phone'] message = send_sms(to_phone, from_phone, event['message']) return {'result': messages.SENT} else: return {'result': messages.NOT_SENT}

Slide 48

Slide 48 text

More Shortcuts t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')]

Slide 49

Slide 49 text

More Shortcuts t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] try to get t1 from the event dictionary, fall back to '0000'

Slide 50

Slide 50 text

More Shortcuts t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] try to get t1 from the event dictionary, fall back to '0000' try to get t2 from the event dictionary, fall back to '0000'

Slide 51

Slide 51 text

More Shortcuts t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] try to get t1 from the event dictionary, fall back to '0000' try to get t2 from the event dictionary, fall back to '0000' assign the values into t1 and t2 in a single step

Slide 52

Slide 52 text

More Shortcuts t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] try to get t1 from the event dictionary, fall back to '0000' try to get t2 from the event dictionary, fall back to '0000' try to get days from the event dictionary, fall back to '' assign the values into t1 and t2 in a single step

Slide 53

Slide 53 text

More Shortcuts t1, t2 = event.get('t1', '0000'), event.get('t2', '0000') days = [int(x) for x in event.get('days', '')] try to get t1 from the event dictionary, fall back to '0000' try to get t2 from the event dictionary, fall back to '0000' try to get days from the event dictionary, fall back to '' list comprehension: turn everything into a list of integers assign the values into t1 and t2 in a single step

Slide 54

Slide 54 text

Logging

Slide 55

Slide 55 text

import logging from config import log_level logger = logging.getLogger() logger.setLevel(log_level) def lambda_handler(event, context): logger.info(messages.GOT_EVENT.format(event)) ... if (is_time_between(...) and is_day_allowed(...)): logger.info(messages.IN_WINDOW) message = send_sms(...) logger.debug(message) return {'result': messages.SENT} else: logger.info(messages.NOT_IN_WINDOW) return {'result': messages.NOT_SENT}

Slide 56

Slide 56 text

import logging from config import log_level logger = logging.getLogger() logger.setLevel(log_level) def lambda_handler(event, context): logger.info(messages.GOT_EVENT.format(event)) ... if (is_time_between(...) and is_day_allowed(...)): logger.info(messages.IN_WINDOW) message = send_sms(...) logger.debug(message) return {'result': messages.SENT} else: logger.info(messages.NOT_IN_WINDOW) return {'result': messages.NOT_SENT}

Slide 57

Slide 57 text

import logging from config import log_level logger = logging.getLogger() logger.setLevel(log_level) def lambda_handler(event, context): logger.info(messages.GOT_EVENT.format(event)) ... if (is_time_between(...) and is_day_allowed(...)): logger.info(messages.IN_WINDOW) message = send_sms(...) logger.debug(message) return {'result': messages.SENT} else: logger.info(messages.NOT_IN_WINDOW) return {'result': messages.NOT_SENT}

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

Time Zones

Slide 60

Slide 60 text

import arrow def lambda_handler(event, context): ... # Shift to client local timezone if specified now = arrow.utcnow() tz = event.get('tz') now = now.to(tz) if tz else now ...

Slide 61

Slide 61 text

import arrow def lambda_handler(event, context): ... # Shift to client local timezone if specified now = arrow.utcnow() tz = event.get('tz') now = now.to(tz) if tz else now ...

Slide 62

Slide 62 text

import arrow def lambda_handler(event, context): ... # Shift to client local timezone if specified now = arrow.utcnow() tz = event.get('tz') now = now.to(tz) if tz else now ...

Slide 63

Slide 63 text

import arrow def lambda_handler(event, context): ... # Shift to client local timezone if specified now = arrow.utcnow() tz = event.get('tz') now = now.to(tz) if tz else now ...

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

module.function

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

Deploying

Slide 76

Slide 76 text

No content

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

makezip.sh #!/bin/bash PWD=`pwd` TIMESTAMP=`date -j +%Y%m%dT%H%M` ZIPFILE=$PWD/textMeMaybe-$TIMESTAMP.zip zip $ZIPFILE config.py messages.py textmemaybe.py SITE_PACKAGES=$VIRTUAL_ENV/lib/python2.7/site-packages/ cd $SITE_PACKAGES zip -gr $ZIPFILE ./

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

No content

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

No content

Slide 87

Slide 87 text

Double quotes are critical!

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

Now What?

Slide 91

Slide 91 text

make them smarter! When your smart things aren’t smart enough...

Slide 92

Slide 92 text

Links • https://www.twilio.com • https://aws.amazon.com/lambda • https://ifttt.com • http://arrow.readthedocs.io • http://docs.aws.amazon.com/lambda/latest/dg/lambda-python- how-to-create-deployment-package.html • http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example- deployment-pkg.html#with-s3-example-deployment-pkg-python

Slide 93

Slide 93 text

Contact Me Maybe Mike Pirnat http://mike.pirnat.com @mpirnat Thanks! :-)