def copy(Api, adId, campaignID): from datetime import datetime, timedelta from v3modules import CampaignUtils ad = getAd(Api, adId) startTime = (datetime.now() + timedelta(days=1)).isoformat() + "Z" adCopy = { "name": ad['name'], "campaignId": campaignID, 'endTime': ad["endTime"], "startTime": startTime, 'type': ad["type"], 'kind': ad['kind'], 'creativeRotation': ad['creativeRotation'], "deliverySchedule": ad["deliverySchedule"], 'sslRequired': ad['sslRequired'], 'sslCompliant': ad['sslCompliant'], 'clickThroughUrlSuffixProperties': ad['clickThroughUrlSuffixProperties'], "placementAssignments": [], "active": False } creativeList = getCreatives(Api, adId) creativeAssociations = CampaignUtils.getCreativeAssociation( Api, campaignID) for element in creativeList: if element not in creativeAssociations: print( "creative with number {0} not found. Inserting into Campaign". format(element)) CampaignUtils.insertCreativeAssociation(Api, element, campaignID) return adCopy
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 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 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
"I1": "Creative Rotation", "J1": "Creative File 1", "K1": "Creative File 2", "L1": "Creative File 3", "M1": "Creative File 4", "N1": "Creative File 5" } urlObject = {'A1': "Creative File", "B1": "Creative URL"} try: campaignName = excel["TPS Placements"].iloc[0]["Campaign"] except: campaignName = excel["SS Placements"].iloc[0]["Campaign"] listValues = {"searchString": campaignName} campaign = CampaignUtils.getCampaignByName(Api, listValues) listValules = {"campaignIds": campaign["id"]} placementList = [ x for x in PlacementUtils.listPlacement(Api, listValules) if x["archived"] == False ] TPSPlacements = [x for x in placementList if "_TPS_" in x["name"]] SSPlacements = [x for x in placementList if "_SS_" in x["name"]] if len(TPSPlacements) > 0: TPSsheet = updateSheet(excel["TPS Placements"], TPSPlacements) excel["TPS Placements"] = TPSsheet TPSsheet.to_excel(writer, sheet_name="TPS Placements", index=False) TPSworksheet = writer.sheets['TPS Placements'] for obj in headerObject: TPSworksheet.write(obj, headerObject[obj], headerBlue) for obj in ChangesArray:
from v3modules import DCMAPI, CreativeUtils, CampaignUtils Api = DCMAPI.DCMAPI() def activateCreative(creativeAssets): for asset in creativeAssets: asset["active"] = True return creativeAssets listValues = {"archived":False, "searchString":"2019","subaccountId":"23262"} campaignList = CampaignUtils.getCampaignList(Api, listValues) for campaign in campaignList: listValues = {"active": True, "archived": False,"campaignId":campaign["id"]} creativeList = CreativeUtils.listCreatives(Api, listValues) for creative in creativeList: try: assets = [x for x in creative["creativeAssets"] if x["active"] == False] except: continue if len(assets) == 0: continue else: creativeAssets = activateCreative(creative["creativeAssets"]) payload = {"creativeAssets": creativeAssets} CreativeUtils.updateCreative(Api, creative["id"], payload)
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
[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']
from v3modules import CampaignUtils, DCMAPI, AdUtils, UtilUtils import datetime import pandas as pd Api = DCMAPI.DCMAPI() AdList = [] def compareAdDates(ad): today = datetime.datetime(2017, 1, 1, 12) adDate = datetime.datetime.strptime(ad["endTime"], "%Y-%m-%dT%H:%M:%S.%fZ") return today > adDate listValues = {"subaccountId": 28400, "archived": False} CanadaCampaigns = CampaignUtils.getCampaignList(Api, listValues) for campaign in CanadaCampaigns: print("Analyzing {campaignName}".format(campaignName=campaign["name"])) listValues = { "campaignIds": campaign["id"], "active": True, "archived": False } ads = AdUtils.listAd(Api, listValues) ads = [x for x in ads if compareAdDates(x)] for ad in ads: AdUtils.deactivateAd(ad["id"], Api) AdList.append({ "name": ad["name"], "id": ad["id"], "campaign name": campaign["name"],
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]
from v3modules import DCMAPI, CampaignUtils, AdUtils Api = DCMAPI.DCMAPI() campaignList = CampaignUtils.getAllCampaigns(Api) campaignList = [x for x in campaignList if "_2018" in x["name"]] for campaign in campaignList: print(campaign["name"]) campaignId = campaign["id"] listValues = {"campaignIds": campaignId, "archived": False} adList = [ x for x in AdUtils.listAd(Api, listValues) if "Brand-neutral" not in x["name"] ] [AdUtils.deactivateAd(x["id"], Api) for x in adList]
from v3modules import DCMAPI, CampaignUtils, AdUtils, EventUtils, CreativeUtils, AdvertiserUtils, ChangeLogUtils, PlacementUtils Api = DCMAPI.DCMAPI() # advertiserSet = AdvertiserUtils.getAdvertiserSet() AdobeTagCopy = EventUtils.getEvent(Api, 2560485) allCampaigns = CampaignUtils.getAllLMA(Api) # allCampaigns = [c for c in allCampaigns if "LMA" not in c["name"]] def findAdobeImpressionPixel(campaignId): listValues = {"campaignId": campaignId} eventlist = EventUtils.listEvents(Api, listValues=listValues) for event in eventlist: if "CDK" in event["name"]: payload = {"enabled": True, "id": event["id"]} return payload for campaign in allCampaigns: # campaign["id"] = 20588848 print(campaign["name"]) impressionPayload = findAdobeImpressionPixel(campaign["id"]) if impressionPayload == None: print("adding eventBody") eventbody = { "campaignId": campaign["id"], "advertiserId": campaign['advertiserId'], "name": "CDK Impression Pixel",
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()
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)
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=["*****@*****.**", ])