def pullAdsIntoCampaign(campaignId, placement, campaignAdList): print("pulling ads") campaign = CampaignUtils.getCampaign(Api, campaignId) videocodes = ["»FP»","»NC»","»TV»","»VP»","»VO»","»VS»"] englishAds = ["431196351","431196357", "431196360", "431196366"] spanishAds = ["431196348", "431196354","431196363", "431196345"] videoAds = ["431196342","431196372","431196375","431196369"] videoHispAds = ["433756626","433757505","433830394","433832422"] adsToUse = None name = placement["name"] campaignName = campaign["name"] if "Hispanic" in campaignName: adsToUse = spanishAds else: adsToUse = englishAds for code in videocodes: if code in name: if "Hispanic" in campaignName: adsToUse = videoHispAds break else: adsToUse = videoAds break if len(campaignAdList) == 0: adsToUse = getModifiedAds(adsToUse, campaignAdList) for ads in adsToUse: copy = AdUtils.copy(Api, ads, campaignId) AdUtils.insertAd(copy, Api)
def checkCampaign(x): placement = PlacementUtils.getPlacement(Api, x["objectId"]) print("checking " + placement["name"]) campaign = CampaignUtils.getCampaign(Api, placement["campaignId"]) if regex.search(campaign["name"]): return placement else: return None
def checkLMA(Api,placement): from v3modules import CampaignUtils import re regex = re.compile("[1-5]L(M|G)") campaign = CampaignUtils.getCampaign(Api, placement["campaignId"]) if regex.search(campaign["name"]): return True return False
def getCampaignName(campaignID): global CampaignObject try: return CampaignObject[campaignID] except: campaign = CampaignUtils.getCampaign(Api,campaignID) CampaignObject[campaignID] = campaign["name"] print("adding {campaignName}".format(campaignName=campaign["name"])) return campaign["name"]
def analyzePlacements(placementId): placement = PlacementUtils.getPlacement(Api, placementId) if "»SS»" not in placement["name"]: return None campaignId = placement["campaignId"] campaign = CampaignUtils.getCampaign(Api, campaignId) regex = re.compile("[1-5]L(M|G)") if regex.search(campaign["name"]): return {"Campaign Name":campaign["name"], "Placement Id": placement["id"], "Placement Name":placement["name"]} else: return None
def lmaCampaignCheck(placement): global LMACampaignObj global NotLMAObj campaignId = placement["campaignId"] if campaignId in LMACampaignObj: return True if campaignId in NotLMAObj: return False print("checking " + str(campaignId)) campaign = CampaignUtils.getCampaign(Api, campaignId) if "LMA" in campaign["name"]: LMACampaignObj[campaign["id"]] = campaign["name"] return True else: NotLMAObj[campaign["id"]] = campaign["name"] return False
def getPlacement(placement_id): global currentCSDList placement = PlacementUtils.getPlacement(Api,placement_id) campaignName = CampaignUtils.getCampaign(Api, placement["campaignId"])["name"].strip() if "CANCELLED" in placement["name"]: return print(campaignName) if campaignName not in currentCSDList: rowID = csdDict[campaignName][1] sheetID = csdDict[campaignName][0] currentCSDList[campaignName] = Smartsheets.getCSD(sheetID,rowID) isTrafficked = PlacementUtils.checkIfTrafficked(Api, placement,currentCSDList[campaignName]) for key in isTrafficked: series.loc[series.placement_id==int(placement_id), key] = isTrafficked[key] series.loc[series.placement_id==int(placement_id), "start_date"] = placement["pricingSchedule"]["startDate"] series.loc[series.placement_id==int(placement_id), "end_date"] = placement["pricingSchedule"]["endDate"]
def checkCampaignEndDate(ad): campaignId = ad["campaignId"] campaign = CampaignUtils.getCampaign(Api, campaignId) today = datetime.datetime.today() campaignDate = datetime.datetime.strptime(campaign["endDate"], "%Y-%m-%d") return today < campaignDate
from v3modules import DCMAPI, CampaignUtils, AdUtils, EventUtils, CreativeUtils, AdvertiserUtils, ChangeLogUtils, PlacementUtils Api = DCMAPI.DCMAPI() # advertiserSet = AdvertiserUtils.getAdvertiserSet() AdobeClickCopy = EventUtils.getEvent(Api, 2668824) AdobeImpressionCopy = EventUtils.getEvent(Api, 2695156) # allCampaigns = [CampaignUtils.getCampaign(Api,20124958)] # campaigns = CampaignUtils.getAllLMA(Api) # allCampaigns = [x for x in campaigns if "103" not in x["name"] and "115" not in x["name"]] # allCampaigns = [CampaignUtils.getCampaign(Api,21798175),CampaignUtils.getCampaign(Api,21815028),CampaignUtils.getCampaign(Api,21712772),CampaignUtils.getCampaign(Api,21736049),CampaignUtils.getCampaign(Api,21792915),CampaignUtils.getCampaign(Api,21825936),CampaignUtils.getCampaign(Api,21830580),CampaignUtils.getCampaign(Api,21884880)] # allCampaigns = [c for c in allCampaigns if "LMA" not in c["name"]]22112046 testList = [ 22064108, 21937425, 22061249, 22046095, 22046937, 22060037, 22059116, 22063868, 22086082, 22110050, 22112046, 22052473 ] allCampaigns = [CampaignUtils.getCampaign(Api, x) for x in testList] # 21798175 # 21815028 # 21712772 # 21736049 # 21792915 # 21825936 # 21830580 # 21884880 def checkCompatibility(ad): creativeId = ad['creativeRotation']['creativeAssignments'][0]['creativeId'] creative = CreativeUtils.getCreative(Api, creativeId) compatibility = creative["compatibility"][0]
def analyzeFile(file_name): import pandas as pd from v3modules import CampaignUtils, PlacementUtils import numpy as np import openpyxl import re LMAOverride = False if ".csv" in file_name: csv = pd.read_csv(file_name) file_name = re.sub('.csv', '.xlsx', file_name) else: csv = pd.read_excel(file_name, sheetname=0) #for item in file_name csv.fillna('N/A', inplace=True) def isEvidon(placementName): nonlocal LMAOverride if LMAOverride == True: return "Y" for string in Evidon: if string in placementName: return "Y" return "N" def nameChange(name, site): global counters import re site = site.loc[counters] if "Carat_" in name: site = re.sub(r'\(\d+\)', "", site).strip() + "_" name = re.sub("Carat_", site, name) name = re.sub("Â", "", name) else: name = re.sub("Â", "", name) counters += 1 return name def dateTimetoDate(value): import datetime import re if isinstance(value, datetime.date): value = value.strftime("%m" + "/" + "%d" + "/" + "%Y") month = value.split('/')[0] if month.startswith('0'): month = re.sub('0', "", month) day = value.split('/')[1] if day.startswith('0'): day = re.sub('0', "", day) year = value.split('/')[2] date = month + "/" + day + "/" + year value = date return value csv["Start date"] = csv["Start date"].apply(dateTimetoDate) csv["End date"] = csv["End date"].apply(dateTimetoDate) csv["Name"] = csv["Name"].apply(nameChange, args=(csv["Site"], )) csv["Evidon"] = csv["Name"].apply(isEvidon) csv = csv[csv['Compatibility'] != 'N/A'] placementID = csv["Id"].iloc[0] placement = PlacementUtils.getPlacement(Api, placementID) campaignID = placement['campaignId'] campaign = CampaignUtils.getCampaign(Api, campaignID)["name"] temp = file_name.split("_") temp.insert(1, re.sub("/", "", campaign.split("_")[0])) file_name = "_".join(temp) for code in LMA: if code in campaign: LMAOverride = True #campaign = campaignName csv['Campaign'] = campaign csv['Creative Rotation'] = np.nan csv['Creative File 1'] = np.nan csv['Creative File 2'] = np.nan csv['Creative File 3'] = np.nan csv['Creative File 4'] = np.nan csv['Creative File 5'] = np.nan del csv['Object type'] del csv['Status'] # REORDER COLUMNS csv = csv[[ 'Campaign', 'Site', 'Id', 'Name', 'Start date', 'End date', 'Compatibility', 'Dimensions', 'Creative Rotation', 'Creative File 1', 'Creative File 2', 'Creative File 3', 'Creative File 4', 'Creative File 5' ]] csv_ss_placement = csv[csv['Dimensions'] == '1x1'] csv = csv[csv['Dimensions'] != '1x1'] site_list = csv_ss_placement['Site'].unique().tolist() def getDimensions(placement): if type(placement) is str: try: return str(placement).split("_")[3] except: dimensions = str(placement).split("»")[5] if "T1" in dimensions: dimensions = "120+N/A" else: dimensions = re.sub("NA\+", "", dimensions) return dimensions csv_ss_placement["Dimensions"] = csv_ss_placement["Name"].apply( getDimensions) csv["Dimensions"] = csv["Name"].apply(getDimensions) for i in range(3): csv_ss_placement = csv_ss_placement.append(pd.Series( [ np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, ], index=csv_ss_placement.columns.tolist()), ignore_index=True) csv_ss_placement = csv_ss_placement.append(pd.Series( [ 'Site', 'Contact', np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, ], index=csv_ss_placement.columns.tolist()), ignore_index=True) siteRow = len(csv_ss_placement) + 1 for site in site_list: csv_ss_placement = csv_ss_placement.append(pd.Series( [ site, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, ], index=csv_ss_placement.columns.tolist()), ignore_index=True) urls = pd.DataFrame(data={'Creative File': [], 'Creative URL': []}) writer = pd.ExcelWriter('Output/%s' % (file_name), engine='xlsxwriter') workbook = writer.book headerObject = { "A1": "Campaign", "B1": "Site", "C1": "Id", "D1": "Name", "E1": "Start Date", "F1": "End Date", "G1": "Compatibility", "H1": "Dimensions", "I1": "Evidon", "J1": "Creative Rotation", "K1": "Creative File 1", "L1": "Creative File 2", "M1": "Creative File 3", "N1": "Creative File 4", "O1": "Creative File 5" } urlObject = {'A1': "Creative File", "B1": "Creative URL"} siteObject = {'A' + str(siteRow): "Site", 'B' + str(siteRow): "Contact"} format1 = workbook.add_format({'bg_color': '#0AADE9'}) if len(csv) != 0: csv.to_excel(writer, sheet_name='TPS Placements', index=False) worksheet_csv = writer.sheets['TPS Placements'] for obj in headerObject: worksheet_csv.write(obj, headerObject[obj], format1) if len(csv_ss_placement) > 4: print(len(csv_ss_placement)) csv_ss_placement.to_excel(writer, sheet_name='SS Placements', index=False) worksheet_csv_ss_placements = writer.sheets['SS Placements'] for obj in headerObject: worksheet_csv_ss_placements.write(obj, headerObject[obj], format1) for obj in siteObject: worksheet_csv_ss_placements.write(obj, siteObject[obj], format1) urls.to_excel(writer, sheet_name='URLs', index=False) worksheet_URLs = writer.sheets['URLs'] for obj in urlObject: worksheet_URLs.write(obj, urlObject[obj], format1) writer.save()
def checkCampaign(campaignId): campaign = CampaignUtils.getCampaign(Api,campaignId) if "2019" in campaign["name"]: return True else: return False
if "2019" in campaign["name"]: return True else: return False def checkDate(endTime): pattern = re.compile("\.(\d+)") endTime = re.sub(pattern,"",endTime) endTime = datetime.datetime.strptime(endTime,"%Y-%m-%dT%H:%M:%SZ") return endTime > datetime.datetime.today() adlist = [x for x in adlist if checkDate(x["endTime"])] adlist = [x for x in adlist if checkCampaign(x["campaignId"])] for ad in adlist: # AdUtils.activateAd(ad["id"],Api) updatedAdList.append({"AdId":ad["id"],"campaignId":ad['campaignId'],"campaignName":CampaignUtils.getCampaign(Api,ad['campaignId'])["name"]}) test = 0 df = pandas.DataFrame(data=updatedAdList) df = df[['campaignName','campaignId','AdId']] writer = pandas.ExcelWriter('In-Stream Ad Report.xlsx',engine='xlsxwriter') df.to_excel(writer, sheet_name ="Info", index = False) worksheet = writer.sheets['Info'] writer.save() import os import modules.send_mail as send_mail directories = os.listdir() reports = [x for x in directories if "In-Stream Ad Report" in x] for report in reports: MailUtils.send_email([report], subject="In-steam Ad Report", message="Attached are the updated ads", recipients=["*****@*****.**", ])
listValues = {"action": "ACTION_UPDATE", "objectType":"OBJECT_PLACEMENT", "minChangeTime":UtilUtils.getYesterday()} UpdateLogs = ChangeLogUtils.getChangeLog(Api, listValues) UpdateLogs = [x for x in UpdateLogs if x["fieldName"] == "Name" and "»TP»" in x["oldValue"] and "»SS»" in x["newValue"]] finalLogs = Createlogs + UpdateLogs length = str(len(finalLogs)) print(length + " checking each placement Now") finalLogs = [checkCampaign(x) for x in finalLogs if checkSubAccount(x)] finalLogs = [x for x in finalLogs if x != None] length = str(len(finalLogs)) print(length) finalPlacementArray = [] for placement in finalLogs: placementAdList = AdUtils.listAd(Api, {"placementIds":placement["id"]}) campaignAdList = AdUtils.listAd(Api, {"campaignIds":placement["campaignId"]}) campaign = CampaignUtils.getCampaign(Api, placement["campaignId"]) placementAdList = [x for x in placementAdList if "TRACKING" in x["name"] and x["archived"] == False] campaignAdList = [x for x in campaignAdList if "TRACKING" in x["name"] and x["archived"] == False] PlacementUtils.pushStaticClickTracking(Api, placement["id"]) if len(campaignAdList) < 4: pullAdsIntoCampaign(placement["campaignId"], placement, campaignAdList) campaignAdList = AdUtils.listAd(Api, {"campaignIds":placement["campaignId"]}) campaignAdList = [x for x in campaignAdList if "TRACKING" in x["name"] and x["archived"] == False] if len(placementAdList) < 4: for ad in campaignAdList: adObject = AdUtils.getAd(Api, ad["id"]) AdUtils.associatePlacement(adObject,placement,Api) finalPlacementArray.append({"Placement Name": placement["name"],"Campaign Name": campaign["name"], "Placement ID":placement["id"]}) if len(finalPlacementArray) > 0: df = pandas.DataFrame(data=finalPlacementArray)
[x for x in changeLog if x["fieldName"] == "Active status"]) for log in changeLogArray: obj = {} currentAd = AdUtils.getAd(Api, log["objectId"]) adEndDate = UtilUtils.stringToDateTimeObject(currentAd['endTime']) changeTime = UtilUtils.stringToDateTimeObject(log['changeTime']) if changeTime < adEndDate: test = 0 test = 0 for log in logs: obj = {} currentAd = AdUtils.getAd(Api, log["objectId"]) currentCampaign = CampaignUtils.getCampaign(Api, currentAd["campaignId"]) changetime = UtilUtils.formatDateTime(log["changeTime"]) userProfile = log['userProfileName'] obj["Campaign Name"] = currentCampaign["name"] obj["Ad Name"] = currentAd["name"] obj["Ad Id"] = currentAd["id"] obj["Change Time"] = changetime obj["User Profile"] = userProfile obj["Ad End Date"] = UtilUtils.formatDateTime(currentAd["endTime"]) changeLogArray.append(obj) df = pandas.DataFrame(data=changeLogArray) writer = pandas.ExcelWriter('Updated Ads Report.xlsx', engine='xlsxwriter') workbook = writer.book df.to_excel(writer, sheet_name="Info", index=False) worksheet = writer.sheets['Info']