Skip to content

Commit

Permalink
semi stable scripts now. Still working to get them better
Browse files Browse the repository at this point in the history
  • Loading branch information
jackschultz committed Jul 24, 2014
1 parent 3c723cb commit d6d44f4
Show file tree
Hide file tree
Showing 14 changed files with 397 additions and 192 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@
/incentivizations_phase2/config/config
/incentivizations_phase2/config/userpass
/incentivizations_phase2/config/userpass.txt
/incentivizations_phase2/data/codes/giftcards.csv
/incentivizations_phase2/data/codes/used_giftcards.csv
/incentivizations_phase2/data/winners_codes
1 change: 0 additions & 1 deletion Incentivization Script/Y2 Source/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,3 @@ Inputs: newwinners.csv, file from above with winners, e-mail addresses, and real

Outputs: emaillog.csv, postive confirmation the code executed, as well as tying code to email address/name; amazoncodes.csv, would add ",USED" after each code sent, immediately after code was sent.


85 changes: 81 additions & 4 deletions incentivizations_phase2/helpers.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
#This file contains a few different helper functions that could be useful across the application

import smtplib, time, requests, json
import smtplib, datetime, requests, json, time

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage


ANIMAL_CATEGORIES = ['species', 'genus', 'family', 'order', 'class', 'phylum', 'kingdom']


