Skip to content

Commit

Permalink
Added AWS SES
Browse files Browse the repository at this point in the history
  • Loading branch information
utkarshbajaj committed Aug 11, 2021
1 parent 8d6a490 commit 3d46906
Show file tree
Hide file tree
Showing 9 changed files with 169 additions and 59 deletions.
Binary file added __pycache__/aws_access.cpython-37.pyc
Binary file not shown.
Binary file modified __pycache__/master.cpython-37.pyc
Binary file not shown.
102 changes: 102 additions & 0 deletions aws_access.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import smtplib
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sendUpdates(user, contestant):

try:

# Replace sender@example.com with your "From" address.
# This address must be verified.
SENDER = 'cfrankingupdate@gmail.com'
SENDERNAME = 'lukesfather'

# Replace smtp_username with your Amazon SES SMTP user name.
USERNAME_SMTP = "AKIA4NPSV35DEI4DB7MT"

# Replace smtp_password with your Amazon SES SMTP password.
PASSWORD_SMTP = "BN9Z780kf9cxAv1DnkhSQ5xXzAlKhueUCbDaZS2nIAlz"

# If you're using Amazon SES in an AWS Region other than US West (Oregon),
# replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
# endpoint in the appropriate region.
HOST = "email-smtp.us-east-1.amazonaws.com"
PORT = 587

server = smtplib.SMTP(HOST, PORT)
server.ehlo()
server.starttls()
#stmplib docs recommend calling ehlo() before & after starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)

# Replace recipient@example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = user['useremail']



# The subject line of the email.
SUBJECT = 'Codeforces Rating Update!'

# The email body for recipients with non-HTML email clients.
BODY_TEXT = ("Hi "
# user['username']
"!\n"
"Your new rating is : "
)

new_rating = contestant['newRating']
name = user['username']

message = 'Hello ' + name + '! your new rating is ' + str(new_rating);
print(message)


# The HTML body of the email.
BODY_HTML = """<html>
<head></head>
<body>
<h1>Hi, Name!</h1>
<p>Congratulations / Better luck next time! <br>
Your new rating at Codeforces is :
</p>
</body>
</html>
"""

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
msg['To'] = RECIPIENT
# Comment or delete the next line if you are not using a configuration set
# msg.add_header('X-SES-CONFIGURATION-SET',CONFIGURATION_SET)

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(message, 'plain')
part2 = MIMEText(BODY_HTML, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
# msg.attach(part2)

# Try to send the message.
try:
server.sendmail(SENDER, RECIPIENT, msg.as_string())
# server.sendmail(SENDER, RECIPIENT, msg.as_string())
# Display an error message if something goes wrong.
except Exception as e:
print ("Error: ", e)
else:
print ("Email sent to " + user['username'])

server.close()

except Exception as e:
print ("Error: ", e)
else:
print ("All Set!")
1 change: 1 addition & 0 deletions contest_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,4 @@ def contest_finder():

if(__name__ == "__main__"):
ans = contest_finder()
print(ans)
8 changes: 6 additions & 2 deletions data-read.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from aws_access import sendUpdates

cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()

result = db.collection('users').get()

for each in result:
print(each.to_dict()['userhandle'])
# for each in result:
# print(each.to_dict()['userhandle'])

sendUpdates(result)
# sendUpdates(result)
57 changes: 30 additions & 27 deletions final.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,41 @@ def contest_finder():
url = "https://codeforces.com/api/contest.list?gym=false"

while(True):
response = requests.get(url)

data = response.json()

list = []

for contest in data['result']:
if contest["phase"] == "FINISHED":
break

if(contest["durationSeconds"] < 12500 and abs(contest['relativeTimeSeconds']) < 2 * oneday):
list.append(contest)

if(len(list) == 0):
print("Sleeping for one day")
time.sleep(oneday)
continue

list.sort(key = lambda x: x['startTimeSeconds'])

for contest in list:
print(contest)

contestId = list[0]['id'];
# contestId = 1525
# response = requests.get(url)
#
# data = response.json()
#
# list = []
#
# for contest in data['result']:
# if contest["phase"] == "FINISHED":
# break
#
# if(contest["durationSeconds"] < 12500 and abs(contest['relativeTimeSeconds']) < 2 * oneday):
# list.append(contest)
#
# if(len(list) == 0)6
# print("Sleeping for one day")
# time.sleep(oneday)
# continue
#
# list.sort(key = lambda x: x['startTimeSeconds'])
#
# for contest in list:
# print(contest)
#
# contestId = list[0]['id'];
contestId = 1526
start = time.time();

cont_url = 'https://codeforces.com/api/contest.ratingChanges?contestId=' + str(contestId)

while True:
response = requests.get(url)
response = requests.get(cont_url)
data = response.json()

# print(data)

end = time.time()
elapsed = end - start

Expand Down Expand Up @@ -72,11 +74,12 @@ def contest_finder():

print("Going to next contest now!")
time.sleep(10);
break






if(__name__ == "__main__"):
ans = contest_finder()
contest_finder()
Empty file added finalv2.py
Empty file.
57 changes: 30 additions & 27 deletions master.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,43 +8,44 @@
from firebase_admin import firestore

from credentials import sender_email, passwd
from aws_access import sendUpdates

class SendMail:
server = smtplib.SMTP('smtp.gmail.com', 587)
# class SendMail:
# server = smtplib.SMTP('smtp.gmail.com', 587)

def __init__(self):
"""Connect to the smtp server for gmail"""
# def __init__(self):
# """Connect to the smtp server for gmail"""

try:
self.server.starttls()
self.server.login(sender_email, passwd)
# try:
# self.server.starttls()
# self.server.login(sender_email, passwd)

print("Login success")
# print("Login success")

except:
print("Was already logged in")
# except:
# print("Was already logged in")



def sendto(self, user_info, contestant_info):
'''Send mail to the participant'''
rec_email = user_info['useremail']
new_rating = contestant_info['newRating']
name = user_info['username']
# def sendto(self, user_info, contestant_info):
# '''Send mail to the participant'''
# rec_email = user_info['useremail']
# new_rating = contestant_info['newRating']
# name = user_info['username']

message = 'Hello ' + name + '! your new rating is ' + str(new_rating);
# message = 'Hello ' + name + '! your new rating is ' + str(new_rating);

# msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
# % ( from_addr, to_addr, subj, date, message_text )
# # msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
# # % ( from_addr, to_addr, subj, date, message_text )

print(message)
self.server.sendmail(sender_email, rec_email, message)
# print(message)
# self.server.sendmail(sender_email, rec_email, message)

def logout(self):
"""Quit the current server session"""
# def logout(self):
# """Quit the current server session"""

self.server.quit()
print("Server quit done")
# self.server.quit()
# print("Server quit done")


class SendUpdates:
Expand All @@ -54,18 +55,20 @@ def sendto(self, url):
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)

mailclient = SendMail()

db = firestore.client()
result = db.collection('users').get()

response = requests.get(url)
data = response.json()

# sendUpdates(result)

for contestant in data['result']:
for user in result:
if user.to_dict()['userhandle'] == contestant['handle']:
# print(user.to_dict())
mailclient.sendto(user.to_dict(), contestant)
# mailclient.sendto(user.to_dict(), contestant)
sendUpdates(user.to_dict(), contestant)

firebase_admin.delete_app(firebase_admin.get_app(name='[DEFAULT]'))

3 changes: 0 additions & 3 deletions web_page/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,3 @@ function myFunction() {
});

}



0 comments on commit 3d46906

Please sign in to comment.