Last active
August 29, 2015 14:01
-
-
Save sushain97/93fc837c6da1fdba6a29 to your computer and use it in GitHub Desktop.
MailChimp Drawing Utility
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
#!/usr/bin/env python3 | |
import sys, argparse, urllib.request, urllib.parse, json, logging, random | |
from datetime import datetime | |
dateFormat = '%m-%d-%y' | |
def getAPIResponse(url, apiKey, data={}): | |
params = {'apikey': apiKey} | |
params.update(data) | |
logging.info('Sending request to %s with data %s' % (url, params)) | |
req = urllib.request.urlopen(url, data=urllib.parse.urlencode(params).encode('utf-8')) | |
return json.loads(req.read().decode('utf-8')) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='MailChimp drawing helper utility') | |
parser.add_argument('apiKey', help='MailChimp API key') | |
parser.add_argument('-d', '--dateSpan', help='Filter campaigns on sent time, format: "MM-DD-YY MM-DD-YY" (first date to second date) OR "MM-DD-YY" (first date to present)') | |
parser.add_argument('-v', '--verbose', help='Set logger to show debug messages', action='store_true') | |
args = parser.parse_args() | |
logging.basicConfig(level=(logging.DEBUG if args.verbose else logging.INFO)) | |
apiKey, dc = args.apiKey.split('-') | |
baseUrl = 'https://%s.api.mailchimp.com/2.0/' % dc | |
try: | |
campaigns = getAPIResponse(baseUrl + 'campaigns/list', apiKey)['data'] | |
except Exception as e: | |
logging.error('Most likely an invalid API key, try again.') | |
logging.debug(json.loads(e.read().decode('utf-8'))) | |
sys.exit(-1) | |
if args.dateSpan: | |
if ' ' in args.dateSpan: | |
startDate, endDate = list(map(lambda x: datetime.strptime(x, dateFormat), args.dateSpan.split(' '))) | |
else: | |
startDate = datetime.strptime(args.dateSpan, dateFormat) | |
endDate = datetime.today() | |
filteredCampaigns = list(filter(lambda x: x['send_time'] and startDate <= datetime.strptime(x['send_time'], '%Y-%m-%d %H:%M:%S') <= endDate, campaigns)) | |
else: | |
filteredCampaigns = campaigns | |
campaignIds = [] | |
print('\nFiltered Campaigns:\n\nCampaign ID\tStatus Title\n' + '-' * 80) | |
for campaignData in filteredCampaigns: | |
print(campaignData['id'], end='\t') | |
campaignIds.append(campaignData['id']) | |
status = campaignData['status'] | |
if status == 'sent': | |
print((status + ' (%s/%s)' % (campaignData['summary']['unique_opens'], campaignData['emails_sent'])).ljust(16), end='') | |
else: | |
print(status.ljust(16), end='') | |
print(campaignData['title']) | |
campaignId = input('\n\nCampaign ID: ') | |
while campaignId not in campaignIds: | |
campaignId = input('Campaign ID: ') | |
openDataLen = list(filter(lambda x: x['id'] == campaignId, filteredCampaigns))[0]['summary']['unique_opens'] | |
openData = [] | |
page = 0 | |
while len(openData) < openDataLen: | |
openData += getAPIResponse(baseUrl + 'reports/opened', apiKey, data={'cid': campaignId, 'opts[limit]': 100, 'opts[start]': page})['data'] | |
page += 1 | |
logging.info('Found %s unique openers' % len(openData)) | |
numWinners = None | |
while not numWinners: | |
try: | |
numWinners = int(input(('\n\n' if numWinners is None else '') + 'Number of winners: ')) | |
except ValueError: | |
numWinners = 0 | |
winners = random.sample(openData, numWinners) | |
print('\n\nWinners:\n' + '-' * 80) | |
for winner in winners: | |
print('%s\t\t(%s)' % (winner['member']['email'], (' '.join(winner['member']['merges'].values())).strip())) | |
print('\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment