Display: exclude domain extensions

75 views
Skip to first unread message

Melle

unread,
May 22, 2023, 8:21:18 AM5/22/23
to Google Ads Scripts Forum
Hi there,

I have the following script to exclude all other domain extensions that don't include .nl 
however when I try to test the script it doesn't run at all.

/**
 * @name Placement Excluder YouTube & Display
 *
 * @instructions
 *     - ⚠ Enable "New scripts experience" above google ads script ⚠
 *     - Find settings in the config variable
 *    
 * @notes
 *     - Check log files below for execution information.
 *     - Run a preview before first usage.
 *
 * @version 2.10
 *
 * @author Bas Baudoin - adsscripts.com
 *
 */

const config = {
  modus: 'list', // add 'campaign', or 'list',
  listName: 'script_display', // when in list modus, e.g. 'exclusions list' (should already exist)
  excludeDomain: true, // by default it only excludes URLs, but it can also exclude the domain
  excludeUrl: false, // exclude full url
  type: 'youtube', // 'display' or 'youtube'
  lastXdays: 1, // 0 = today, 1 = today+yesterday, etc.

  excludeDomains: ['20min.ch', '.tk', '.ru', 'viral', '.za', '.ru'], // example: ['20min.ch', '.tk', '.de', 'viral'],
  mustInclude: ['.nl'],
  exceptions: ['zaaltje'],

  // for developer
  testMode: false, // = false for normal operation
  reverse: false, // = false for normal operation
}

function main() {
  console.log('starting script...')
  const { excludeDomains, mustIncludes } = createRegexes()
  //console.log(excludeDomains)
  const startDate = getDateByDaysAgo(config.lastXdays)
  const endDate = getDateByDaysAgo(0)
  console.log(startDate, endDate)
  const rev = config.reverse && config.testMode ? 'NOT ' : ''

  let qBase = "SELECT detail_placement_view.target_url, detail_placement_view.placement_type, detail_placement_view.placement, detail_placement_view.group_placement_target_url, detail_placement_view.display_name, metrics.ctr, ad_group.name, campaign.id, campaign.name, metrics.impressions, metrics.clicks, metrics.conversions, metrics.ctr "
  qBase += 'FROM detail_placement_view '
  qBase += `WHERE segments.date BETWEEN '${startDate}' AND '${endDate}' `
  //console.log(qBase)

  console.log('Excluding 🔂 terms and domains')
  const qDomains = qBase + `AND detail_placement_view.target_url ${rev}REGEXP_MATCH '${excludeDomains}' `
  if (config.excludeDomains.length > 0) excludeLoop(qDomains)

  console.log('Excluding 🔂 "must contain"')
  const qPerformance = qBase + `AND detail_placement_view.target_url NOT REGEXP_MATCH '${mustIncludes}' `
  excludeLoop(qPerformance)
}

// --- //

function excludeLoop(q) {
  var report = AdsApp.report(q)

  let list
  if (config.listName !== '') {
    list = AdsApp.excludedPlacementLists().withCondition('Name = "' + config.listName + '"').get().next()
  }

  let exclusions = []
  const accountName = AdsApp.currentAccount().getName()
  const startDate = getDateByDaysAgo(config.lastXdays)
  const endDate = getDateByDaysAgo(0)
  const dateRange = `${startDate} - ${endDate}`

  const rows = report.rows()
 
  while (rows.hasNext()) {
    const row = rows.next()
    console.log('---')
    const placementUrl = row['detail_placement_view.target_url']
    const campaignId = row['campaign.id']
    const campaignName = row['campaign.name']
    const impressions = row['metrics.impressions']
    const clicks = row['metrics.clicks']
    const conversions = row['metrics.conversions']
    console.log('🛑 excluding', placementUrl, campaignName)

    // check if in exclusion list
    const isInExceptionList = config.exceptions.find(x => {
      if (placementUrl) {
        return placementUrl.includes(x)
      }
    })
    if (isInExceptionList) {
      console.log(`Placement excluded because it is in exclusion list: ${isInExceptionList} in ${placementUrl}`)
      continue
    }

    if (config.modus === 'campaign') {
      if (config.excludeUrl) {
        excludePlacementInCampaign(placementUrl, campaignId)
      }
     
      if (config.excludeDomain) {
        const domain = placementUrl.split('/')[0]
        if (domain.includes('.')) {
          excludePlacementInCampaign(domain, campaignId)
        }
      }
    }
   
    if (config.modus === 'list') {
      if (config.excludeUrl) {
        list.addExcludedPlacement(placementUrl)
      }
     
      if (config.excludeDomain) {
        const domain = placementUrl.split('/')[0]
        if (domain.includes('.')) {
          list.addExcludedPlacement(domain)
        }
      }
    }
   
    exclusions.push([accountName, dateRange, placementUrl, campaignName, impressions, clicks, conversions]) // not used
  }
}

