-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
197 lines (176 loc) · 6.16 KB
/
lambda_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import boto3
import os
import praw
import json
from botocore.exceptions import ClientError
from Credentials import Credentials
def find_nintendo_switch_physical_deals(app_client_id, app_client_secret, app_user_agent, old_deals):
"""
Creates a Reddit instance and searches for new physical US deals through the ten newest submissions
from r/NintendoSwitchDeals
Returns a list of subreddit objects if it finds one or more deals or an empty list
"""
new_deals = []
# Create Reddit Instance to interact with Reddit API
reddit = praw.Reddit(
client_id=app_client_id,
client_secret=app_client_secret,
user_agent=app_user_agent,
)
subreddit = reddit.subreddit("NintendoSwitchDeals")
# Check the ten newest posts from r/NintendoSwitchDeals
# Filter for new physical deals in the US
for submission in subreddit.new(limit=10):
if submission.id not in old_deals and submission.link_flair_text == "Physical Deal" and "/US" in submission.title:
# Add the submission to the new deals list
new_deals.append(submission)
return new_deals
def lambda_handler(event, context):
"""
Tries to find new Nintendo Switch deals on physical products and might
send an email through Amazon Simple Email Service (SES) SDK to notify user
Returns JSON that notifies if it sent an email or not
"""
# Get credential parameters from Systems Manager Parameter Store
AWS_REGION = os.environ.get('AWS_REGION')
aws_client = boto3.client('ssm', region_name=AWS_REGION)
response = aws_client.get_parameters(
Names=[
'email_sender',
'email_recipient',
'client_id',
'client_secret',
'user_agent'
],
WithDecryption=True
)
# Store credential parameters into Credentials object
credentials = Credentials(response['Parameters'])
# Create old deals list for caching data from file
old_deals = []
# If old deals file exists: read it and push to old deals list
file_path = "/tmp/old_deals.txt"
if os.path.exists(file_path):
# Read file data and push into old deals list
try:
print(f'Reading {file_path}')
with open(file_path, 'r') as file:
for submission_id in file:
old_deals.append(submission_id.strip("\n"))
except OSError as error:
print(f'Failed to open {file_path}')
return {
'statusCode': 500,
'body': json.dumps(f'{error}')
}
# Else: Create old deals file
else:
try:
file = open(file_path, 'a')
file.close()
print(f'Created file {file_path}')
except OSError as error:
print(f'Failed to create {file_path}')
return {
'statusCode': 500,
'body': json.dumps(f'{error}')
}
# Get new physical deals from r/NintendoSwitchDeals
client_id = credentials.get_client_id()
client_secret = credentials.get_client_secret()
user_agent = credentials.get_user_agent()
new_deals = find_nintendo_switch_physical_deals(client_id, client_secret, user_agent, old_deals)
# If new deals list is not empty:
if new_deals:
# Add new deals to email body text for non-HTML email clients
body_text = "Nintendo Switch Physical Deals Email Bot presents:\r\n"
for submission in new_deals:
deal_link = f'{submission.url}\r\n'
body_text += deal_link
print("Body Text:")
print(body_text)
# Add new deals to HTML email body
html_deals = ""
for submission in new_deals:
deal = f'<a href="{submission.url}">{submission.title}</a><br>'
html_deals += deal
body_html = """<html>
<head></head>
<body style="font-family: Verdana, sans-serif">
<h1>Nintendo Switch Physical Deals Email Bot presents:</h1><br>
<p>
{}
</p>
</body>
</html>
""".format(html_deals)
print("Body HTML:")
print(body_html)
# Set email credentials
SENDER = credentials.get_sender_email()
RECIPIENT = credentials.get_recipient_email()
SUBJECT = "New from r/NintendoSwitchDeals!"
CHARSET = "UTF-8"
# Send email with SES SDK and return json with email id if sent successfully
# Code modified from "Sending email through Amazon SES using an AWS SDK" by Amazon Simple Email Service Developer Guide
# https://docs.aws.amazon.com/ses/latest/dg/send-an-email-using-sdk-programmatically.html
aws_client = boto3.client('ses',region_name=AWS_REGION)
try:
response = aws_client.send_email(
Destination={
'ToAddresses': [
RECIPIENT,
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': body_html,
},
'Text': {
'Charset': CHARSET,
'Data': body_text,
},
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER,
)
# Display an error if something goes wrong.
except ClientError as error:
print(error.response['Error']['Message'])
return {
'statusCode': 400,
'body': json.dumps(error.response['Error']['Message'])
}
else:
message_id = response['MessageId']
print(f"Email sent to {SENDER}! Message ID: {message_id}")
# Open old_deals.txt file to update with new deals
try:
print(f'Appending new deals to {file_path}')
with open(file_path, 'a') as file:
for submission in new_deals:
file.write(f'{submission.id}\n')
except OSError as error:
print(f'Failed to open {file_path}')
return {
'statusCode': 500,
'body': json.dumps(f'{error}')
}
return {
'statusCode': 200,
'body': json.dumps(f"Email sent to {SENDER}! Message ID: {message_id}")
}
else:
# Notify no new deals, no email sent
print("There are 0 new deals. Thus, no email was sent to user.")
# Return success json
return {
'statusCode': 200,
'body': json.dumps('No new deals!')
}