def get_config(filename):
'''
Gets all keys/values from config file
Expand All @@ -30,12 +33,14 @@ def get_userpass(user_password_file_path):
apiuserpass = userpassfile.readline().strip('\n').strip().split(':')
userpassfile.close()


def send_email(to_addr, from_addr, subject, body_plain, body_html, smtp_options, images=None):
'''
This function sends an email through the GMU smtp server. Both html and plain
'''

#we want to bcc important people in
bcc = None #'[email protected]'#'[email protected]' #['[email protected]'] #[]

msgroot = MIMEMultipart('related')

msgroot['Subject'] = subject
Expand All @@ -52,7 +57,6 @@ def send_email(to_addr, from_addr, subject, body_plain, body_html, smtp_options,
msgalternative.attach(part2)
msgalternative.attach(part1)


for image in images:
img_file = open(image[0], 'rb')
mime_image = MIMEImage(img_file.read())
Expand All @@ -66,7 +70,7 @@ def send_email(to_addr, from_addr, subject, body_plain, body_html, smtp_options,
server.starttls()
server.login(smtp_options['username'],smtp_options['password'])

server.sendmail(from_addr,[to_addr],msgroot.as_string())
server.sendmail(from_addr,[to_addr, None, bcc],msgroot.as_string())

server.quit()
time.sleep(1)
Expand Down Expand Up @@ -109,3 +113,76 @@ def get_email_from_username(allusers, username):
print "No email found for "+str(username)
return email
return None

def read_code_winner_data(data_full_path):
winner_list = []
with open(data_full_path,'r') as f:
next(f) #ignore the first header row
for line in f:
info = line.split(',')
user_info = {}
user_info['user_id'] = int(info[0])
user_info['date'] = datetime.datetime.strptime(info[1], '%Y-%m-%d')
user_info['day_of_week'] = user_info['date'].strftime('%A')
user_info['username'] = info[2][1:-1] if info[2][0] == '"' else info[2]
user_info['number_of_codes'] = int(info[3])
user_info['number_of_new_merits'] = int(info[4])
user_info['number_of_total_merits'] = int(info[5])
user_info['change_in_badge_level'] = int(info[6])
user_info['new_badge_levels'] = [int(x) for x in info[7:13]]
user_info['merits_per_new_level'] = [int(x) for x in info[13:19]]
user_info['more_levels'] = int(info[19])
user_info['merits_until_next_level'] = int(info[20])
user_info['next_level'] = int(info[21])
user_info['code_number'] = 1
winner_list.append(user_info)
return winner_list

def read_thank_you_winner_data(data_full_path):
winner_list = []
with open(data_full_path,'r') as f:
next(f) #ignore the first header row
for line in f:
info = line.split(',')
user_info = {}
user_info['user_id'] = int(info[0])
user_info['date'] = datetime.datetime.strptime(info[1], '%Y-%m-%d')
user_info['day_of_week'] = user_info['date'].strftime('%A')
user_info['username'] = info[2][1:-1]
user_info['number_of_thanks'] = int(info[3])
winner_list.append(user_info)
return winner_list

def get_and_mark_amazon_code(infilename, used_codes, test=True):
'''
This returns the first code that hasn't been used based on the filename
as well as isn't in the used_codes array and appends them to a seperate file.
Note: you're probably going to want to move those lines into the gift card
file after to update for the next run.
'''
outfilename = infilename[:-4] + '_out' + infilename[-4:]
code = None
with open(infilename, 'r') as f:
with open(outfilename, 'a') as dest:
for line in f:
split = line.split(',')
code = split[0].strip('\n')
if len(split) == 1 and code not in used_codes:
line_to_write = code + ', USED\n'
dest.write(line_to_write)
break
return code

ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])

if __name__ == "__main__":
codes = []
code = get_and_mark_amazon_code('data/codes/giftcards.csv',codes[:])
codes.append(code)
code = get_and_mark_amazon_code('data/codes/giftcards.csv',codes[:])
codes.append(code)
code = get_and_mark_amazon_code('data/codes/giftcards.csv',codes[:])
codes.append(code)
code = get_and_mark_amazon_code('data/codes/giftcards.csv',codes[:])
codes.append(code)
get_and_mark_amazon_code('data/codes/giftcards.csv',codes)
Binary file added incentivizations_phase2/images/amazon.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
95 changes: 95 additions & 0 deletions incentivizations_phase2/send_codes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import csv, requests, time, re, sys, random, smtplib, jinja2, envelopes

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

#Imports from files that I've defined
import helpers

if __name__ == "__main__":

#are we in test mode or do we want to send the emails for real?
test_mode = True#default to testing. No accidents here

#grab the configuration from the config file
config = helpers.get_config('config/config')
userpass = helpers.get_config('config/userpass')

#options for the smtp server
smtp_options = {}
smtp_options['server'] = config['server']
smtp_options['port'] = config['port']
smtp_options['username'] = userpass['smtp_username']
smtp_options['password'] = userpass['smtp_password']
smtp_options['from_addr'] = config['from']

#paths to the data
data_directory = 'winners_codes'
data_filename = 'Winners_2014-07-15.csv'
data_full_path = 'data/' + data_directory + '/' + data_filename
winner_list = helpers.read_code_winner_data(data_full_path)

#paths to the templates
template_path = 'templates/gift_cards'
#grab the text of the emails
#template one first
plain_filename = config['codeplain']
html_filename = config['codehtml']
#get plain file
plain_text_file = open(template_path + '/' + plain_filename, 'r')
plain_template = plain_text_file.read()
plain_text_file.close()
#get html file
html_file = open(template_path + '/' + html_filename, 'r')
html_template = html_file.read()
html_file.close()
#templates for codes emails
code_plain_template = jinja2.Template(plain_template)
code_html_template = jinja2.Template(html_template)


print "Getting All Users..."
all_users = helpers.get_data("https://scicast.org/users/index?role=None&traded_since=None", userpass['api_username'], userpass['api_password'])

current_codes = []
for winner in winner_list:

#images that we need to send. Restart this ever time since it can change based on type
images = []
images.append(['images/scicast_logo.png', '<@sci_logo>'])
images.append(['images/amazon.gif', '<@amazon_image>'])

#pick a random template for the thank you
if winner['number_of_codes'] > 0:
plain_template = code_plain_template
html_template = code_html_template
subject = 'Amazon Gift Code from Scicast.org'
for code_number in range(1,winner['number_of_codes']+1):
winner['code_number'] = code_number
winner['amazon_code'] = helpers.get_and_mark_amazon_code('data/codes/giftcards.csv', current_codes[:])
current_codes.append(winner['amazon_code'])
if not winner['amazon_code']:
print "no code .... continuing"
continue
text_rendered = plain_template.render(winner)
html_rendered = html_template.render(winner)
to_addr = helpers.get_email_from_username(all_users, winner["username"])
to_addr_check = helpers.get_email_from_userid(all_users, winner["user_id"])
if winner['number_of_codes'] > 1:
subject += " " + str(winner['code_number']) + ' of ' + str(winner['number_of_codes'])

if to_addr != to_addr_check or test_addr == None:
print "error with address " + to_addr + ".... continuing"
continue
#send the emails
if test_mode:
to_addr = '[email protected]'
print "TEST: " + winner["username"] + ', ' + to_addr + ',' + winner['amazon_code']
subject += ' Test'
helpers.send_email(to_addr, smtp_options['from_addr'], subject, text_rendered, html_rendered, smtp_options, images)
elif to_addr != None:
to_addr += ".rpost.org"
print winner['date'].strftime("%x") + ', ' + winner["username"] + ', ' + to_addr + ',' + winner['amazon_code']
# helpers.send_email(to_addr, smtp_options['from_addr'], subject, text_rendered, html_rendered, smtp_options, images)

Loading

0 comments on commit d6d44f4

Please sign in to comment.