function createRegexes() {
  const excludeDomains = '(^.*' + config.excludeDomains
    .map(x => x.replace(/\./g, '[.]'))
    .join('.*$)|(^.*') + '.*$)'
  const mustIncludes = '(^.*' + config.mustInclude
    .map(x => x.replace(/\./g, '[.]'))
    .join('.*$)|(^.*') + '.*$)'
  return { excludeDomains, mustIncludes }
}

function excludePlacementInCampaign(placementUrl, campaignId) {
  let campaigns
 
  if (config.type === 'youtube') {
    console.log('❗❗ cannot exclude placements in youtube campaigns via scripts, use list mode')
    // hope that google will allow this in the future (2022-07-26)
    return
  }
 
  if (config.type === 'display') {
    campaigns = AdsApp.campaigns().withIds([parseInt(campaignId)]).get()
    if (campaigns.totalNumEntities() != 1) {
      console.log('⚠ campaign Id not found ' + campaignId)
      return
    }
  }
   
  const campaign = campaigns.next()
  const res = campaign.display().newPlacementBuilder().withUrl(placementUrl).exclude()
}

function getDateByDaysAgo(daysAgo) {
  let today = new Date()
  today.setDate(today.getDate() - daysAgo)
  var formattedDate = Utilities.formatDate(today, 'PST', 'yyyy-MM-dd')
  return formattedDate
}

Google Ads Scripts Forum Advisor

unread,
May 23, 2023, 12:43:52 PM5/23/23
to adwords...@googlegroups.com
Hi,

Thank you for raising this to the Google Ads Scripts support team.

With regards to the issue you're encountering, can you further elaborate what you meant with your statement "however when I try to test the script it doesn't run at all" and provide the below needed information via Reply privately to the author option so our team can have a better view and can provide precise recommendations?
  • Google Ads account ID / CID
  • Script name
  • Screenshots which describes the issue

This message is in relation to case "ref:_00D1U1174p._5004Q2lKKpT:ref"

Thanks,
 
Google Logo Google Ads Scripts Team


Melle

unread,
May 30, 2023, 5:07:48 AM5/30/23
to Google Ads Scripts Forum
I cannot reply directly to the author. I have no rights?



Op dinsdag 23 mei 2023 om 18:43:52 UTC+2 schreef Google Ads Scripts Forum Advisor:

Asavela Ludidi

unread,
May 31, 2023, 3:45:29 AM5/31/23
to Melle via Google Ads Scripts Forum
Hi Melle,

Thank you for your response. 

- generic_campaign_may_test_1
-May - 2023 - Test Script - Asa

Error: 
image.png

image.png

image.png

image.png

This is my first code ever written, so forgive me if i have missed anything.

Regards, 
Asa Ludidi


--
-- You received this message because you are subscribed to the Google Groups AdWords Scripts Forum group. Please do not reply to this email. To post to this group or unsubscribe please visit https://developers.google.com/adwords/scripts/community.
---
You received this message because you are subscribed to the Google Groups "Google Ads Scripts Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to adwords-scrip...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/adwords-scripts/c78cf9a5-6b99-4d58-ac09-1575fa2e2914n%40googlegroups.com.

Thúy Vi Cái

unread,
May 31, 2023, 3:45:41 AM5/31/23
to Melle via Google Ads Scripts Forum

wZANhZa9Vp

Google Ads Scripts Forum Advisor

unread,
Jun 1, 2023, 10:20:38 AM6/1/23
to adwords...@googlegroups.com

Hi,



Thank you for your response.

You may send the requested details privately via the Reply to author option. Kindly note that you may need to join the Google Group for you to use this option. If this option is not available on your end still, you may send it through our email (googleadsscr...@google.com) instead.

Reply all
Reply to author
Forward
0 new messages