Last active
September 22, 2017 17:55
-
-
Save quasoft/3760ca0702b52d59d5c8420f4403c000 to your computer and use it in GitHub Desktop.
Lambda function that sends a daily E-mail with the title of the daily free eBook of Packt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from datetime import datetime | |
from urllib.request import urlopen | |
import boto3 | |
import re | |
CLAIM_PAGE = os.environ['claim_page'] | |
SNS_TOPIC = os.environ['topic_arn'] | |
EMAIL = os.environ['email'] | |
def check_daily_book(): | |
'''Open the claim page for the daily free eBook and extract | |
the title of the book. Then it by SNS to my email. | |
''' | |
with urlopen(CLAIM_PAGE) as stream: | |
html = stream.read().decode("utf-8") | |
print('Length of html: %d' % len(html)) | |
r = re.search(r'<div class="dotd-title">\s*?<h2>\s*(.+?)\s*</h2>\s*?</div>', html) | |
if r: | |
title = r.group(1).strip() | |
print(title) | |
sns = boto3.client('sns') | |
subject = "Packt Daily: " + (title[:57] + '...' if len(title) > 60 else title) | |
msg = "" | |
msg += "Packt daily free eBook is '%s'" % title | |
msg += "\r\n\r\n" | |
msg += "Check it out at " + CLAIM_PAGE | |
sns.publish( | |
TopicArn=SNS_TOPIC, | |
Message=msg, | |
Subject=subject | |
) | |
return title | |
return None | |
def lambda_handler(event, context): | |
print('Checking {} at {}...'.format(CLAIM_PAGE, event['time'])) | |
try: | |
check_daily_book() | |
except: | |
print('Check failed!') | |
raise | |
else: | |
print('Check passed!') | |
return event['time'] | |
finally: | |
print('Check complete at {}'.format(str(datetime.now()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment