Snippets

Sam Fonoimoana Get Marketo Lead Activities

Created by Sam Fonoimoana
import datetime, csv
from pprint import pprint, pformat
from marketorestpython.client import MarketoClient

'''
This script will return all specified activities across all leads
for the date range you specify. This will be outputted to a csv 
with the following columns:
- Lead ID
- Activity Date
- Activity Type ID
- Activity Type Name # i.e. 'PDF Download'
- Primary Attribute Value # i.e. 'The Greatest PDF I made'
You can use the output to find customer journey patterns.
'''

# ********************************** #
# **** ENTER VARIABLES HERE !!! **** #
# ********************************** #

# Marketo Creds
munchkin_id = 'MKTO_SUBDOMAIN' # fill in Munchkin ID, typical format 000-AAA-000
client_id = 'MKTO_CLIENT_ID' # enter Client ID from Admin > LaunchPoint > View Details
client_secret = 'MKTO_CLIENT_SECRET' # enter Client ID and Secret from Admin > LaunchPoint > View Details

# Specify which activities you want to include
activity_type_ids = [] # i.e. ['100001','100002','100003','100004'] # pageviews, content downloads, video views, status change

# Date Range and CSV output file
update_start = 'ENTER_YOUR_START_DATE' #'2022-02-20'
update_end = 'ENTER_YOUR_END_DATE' #'2022-02-27'
output_file = 'ENTER_YOUR_FILE_PATH' # 'activities.csv' # UPDATE WITH YOUR FILE

# ********************************** #
# **** FUNCTIONS ******************* #
# ********************************** #

# pass in strings YYYY-MM-DD
def gimme_dates(start, end):
    sdate = datetime.datetime.strptime(start,'%Y-%m-%d')
    edate = datetime.datetime.strptime(end,'%Y-%m-%d')
    r = [sdate+datetime.timedelta(days=x) for x in range((edate-sdate).days+1)]
    # r = [edate-datetime.timedelta(days=x) for x in range((edate-sdate).days+1)] # other descending
    r = [datetime.datetime.strftime(x,'%Y-%m-%d') for x in r]
    return r

# ****** GET ACTIVITY TYPES ******
def get_activity_types():
    mc = MarketoClient(munchkin_id, client_id, client_secret, api_limit=None, max_retry_time=None)
    cas = mc.execute(method = 'get_activity_types')
    # for c in cas: pprint(c)
    return cas

# ****** GET ACTIVITY LEADS ******
def get_activity_type_leads(activity_type_ids, start_date, end_date, listId=None):
    mc = MarketoClient(munchkin_id, client_id, client_secret, api_limit=None, max_retry_time=None)
    cas = mc.execute(
        method='get_lead_activities', 
        activityTypeIds=activity_type_ids,#['23','22'], 
        nextPageToken=None, 
        sinceDatetime=start_date,#'2015-10-06', 
        untilDatetime=end_date,#'2016-04-30', 
        batchSize=None, 
        listId=listId, 
        # leadIds=[1,2]
    )
    return cas


# ********************************** #
# **** MAIN PROCESS - GRAB DATA **** #
# ********************************** #

# Get activity types to append friendly names
activity_types = get_activity_types()
id_names = {row.get('id'): row.get('name') for row in activity_types}

# break the date range into days
dates = gimme_dates(update_start, update_end)

# reset the file
with open(output_file,'w') as f: pass

# add column headers
columns = ['leadId','activityDate','activityTypeId','activityName','primaryAttributeValue']
with open(output_file,'a') as f:
    writer = csv.writer(f)
    writer.writerow(columns)

# get the data, date by date
for i in range(len(dates)-1):
    
    update_start = dates[i]
    update_end = dates[i+1]
    
    print(f'Going to grab data for {update_start} to {update_end}')
    lead_activities = get_activity_type_leads(activity_type_ids, update_start, update_end)
    data = []
    for a in lead_activities: #pprint(a)
        lid = a.get('leadId')
        activity = id_names.get(a.get('activityTypeId')) # friendly name of the activity
        this_row = [lid,a.get('activityDate'),a.get('activityTypeId'),activity,a.get('primaryAttributeValue')]
        data.append(this_row)
    
    # write the days activities to file
    with open(output_file,'a') as f:
        writer = csv.writer(f)
        writer.writerows(data)

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.