Skip to content

Instantly share code, notes, and snippets.

@hidesakai
Created April 19, 2017 12:32
Show Gist options
  • Save hidesakai/7848982622917244ca125b9fcc3905ed to your computer and use it in GitHub Desktop.
Save hidesakai/7848982622917244ca125b9fcc3905ed to your computer and use it in GitHub Desktop.
AWS Lambda + Twilio Googleカレンダーのリマインダーを音声通知にして電話させる ref: http://qiita.com/hidesakai/items/20873fa354cb49911608
# -*- coding: utf-8 -*-
import os
import re
import json
import email
import base64
import urllib
import boto3
from twilio.rest import Client
account_sid = os.environ['ACCOUNT_SID']
auth_token = os.environ['AUTH_TOKEN']
# Twilio アカウントページのAccount SIDとAuth TokenをSETする
client = Client(account_sid, auth_token)
s3 = boto3.client('s3')
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
titleText = None
timeText = None
try:
# Gmailから転送されてきたメールデータを取り出す
response = s3.get_object(Bucket=bucket, Key=key)
b = email.message_from_string(response['Body'].read())
titleRegex = re.compile("タイトル: (.+)")
timeRegex = re.compile("日時: \d{4}/\d{2}/\d{2} \(.+\) (\d{2}\:\d{2}) ~ (\d{2}\:\d{2}) .+")
if b.is_multipart():
for payload in b.get_payload():
line = base64.b64decode(payload.get_payload())
# メール本文のタイトルと日時を抽出
title = titleRegex.search(line)
if title is not None:
titleText = title.group(1)
time = timeRegex.search(line)
if time is not None:
timeText = time.group(1)
except Exception as e:
print(e)
raise e
if titleText is not None and timeText is not None:
twiml = "<Response><Pause length='3'/><Say voice='woman' language='ja-jp'>これはリマインダーです。本日 %s より、%s の予定が入っております。</Say></Response>" % (timeText, titleText)
# リマインドテキスト(できたTwiML)をTwimlets Echoへ渡し、指定電話番号へ発信する
call = client.api.account.calls\
.create(to=os.environ['REMIND_TO'],
from_=os.environ['REMIND_FROM'],
url="http://twimlets.com/echo?Twiml="+urllib.quote(twiml.encode("utf-8")))
print(call.sid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment