The Campaign Run Report available on the Platform provides comprehensive information. Using the APIS, we can further refine these reports to our needs.
The following script is a sample Python code that:
- Connects to the given URL and Account.
- Retrieves the list of Campaigns.
- Checks which Campaigns were executed today.
- For those Campaigns, fetches the Campaign Runs.
- For each run, retrieves the Campaign Run results.
- Transfers the results into a single CSV file.
To create a standalone application, we need to consider how are we going to pass the parameters. Let's start with that:
import requests
import csv
import os
import json
import argparse
from datetime import datetime, timezone
import sys
#Let's set up the command line parameters:
parser = argparse.ArgumentParser()
parser.add_argument('--api', help='api authentication key "API: xyz" ')
parser.add_argument('--accountid',help='Account ID')
parser.add_argument('--url',help='Cyara portal URL eq. https://cyaraportal.us/')
parser.add_argument('--csv',help='csv filename')
args = parser.parse_args()
if args.api == None:
print ("Api key is not defined")
sys.exit()
else:
api = 'ApiKey '+args.api
if args.accountid == None:
print ("Account ID is not defined")
sys.exit()
else:
acct_id = args.accountid
if args.url == None:
print ("Cyara portal URL is not defined")
sys.exit()
else:
url = args.url
if args.csv == None:
print ("csv filename is not defined. Generic name will be used")
csv_file='export.csv'
else:
csv_file = args.csv
Now, let's construct our authentication header:
#Let's build auth headers
header = requests.structures.CaseInsensitiveDict()
header["accept"] = "application/json"
header["Authorization"] = api
Next, we need to create the necessary functions that will be used in the automation:
#Function to get results for a given Campaign and Campaign Run ID.
def get_results(url,header,acct_id,campaign_id,run_id):
rurl = url+'/cyarawebapi/v3.0/accounts/'+str(acct_id)+'/report/campaigns/'+str(campaign_id)+'/runs/'+str(run_id)+'/results?stepResults=true'
r = requests.get(rurl,verify=False,headers=header).text
cr = json.loads(r)
results = cr['results']
return results
#Function to get all the Campaigns for a given Account:
def get_campaigns(url,header,acct_id):
print (url+'/cyarawebapi/v3.0/accounts/'+acct_id+'/campaigns'+'?pageSize=1000')
r = requests.get(url+'/cyarawebapi/v3.0/accounts/'+acct_id+'/campaigns'+'?pageSize=1000',verify=False,headers=header).text
cr = json.loads(r)
campaigns = cr['results']
return campaigns
#Function to get all the Campaign runs for a given Campaign from midnight to current time in ZULU
def get_campaign_runs(url,header,acct_id,campaign):
current_date_utc = datetime.now(timezone.utc).date()
# Create a datetime object for 12:00 AM in UTC
zulu_time_midnight = datetime(current_date_utc.year, current_date_utc.month, current_date_utc.day, 0, 0, 0, tzinfo=timezone.utc)
zulu_time_midnight = zulu_time_midnight.strftime("%Y-%m-%d %H:%M:%S")
print ('Zulu Time Midnight'+str(zulu_time_midnight))
# get current time
current_zulu_time = datetime.now(timezone.utc)
current_zulu_time = current_zulu_time.strftime("%Y-%m-%d %H:%M:%S")
print ('Current Zulu time: '+str(current_zulu_time))
urlstring= url+'/cyarawebapi/v3.0/accounts/'+acct_id+'/campaigns/'+str(campaign['campaignId'])+'/runs'+'?fromDate='+str(zulu_time_midnight)+'&toDate='+str(current_zulu_time)
print ('GET: '+urlstring)
r = requests.get(urlstring,headers=header,verify=False).text
rj = json.loads(r)
campaign_runs=[]
for run in rj['results']:
campaign_runs.append(run['runId'])
return campaign_runs
#Function to write report for a given Campaign into the CSV file.
def write_report(csv_file,result):
#Let's massage the data and build our CSV report string:
testcase=result['testCase']
testcaseid=testcase['testCaseId']
name=testcase['name']
cld=result['calledNumber']
cli=result['callingNumber']
testresult = result['testResult']
detail=testresult['detail']
callresult=testresult['result']
#the line to be written into the csv file:
obj = [testcaseid,name,cld,cli,detail,callresult]
#print ('Writing the string: '+str(testcaseid)+' '+str(name)+' '+str(cld)+' '+str(cli)+' '+str(detail)+' '+str(callresult))
with open(csv_file, mode='a', newline='') as f:
writer = csv.writer(f)
writer.writerow(obj)
In the write_report function, we are massaging the data based on the JSON structure received from Cyara. We are adding Test Case ID, Test Case Name, Called Number, Calling Number, Detailed Call Result, and Call Result. This script gets all the Campaigns that were executed today and pulls all their executions up until the current time. We need to add the CampaignID, Campaign Name, and other necessary elements.
Once this is done, let's pull the report for all Campaigns that were executed today up to this current moment:
#Start processing
#Step 1: write the first line into the CSV file
first_line=["testcaseid", "TestCaseName","CalledNumber","ANI","Call result detail","Call result"]
with open(csv_file, mode='w', newline='') as ff:
print ('Writing the first row: testcaseid", "TestCaseName","CalledNumber","ANI","Call result detail","Call result')
writer = csv.writer(ff)
writer.writerow(first_line)
#Step 2: Get the list of Campaigns for the Account
campaigns = get_campaigns(url,header,acct_id)
#Step 3: Get Campaign runs for those Campaigns that were executed today
for campaign in campaigns:
if campaign['lastRunDate'] is not None:
#print ('Campaign run date'+str(campaign['lastRunDate']))
current_date_time_utc = datetime.now(timezone.utc)
zulu_time_str = current_date_time_utc.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
zulu_time = datetime.strptime(zulu_time_str, "%Y-%m-%dT%H:%M:%S.%fZ")
date_only = zulu_time.date()
formatted_date_str = campaign['lastRunDate'][:19] + "Z"
campaign_last_run_date = datetime.strptime(formatted_date_str, "%Y-%m-%dT%H:%M:%SZ")
#print ('Campaign last run date: '+str(campaign_last_run_date))
#print ('zulu date: '+str(date_only ))
if campaign_last_run_date.date()==date_only:
print ('True')
print ('Get campaign runs for campaign '+str(campaign['campaignId']))
campaign_runs = get_campaign_runs(url,header,acct_id,campaign)
print ('List runids: '+str(campaign_runs))
for campaignrun in campaign_runs:
results = get_results(url,header,acct_id,campaign['campaignId'],campaignrun)
for result in results:
write_report(csv_file,result)
# Done
To compile the above script, save the blocks together as a Python (.py) file, and follow the instructions at: https://www.blog.pythonlibrary.org/2021/05/27/pyinstaller-how-to-turn-your-python-code-into-an-exe-on-windows/