Automação Google Ads: Como programar alertas

Nessa série especial, reunimos alguns scripts úteis para você automatizar e aumentar o retorno de suas campanhas no Google Ads. Confira abaixo como automatizar o Google Ads para “Programação de alertas especiais”.

 

1. Detector de Anomalias da Conta – Por Google Ads. O script do Google alerta por e-mail quando sua conta apresenta um comportamento muito diferente de seu histórico. Ele faz uma comparação com as estatísticas obtidas até o dia atual com o histórico das estatísticas em relação ao mesmo dia da semana.

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* @name Account Anomaly Detector
*
* @fileoverview The Account Anomaly Detector alerts the advertiser whenever an
* advertiser account is suddenly behaving too differently from what's
* historically observed. See
* https://developers.google.com/adwords/scripts/docs/solutions/account-anomaly-detector
* for more details.
*
* @author AdWords Scripts Team [[email protected]]
*
* @version 1.1
*
* @changelog
* - version 1.1.1
* - Fixed bug in handling of reports with 0 rows.
* - version 1.1
* - Added conversions to tracked statistics.
* - version 1.0.3
* - Improved code readability and comments.
* - version 1.0.2
* - Added validation for external spreadsheet setup.
* - Updated to use report version v201609.
* - version 1.0.1
* - Improvements to time zone handling.
* - version 1.0
* - Released initial version.
*/

var SPREADSHEET_URL = 'YOUR_SPREADSHEET_URL';

var DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday'];

/**
* Configuration to be used for running reports.
*/
var REPORTING_OPTIONS = {
// Comment out the following line to default to the latest reporting version.
apiVersion: 'v201705'
};

function main() {
Logger.log('Using spreadsheet - %s.', SPREADSHEET_URL);
var spreadsheet = validateAndGetSpreadsheet(SPREADSHEET_URL);
spreadsheet.setSpreadsheetTimeZone(AdWordsApp.currentAccount().getTimeZone());

var impressionsThreshold = parseField(spreadsheet.
getRangeByName('impressions').getValue());
var clicksThreshold = parseField(spreadsheet.getRangeByName('clicks').
getValue());
var conversionsThreshold =
parseField(spreadsheet.getRangeByName('conversions').getValue());
var costThreshold = parseField(spreadsheet.getRangeByName('cost').getValue());
var weeksStr = spreadsheet.getRangeByName('weeks').getValue();
var weeks = parseInt(weeksStr.substring(0, weeksStr.indexOf(' ')));
var email = spreadsheet.getRangeByName('email').getValue();

var now = new Date();

// Basic reporting statistics are usually available with no more than a 3-hour
// delay.
var upTo = new Date(now.getTime() - 3 * 3600 * 1000);
var upToHour = parseInt(getDateStringInTimeZone('h', upTo));

if (upToHour == 1) {
// first run for the day, kill existing alerts
spreadsheet.getRangeByName('clicks_alert').clearContent();
spreadsheet.getRangeByName('impressions_alert').clearContent();
spreadsheet.getRangeByName('conversions_alert').clearContent();
spreadsheet.getRangeByName('cost_alert').clearContent();
}

var dateRangeToCheck = getDateStringInPast(0, upTo);
var dateRangeToEnd = getDateStringInPast(1, upTo);
var dateRangeToStart = getDateStringInPast(1 + weeks * 7, upTo);
var fields = 'HourOfDay,DayOfWeek,Clicks,Impressions,Conversions,Cost';
var todayQuery = 'SELECT ' + fields +
' FROM ACCOUNT_PERFORMANCE_REPORT DURING ' + dateRangeToCheck + ',' +
dateRangeToCheck;
var pastQuery = 'SELECT ' + fields +
' FROM ACCOUNT_PERFORMANCE_REPORT WHERE DayOfWeek=' +
DAYS[getDateStringInTimeZone('u', now)].toUpperCase() +
' DURING ' + dateRangeToStart + ',' + dateRangeToEnd;

var todayStats = getReportStats(todayQuery, upToHour, 1);
var pastStats = getReportStats(pastQuery, upToHour, weeks);

var statsExist = true;
if (typeof todayStats === 'undefined' || typeof pastStats === 'undefined') {
statsExist = false;
}

var alertText = [];
if (statsExist && impressionsThreshold &&
todayStats.impressions < pastStats.impressions * impressionsThreshold) {
var ImpressionsAlert = ' Impressions are too low: ' +
todayStats.impressions + ' impressions by ' + upToHour +
':00, expecting at least ' +
parseInt(pastStats.impressions * impressionsThreshold);
writeAlert(spreadsheet, 'impressions_alert', alertText, ImpressionsAlert,
upToHour);
}
if (statsExist && clicksThreshold &&
todayStats.clicks < pastStats.clicks * clicksThreshold) {
var clickAlert = ' Clicks are too low: ' + todayStats.clicks +
' clicks by ' + upToHour + ':00, expecting at least ' +
(pastStats.clicks * clicksThreshold).toFixed(1);
writeAlert(spreadsheet, 'clicks_alert', alertText, clickAlert, upToHour);
}
if (statsExist && conversionsThreshold &&
todayStats.conversions < pastStats.conversions * conversionsThreshold) {
var conversionsAlert =
' Conversions are too low: ' + todayStats.conversions +
' conversions by ' + upToHour + ':00, expecting at least ' +
(pastStats.conversions * conversionsThreshold).toFixed(1);
writeAlert(
spreadsheet, 'conversions_alert', alertText, conversionsAlert,
upToHour);
}
if (statsExist && costThreshold &&
todayStats.cost > pastStats.cost * costThreshold) {
var costAlert = ' Cost is too high: ' + todayStats.cost + ' ' +
AdWordsApp.currentAccount().getCurrencyCode() + ' by ' + upToHour +
':00, expecting at most ' +
(pastStats.cost * costThreshold).toFixed(2);
writeAlert(spreadsheet, 'cost_alert', alertText, costAlert, upToHour);
}

if (alertText.length > 0 && email && email.length > 0) {
MailApp.sendEmail(email,
'AdWords Account ' + AdWordsApp.currentAccount().getCustomerId() +
' misbehaved.',
'Your account ' + AdWordsApp.currentAccount().getCustomerId() +
' is not performing as expected today: \n\n' + alertText.join('\n') +
'\n\nLog into AdWords and take a look.\n\nAlerts dashboard: ' +
SPREADSHEET_URL);
}

writeDataToSpreadsheet(spreadsheet, now, statsExist, todayStats, pastStats,
AdWordsApp.currentAccount().getCustomerId());
}

function toFloat(value) {
value = value.toString().replace(/,/g, '');
return parseFloat(value);
}

function parseField(value) {
if (value == 'No alert') {
return null;
} else {
return toFloat(value);
}
}

/**
* Runs an AdWords report query for a number of weeks and return the average
* values for the stats.
*
* @param {string} query The formatted report query.
* @param {int} hours The limit hour of day for considering the report rows.
* @param {int} weeks The number of weeks for the past stats.
* @return {Object} An object containing the average values for the stats.
*/
function getReportStats(query, hours, weeks) {
var reportRows = [];
var report = AdWordsApp.report(query, REPORTING_OPTIONS);
var rows = report.rows();
while (rows.hasNext()) {
reportRows.push(rows.next());
}
return accumulateRows(reportRows, hours, weeks);
}

function accumulateRows(rows, hours, weeks) {
var result = {clicks: 0, impressions: 0, conversions: 0, cost: 0};

for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var hour = row['HourOfDay'];
if (hour < hours) {
result = addRow(row, result, 1 / weeks);
}
}
return result;
}

function addRow(row, previous, coefficient) {
if (!coefficient) {
coefficient = 1;
}
if (row == null) {
row = {Clicks: 0, Impressions: 0, Conversions: 0, Cost: 0};
}
if (!previous) {
return {
clicks: parseInt(row['Clicks']) * coefficient,
impressions: parseInt(row['Impressions']) * coefficient,
conversions: parseInt(row['Conversions']) * coefficient,
cost: toFloat(row['Cost']) * coefficient
};
} else {
return {
clicks: parseInt(row['Clicks']) * coefficient + previous.clicks,
impressions:
parseInt(row['Impressions']) * coefficient + previous.impressions,
conversions:
parseInt(row['Conversions']) * coefficient + previous.conversions,
cost: toFloat(row['Cost']) * coefficient + previous.cost
};
}
}

/**
* Produces a formatted string representing a date in the past of a given date.
*
* @param {number} numDays The number of days in the past.
* @param {date} date A date object. Defaults to the current date.
* @return {string} A formatted string in the past of the given date.
*/
function getDateStringInPast(numDays, date) {
date = date || new Date();
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var past = new Date(date.getTime() - numDays * MILLIS_PER_DAY);
return getDateStringInTimeZone('yyyyMMdd', past);
}

/**
* Produces a formatted string representing a given date in a given time zone.
*
* @param {string} format A format specifier for the string to be produced.
* @param {date} date A date object. Defaults to the current date.
* @param {string} timeZone A time zone. Defaults to the account's time zone.
* @return {string} A formatted string of the given date in the given time zone.
*/
function getDateStringInTimeZone(format, date, timeZone) {
date = date || new Date();
timeZone = timeZone || AdWordsApp.currentAccount().getTimeZone();
return Utilities.formatDate(date, timeZone, format);
}

/**
* Validates the provided spreadsheet URL and email address
* to make sure that they're set up properly. Throws a descriptive error message
* if validation fails.
*
* @param {string} spreadsheeturl The URL of the spreadsheet to open.
* @return {Spreadsheet} The spreadsheet object itself, fetched from the URL.
* @throws {Error} If the spreadsheet URL or email hasn't been set
*/
function validateAndGetSpreadsheet(spreadsheeturl) {
if (spreadsheeturl == 'YOUR_SPREADSHEET_URL') {
throw new Error('Please specify a valid Spreadsheet URL. You can find' +
' a link to a template in the associated guide for this script.');
}
var spreadsheet = SpreadsheetApp.openByUrl(spreadsheeturl);
var email = spreadsheet.getRangeByName('email').getValue();
if ('[email protected]' == email) {
throw new Error('Please either set a custom email address in the' +
' spreadsheet, or set the email field in the spreadsheet to blank' +
' to send no email.');
}
return spreadsheet;
}

/**
* Writes the alert time in the spreadsheet and push the alert message to the
* list of messages.
*
* @param {Spreadsheet} spreadsheet The dashboard spreadsheet.
* @param {string} rangeName The named range in the spreadsheet.
* @param {Array<string>} alertText The list of alert messages.
* @param {string} alertMessage The alert message.
* @param {int} hour The limit hour used to get the stats.
*/
function writeAlert(spreadsheet, rangeName, alertText, alertMessage, hour) {
var range = spreadsheet.getRangeByName(rangeName);
if (!range.getValue() || range.getValue().length == 0) {
alertText.push(alertMessage);
range.setValue('Alerting ' + hour + ':00');
}
}

/**
* Writes the data to the spreadsheet.
*
* @param {Spreadsheet} spreadsheet The dashboard spreadsheet.
* @param {Date} now The date corresponding to the running time of the script.
* @param {boolean} statsExist A boolean that indicates the existence of stats.
* @param {Object} todayStats The stats for today.
* @param {Object} pastStats The past stats for the period defined in the
* spreadsheet.
* @param {string} accountId The account ID.
*/
function writeDataToSpreadsheet(spreadsheet, now, statsExist, todayStats,
pastStats, accountId) {
spreadsheet.getRangeByName('date').setValue(now);
spreadsheet.getRangeByName('account_id').setValue(accountId);
spreadsheet.getRangeByName('timestamp').setValue(
getDateStringInTimeZone('E HH:mm:ss z', now));

if (statsExist) {
var dataRows = [
[todayStats.impressions, pastStats.impressions.toFixed(0)],
[todayStats.clicks, pastStats.clicks.toFixed(1)],
[todayStats.conversions, pastStats.conversions.toFixed(1)],
[todayStats.cost, pastStats.cost.toFixed(2)]
];
spreadsheet.getRangeByName('data').setValues(dataRows);
}
}

 

Como configurar

 

2. Verificador de Links – Por Google Ads. Verifique se seus anúncios não estão direcionando para uma página 404 com esse script. O script vasculha suas palavras-chave, anúncios e sitelinks em busca de páginas de erro e além de alertar por e-mail ele também cria um relatório.

// Copyright 2016, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* @name Link Checker
*
* @overview The Link Checker script iterates through the ads, keywords, and
* sitelinks in your account and makes sure their URLs do not produce "Page
* not found" or other types of error responses. See
* https://developers.google.com/adwords/scripts/docs/solutions/link-checker
* for more details.
*
* @author AdWords Scripts Team [[email protected]]
*
* @version 2.1
*
* @changelog
* - version 2.1
* - Added expansion of conditional ValueTrack parameters (e.g. ifmobile).
* - Added expanded text ad and other ad format support.
* - version 2.0.3
* - Added validation for external spreadsheet setup.
* - version 2.0.2
* - Allow the custom tracking label to include spaces.
* - version 2.0.1
* - Catch and output all UrlFetchApp exceptions.
* - version 2.0
* - Completely revised the script to work on larger accounts.
* - Check URLs in campaign and ad group sitelinks.
* - version 1.2
* - Released initial version.
*/

var CONFIG = {
// URL of the spreadsheet template.
// This should be a copy of https://goo.gl/8YLeMj.
SPREADSHEET_URL: 'YOUR_SPREADSHEET_URL',

// Array of addresses to be alerted via email if issues are found.
RECIPIENT_EMAILS: [
'YOUR_EMAIL_HERE'
],

// Label to use when a link has been checked.
LABEL: 'LinkChecker_Done',

// Number of milliseconds to sleep after each URL request. If your URLs are
// all on one or a few domains, use this throttle to reduce the load that the
// script imposes on your web server(s).
THROTTLE: 0,

// Number of seconds before timeout that the script should stop checking URLs
// to make sure it has time to output its findings.
TIMEOUT_BUFFER: 120
};

/**
* Parameters controlling the script's behavior after hitting a UrlFetchApp
* QPS quota limit.
*/
var QUOTA_CONFIG = {
INIT_SLEEP_TIME: 250,
BACKOFF_FACTOR: 2,
MAX_TRIES: 5
};

/**
* Exceptions that prevent the script from finishing checking all URLs in an
* account but allow it to resume next time.
*/
var EXCEPTIONS = {
QPS: 'Reached UrlFetchApp QPS limit',
LIMIT: 'Reached UrlFetchApp daily quota',
TIMEOUT: 'Approached script execution time limit'
};

/**
* Named ranges in the spreadsheet.
*/
var NAMES = {
CHECK_AD_URLS: 'checkAdUrls',
CHECK_KEYWORD_URLS: 'checkKeywordUrls',
CHECK_SITELINK_URLS: 'checkSitelinkUrls',
CHECK_PAUSED_ADS: 'checkPausedAds',
CHECK_PAUSED_KEYWORDS: 'checkPausedKeywords',
CHECK_PAUSED_SITELINKS: 'checkPausedSitelinks',
VALID_CODES: 'validCodes',
EMAIL_EACH_RUN: 'emailEachRun',
EMAIL_NON_ERRORS: 'emailNonErrors',
EMAIL_ON_COMPLETION: 'emailOnCompletion',
SAVE_ALL_URLS: 'saveAllUrls',
FREQUENCY: 'frequency',
DATE_STARTED: 'dateStarted',
DATE_COMPLETED: 'dateCompleted',
DATE_EMAILED: 'dateEmailed',
NUM_ERRORS: 'numErrors',
RESULT_HEADERS: 'resultHeaders',
ARCHIVE_HEADERS: 'archiveHeaders'
};

function main() {
var spreadsheet = validateAndGetSpreadsheet(CONFIG.SPREADSHEET_URL);
validateEmailAddresses(CONFIG.RECIPIENT_EMAILS);
spreadsheet.setSpreadsheetTimeZone(AdWordsApp.currentAccount().getTimeZone());

var options = loadOptions(spreadsheet);
var status = loadStatus(spreadsheet);

if (!status.dateStarted) {
// This is the very first execution of the script.
startNewAnalysis(spreadsheet);
} else if (status.dateStarted > status.dateCompleted) {
Logger.log('Resuming work from a previous execution.');
} else if (dayDifference(status.dateStarted, new Date()) <
options.frequency) {
Logger.log('Waiting until ' + options.frequency +
' days have elapsed since the start of the last analysis.');
return;
} else {
// Enough time has passed since the last analysis to start a new one.
removeLabels([CONFIG.LABEL]);
startNewAnalysis(spreadsheet);
}

var results = analyzeAccount(options);
outputResults(results, options);
}

/**
* Checks as many new URLs as possible that have not previously been checked,
* subject to quota and time limits.
*
* @param {Object} options Dictionary of options.
* @return {Object} An object with fields for the URLs checked and an indication
* if the analysis was completed (no remaining URLs to check).
*/
function analyzeAccount(options) {
// Ensure the label exists before attempting to retrieve already checked URLs.
ensureLabels([CONFIG.LABEL]);

var checkedUrls = getAlreadyCheckedUrls(options);
var urlChecks = [];
var didComplete = false;

try {
// If the script throws an exception, didComplete will remain false.
didComplete = checkUrls(checkedUrls, urlChecks, options);
} catch(e) {
if (e == EXCEPTIONS.QPS ||
e == EXCEPTIONS.LIMIT ||
e == EXCEPTIONS.TIMEOUT) {
Logger.log('Stopped checking URLs early because: ' + e);
Logger.log('Checked URLs will still be output.');
} else {
throw e;
}
}

return {
urlChecks: urlChecks,
didComplete: didComplete
};
}

/**
* Outputs the results to a spreadsheet and sends emails if appropriate.
*
* @param {Object} results An object with fields for the URLs checked and an
* indication if the analysis was completed (no remaining URLs to check).
* @param {Object} options Dictionary of options.
*/
function outputResults(results, options) {
var spreadsheet = SpreadsheetApp.openByUrl(CONFIG.SPREADSHEET_URL);

var numErrors = countErrors(results.urlChecks, options);
Logger.log('Found ' + numErrors + ' this execution.');

saveUrlsToSpreadsheet(spreadsheet, results.urlChecks, options);

// Reload the status to get the total number of errors for the entire
// analysis, which is calculated by the spreadsheet.
status = loadStatus(spreadsheet);

if (results.didComplete) {
spreadsheet.getRangeByName(NAMES.DATE_COMPLETED).setValue(new Date());
Logger.log('Found ' + status.numErrors + ' across the entire analysis.');
}

if (CONFIG.RECIPIENT_EMAILS) {
if (!results.didComplete && options.emailEachRun &&
(options.emailNonErrors || numErrors > 0)) {
sendIntermediateEmail(spreadsheet, numErrors);
}

if (results.didComplete &&
(options.emailEachRun || options.emailOnCompletion) &&
(options.emailNonErrors || status.numErrors > 0)) {
sendFinalEmail(spreadsheet, status.numErrors);
}
}
}

/**
* Loads data from a spreadsheet based on named ranges. Strings 'Yes' and 'No'
* are converted to booleans. One-dimensional ranges are converted to arrays
* with blank cells omitted. Assumes each named range exists.
*
* @param {Object} spreadsheet The spreadsheet object.
* @param {Array.<string>} names A list of named ranges that should be loaded.
* @return {Object} A dictionary with the names as keys and the values
* as the cell values from the spreadsheet.
*/
function loadDatabyName(spreadsheet, names) {
var data = {};

for (var i = 0; i < names.length; i++) {
var name = names[i];
var range = spreadsheet.getRangeByName(name);

if (range.getNumRows() > 1 && range.getNumColumns() > 1) {
// Name refers to a 2d range, so load it as a 2d array.
data[name] = range.getValues();
} else if (range.getNumRows() == 1 && range.getNumColumns() == 1) {
// Name refers to a single cell, so load it as a value and replace
// Yes/No with boolean true/false.
data[name] = range.getValue();
data[name] = data[name] === 'Yes' ? true : data[name];
data[name] = data[name] === 'No' ? false : data[name];
} else {
// Name refers to a 1d range, so load it as an array (regardless of
// whether the 1d range is oriented horizontally or vertically).
var isByRow = range.getNumRows() > 1;
var limit = isByRow ? range.getNumRows() : range.getNumColumns();
var cellValues = range.getValues();

data[name] = [];
for (var j = 0; j < limit; j++) {
var cellValue = isByRow ? cellValues[j][0] : cellValues[0][j];
if (cellValue) {
data[name].push(cellValue);
}
}
}
}

return data;
}

/**
* Loads options from the spreadsheet.
*
* @param {Object} spreadsheet The spreadsheet object.
* @return {Object} A dictionary of options.
*/
function loadOptions(spreadsheet) {
return loadDatabyName(spreadsheet,
[NAMES.CHECK_AD_URLS, NAMES.CHECK_KEYWORD_URLS,
NAMES.CHECK_SITELINK_URLS, NAMES.CHECK_PAUSED_ADS,
NAMES.CHECK_PAUSED_KEYWORDS, NAMES.CHECK_PAUSED_SITELINKS,
NAMES.VALID_CODES, NAMES.EMAIL_EACH_RUN,
NAMES.EMAIL_NON_ERRORS, NAMES.EMAIL_ON_COMPLETION,
NAMES.SAVE_ALL_URLS, NAMES.FREQUENCY]);
}

/**
* Loads state information from the spreadsheet.
*
* @param {Object} spreadsheet The spreadsheet object.
* @return {Object} A dictionary of status information.
*/
function loadStatus(spreadsheet) {
return loadDatabyName(spreadsheet,
[NAMES.DATE_STARTED, NAMES.DATE_COMPLETED,
NAMES.DATE_EMAILED, NAMES.NUM_ERRORS]);
}

/**
* Saves the start date to the spreadsheet and archives results of the last
* analysis to a separate sheet.
*
* @param {Object} spreadsheet The spreadsheet object.
*/
function startNewAnalysis(spreadsheet) {
Logger.log('Starting a new analysis.');

spreadsheet.getRangeByName(NAMES.DATE_STARTED).setValue(new Date());

// Helper method to get the output area on the results or archive sheets.
var getOutputRange = function(rangeName) {
var headers = spreadsheet.getRangeByName(rangeName);
return headers.offset(1, 0, headers.getSheet().getDataRange().getLastRow());
};

getOutputRange(NAMES.ARCHIVE_HEADERS).clearContent();

var results = getOutputRange(NAMES.RESULT_HEADERS);
results.copyTo(getOutputRange(NAMES.ARCHIVE_HEADERS));

getOutputRange(NAMES.RESULT_HEADERS).clearContent();
}

/**
* Counts the number of errors in the results.
*
* @param {Array.<Object>} urlChecks A list of URL check results.
* @param {Object} options Dictionary of options.
* @return {number} The number of errors in the results.
*/
function countErrors(urlChecks, options) {
var numErrors = 0;

for (var i = 0; i < urlChecks.length; i++) {
if (options.validCodes.indexOf(urlChecks[i].responseCode) == -1) {
numErrors++;
}
}

return numErrors;
}

/**
* Saves URLs for a particular account to the spreadsheet starting at the first
* unused row.
*
* @param {Object} spreadsheet The spreadsheet object.
* @param {Array.<Object>} urlChecks A list of URL check results.
* @param {Object} options Dictionary of options.
*/
function saveUrlsToSpreadsheet(spreadsheet, urlChecks, options) {
// Build each row of output values in the order of the columns.
var outputValues = [];
for (var i = 0; i < urlChecks.length; i++) {
var urlCheck = urlChecks[i];

if (options.saveAllUrls ||
options.validCodes.indexOf(urlCheck.responseCode) == -1) {
outputValues.push([
urlCheck.customerId,
new Date(urlCheck.timestamp),
urlCheck.url,
urlCheck.responseCode,
urlCheck.entityType,
urlCheck.campaign,
urlCheck.adGroup,
urlCheck.ad,
urlCheck.keyword,
urlCheck.sitelink
]);
}
}

if (outputValues.length > 0) {
// Find the first open row on the Results tab below the headers and create a
// range large enough to hold all of the output, one per row.
var headers = spreadsheet.getRangeByName(NAMES.RESULT_HEADERS);
var lastRow = headers.getSheet().getDataRange().getLastRow();
var outputRange = headers.offset(lastRow - headers.getRow() + 1,
0, outputValues.length);
outputRange.setValues(outputValues);
}

for (var i = 0; i < CONFIG.RECIPIENT_EMAILS.length; i++) {
spreadsheet.addEditor(CONFIG.RECIPIENT_EMAILS[i]);
}
}

/**
* Sends an email to a list of email addresses with a link to the spreadsheet
* and the results of this execution of the script.
*
* @param {Object} spreadsheet The spreadsheet object.
* @param {boolean} numErrors The number of errors found in this execution.
*/
function sendIntermediateEmail(spreadsheet, numErrors) {
spreadsheet.getRangeByName(NAMES.DATE_EMAILED).setValue(new Date());

MailApp.sendEmail(CONFIG.RECIPIENT_EMAILS.join(','),
'Link Checker Results',
'The Link Checker script found ' + numErrors + ' URLs with errors in ' +
'an execution that just finished. See ' +
spreadsheet.getUrl() + ' for details.');
}

/**
* Sends an email to a list of email addresses with a link to the spreadsheet
* and the results across the entire account.
*
* @param {Object} spreadsheet The spreadsheet object.
* @param {boolean} numErrors The number of errors found in the entire account.
*/
function sendFinalEmail(spreadsheet, numErrors) {
spreadsheet.getRangeByName(NAMES.DATE_EMAILED).setValue(new Date());

MailApp.sendEmail(CONFIG.RECIPIENT_EMAILS.join(','),
'Link Checker Results',
'The Link Checker script found ' + numErrors + ' URLs with errors ' +
'across its entire analysis. See ' +
spreadsheet.getUrl() + ' for details.');
}

/**
* Retrieves all final URLs and mobile final URLs in the account across ads,
* keywords, and sitelinks that were checked in a previous run, as indicated by
* them having been labeled.
*
* @param {Object} options Dictionary of options.
* @return {Object} A map of previously checked URLs with the URL as the key.
*/
function getAlreadyCheckedUrls(options) {
var urlMap = {};

var addToMap = function(items) {
for (var i = 0; i < items.length; i++) {
var urls = expandUrlModifiers(items[i]);
urls.forEach(function(url) {
urlMap[url] = true;
});
}
};

if (options.checkAdUrls) {
addToMap(getUrlsBySelector(AdWordsApp.ads().
withCondition(labelCondition(true))));
}

if (options.checkKeywordUrls) {
addToMap(getUrlsBySelector(AdWordsApp.keywords().
withCondition(labelCondition(true))));
}

if (options.checkSitelinkUrls) {
addToMap(getAlreadyCheckedSitelinkUrls());
}

return urlMap;
}

/**
* Retrieves all final URLs and mobile final URLs for campaign and ad group
* sitelinks.
*
* @return {Array.<string>} An array of URLs.
*/
function getAlreadyCheckedSitelinkUrls() {
var urls = [];

// Helper method to get campaign or ad group sitelink URLs.
var addSitelinkUrls = function(selector) {
var iterator = selector.withCondition(labelCondition(true)).get();

while (iterator.hasNext()) {
var entity = iterator.next();
var sitelinks = entity.extensions().sitelinks();
urls = urls.concat(getUrlsBySelector(sitelinks));
}
};

addSitelinkUrls(AdWordsApp.campaigns());
addSitelinkUrls(AdWordsApp.adGroups());

return urls;
}

/**
* Retrieves all URLs in the entities specified by a selector.
*
* @param {Object} selector The selector specifying the entities to use.
* The entities should be of a type that has a urls() method.
* @return {Array.<string>} An array of URLs.
*/
function getUrlsBySelector(selector) {
var urls = [];
var entities = selector.get();

// Helper method to add the url to the list if it exists.
var addToList = function(url) {
if (url) {
urls.push(url);
}
};

while (entities.hasNext()) {
var entity = entities.next();

addToList(entity.urls().getFinalUrl());
addToList(entity.urls().getMobileFinalUrl());
}

return urls;
}

/**
* Retrieves all final URLs and mobile final URLs in the account across ads,
* keywords, and sitelinks, and checks their response code. Does not check
* previously checked URLs.
*
* @param {Object} checkedUrls A map of previously checked URLs with the URL as
* the key.
* @param {Array.<Object>} urlChecks An array into which the results of each URL
* check will be inserted.
* @param {Object} options Dictionary of options.
* @return {boolean} True if all URLs were checked.
*/
function checkUrls(checkedUrls, urlChecks, options) {
var didComplete = true;

// Helper method to add common conditions to ad group and keyword selectors.
var addConditions = function(selector, includePaused) {
var statuses = ['ENABLED'];
if (includePaused) {
statuses.push('PAUSED');
}

var predicate = ' IN [' + statuses.join(',') + ']';
return selector.withCondition(labelCondition(false)).
withCondition('Status' + predicate).
withCondition('CampaignStatus' + predicate).
withCondition('AdGroupStatus' + predicate);
};

if (options.checkAdUrls) {
didComplete = didComplete && checkUrlsBySelector(checkedUrls, urlChecks,
addConditions(AdWordsApp.ads().withCondition('CreativeFinalUrls != ""'),
options.checkPausedAds));
}

if (options.checkKeywordUrls) {
didComplete = didComplete && checkUrlsBySelector(checkedUrls, urlChecks,
addConditions(AdWordsApp.keywords().withCondition('FinalUrls != ""'),
options.checkPausedKeywords));
}

if (options.checkSitelinkUrls) {
didComplete = didComplete &&
checkSitelinkUrls(checkedUrls, urlChecks, options);
}

return didComplete;
}

/**
* Retrieves all final URLs and mobile final URLs in a selector and checks them
* for a valid response code. Does not check previously checked URLs. Labels the
* entity that it was checked, if possible.
*
* @param {Object} checkedUrls A map of previously checked URLs with the URL as
* the key.
* @param {Array.<Object>} urlChecks An array into which the results of each URL
* check will be inserted.
* @param {Object} selector The selector specifying the entities to use.
* The entities should be of a type that has a urls() method.
* @return {boolean} True if all URLs were checked.
*/
function checkUrlsBySelector(checkedUrls, urlChecks, selector) {
var customerId = AdWordsApp.currentAccount().getCustomerId();
var iterator = selector.get();
var entities = [];

// Helper method to check a URL.
var checkUrl = function(entity, url) {
if (!url) {
return;
}

var urlsToCheck = expandUrlModifiers(url);

for (var i = 0; i < urlsToCheck.length; i++) {
var expandedUrl = urlsToCheck[i];
if (checkedUrls[expandedUrl]) {
continue;
}

var responseCode = requestUrl(expandedUrl);
var entityType = entity.getEntityType();

urlChecks.push({
customerId: customerId,
timestamp: new Date(),
url: expandedUrl,
responseCode: responseCode,
entityType: entityType,
campaign: entity.getCampaign ? entity.getCampaign().getName() : '',
adGroup: entity.getAdGroup ? entity.getAdGroup().getName() : '',
ad: entityType == 'Ad' ? getAdAsText(entity) : '',
keyword: entityType == 'Keyword' ? entity.getText() : '',
sitelink: entityType.indexOf('Sitelink') != -1 ?
entity.getLinkText() : ''
});

checkedUrls[expandedUrl] = true;
}
};

while (iterator.hasNext()) {
entities.push(iterator.next());
}

for (var i = 0; i < entities.length; i++) {
var entity = entities[i];

checkUrl(entity, entity.urls().getFinalUrl());
checkUrl(entity, entity.urls().getMobileFinalUrl());

// Sitelinks do not have labels.
if (entity.applyLabel) {
entity.applyLabel(CONFIG.LABEL);
checkTimeout();
}
}

// True only if we did not breach an iterator limit.
return entities.length == iterator.totalNumEntities();
}

/**
* Retrieves a text representation of an ad, casting the ad to the appropriate
* type if necessary.
*
* @param {Ad} ad The ad object.
* @return {string} The text representation.
*/
function getAdAsText(ad) {
// There is no AdTypeSpace method for textAd
if (ad.getType() === 'TEXT_AD') {
return ad.getHeadline();
} else if (ad.isType().expandedTextAd()) {
var eta = ad.asType().expandedTextAd();
return eta.getHeadlinePart1() + ' - ' + eta.getHeadlinePart2();
} else if (ad.isType().gmailImageAd()) {
return ad.asType().gmailImageAd().getName();
} else if (ad.isType().gmailMultiProductAd()) {
return ad.asType().gmailMultiProductAd().getHeadline();
} else if (ad.isType().gmailSinglePromotionAd()) {
return ad.asType().gmailSinglePromotionAd().getHeadline();
} else if (ad.isType().html5Ad()) {
return ad.asType().html5Ad().getName();
} else if (ad.isType().imageAd()) {
return ad.asType().imageAd().getName();
} else if (ad.isType().responsiveDisplayAd()) {
return ad.asType().responsiveDisplayAd().getLongHeadline();
}
return 'N/A';
}

/**
* Retrieves all final URLs and mobile final URLs for campaign and ad group
* sitelinks and checks them for a valid response code. Does not check
* previously checked URLs. Labels the containing campaign or ad group that it
* has been checked.
*
* @param {Object} checkedUrls A map of previously checked URLs with the URL as
* the key.
* @param {Array.<Object>} urlChecks An array into which the results of each URL
* check will be inserted.
* @param {Object} options Dictionary of options.
* @return {boolean} True if all URLs were checked.
*/
function checkSitelinkUrls(checkedUrls, urlChecks, options) {
var didComplete = true;

// Helper method to check URLs for sitelinks in a campaign or ad group
// selector.
var checkSitelinkUrls = function(selector) {
var iterator = selector.withCondition(labelCondition(false)).get();
var entities = [];

while (iterator.hasNext()) {
entities.push(iterator.next());
}

for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
var sitelinks = entity.extensions().sitelinks();

if (sitelinks.get().hasNext()) {
didComplete = didComplete &&
checkUrlsBySelector(checkedUrls, urlChecks, sitelinks);
entity.applyLabel(CONFIG.LABEL);
checkTimeout();
}
}

// True only if we did not breach an iterator limit.
didComplete = didComplete &&
entities.length == iterator.totalNumEntities();
};

var statuses = ['ENABLED'];
if (options.checkPausedSitelinks) {
statuses.push('PAUSED');
}

var predicate = ' IN [' + statuses.join(',') + ']';
checkSitelinkUrls(AdWordsApp.campaigns().
withCondition('Status' + predicate));
checkSitelinkUrls(AdWordsApp.adGroups().
withCondition('Status' + predicate).
withCondition('CampaignStatus' + predicate));

return didComplete;
}

/**
* Expands a URL that contains ValueTrack parameters such as {ifmobile:mobile}
* to all the combinations, and returns as an array. The following pairs of
* ValueTrack parameters are currently expanded:
* 1. {ifmobile:<...>} and {ifnotmobile:<...>} to produce URLs simulating
* clicks from either mobile or non-mobile devices.
* 2. {ifsearch:<...>} and {ifcontent:<...>} to produce URLs simulating
* clicks on either the search or display networks.
* Any other ValueTrack parameters or customer parameters are stripped out from
* the URL entirely.
*
* @param {string} url The URL which may contain ValueTrack parameters.
* @return {!Array.<string>} An array of one or more expanded URLs.
*/
function expandUrlModifiers(url) {
var ifRegex = /({(if\w+):([^}]+)})/gi;
var modifiers = {};
var matches;
while (matches = ifRegex.exec(url)) {
// Tags are case-insensitive, e.g. IfMobile is valid.
modifiers[matches[2].toLowerCase()] = {
substitute: matches[0],
replacement: matches[3]
};
}
if (Object.keys(modifiers).length) {
if (modifiers.ifmobile || modifiers.ifnotmobile) {
var mobileCombinations =
pairedUrlModifierReplace(modifiers, 'ifmobile', 'ifnotmobile', url);
} else {
var mobileCombinations = [url];
}

// Store in a map on the offchance that there are duplicates.
var combinations = {};
mobileCombinations.forEach(function(url) {
if (modifiers.ifsearch || modifiers.ifcontent) {
pairedUrlModifierReplace(modifiers, 'ifsearch', 'ifcontent', url)
.forEach(function(modifiedUrl) {
combinations[modifiedUrl] = true;
});
} else {
combinations[url] = true;
}
});
var modifiedUrls = Object.keys(combinations);
} else {
var modifiedUrls = [url];
}
// Remove any custom parameters
return modifiedUrls.map(function(url) {
return url.replace(/{[0-9a-zA-Z\_\+\:]+}/g, '');
});
}

/**
* Return a pair of URLs, where each of the two modifiers is mutually exclusive,
* one for each combination. e.g. Evaluating ifmobile and ifnotmobile for a
* mobile and a non-mobile scenario.
*
* @param {Object} modifiers A map of ValueTrack modifiers.
* @param {string} modifier1 The modifier to honour in the URL.
* @param {string} modifier2 The modifier to remove from the URL.
* @param {string} url The URL potentially containing ValueTrack parameters.
* @return {Array.<string>} A pair of URLs, as a list.
*/
function pairedUrlModifierReplace(modifiers, modifier1, modifier2, url) {
return [
urlModifierReplace(modifiers, modifier1, modifier2, url),
urlModifierReplace(modifiers, modifier2, modifier1, url)
];
}

/**
* Produces a URL where the first {if...} modifier is set, and the second is
* deleted.
*
* @param {Object} mods A map of ValueTrack modifiers.
* @param {string} mod1 The modifier to honour in the URL.
* @param {string} mod2 The modifier to remove from the URL.
* @param {string} url The URL potentially containing ValueTrack parameters.
* @return {string} The resulting URL with substitions.
*/
function urlModifierReplace(mods, mod1, mod2, url) {
var modUrl = mods[mod1] ?
url.replace(mods[mod1].substitute, mods[mod1].replacement) :
url;
return mods[mod2] ? modUrl.replace(mods[mod2].substitute, '') : modUrl;
}

/**
* Requests a given URL. Retries if the UrlFetchApp QPS limit was reached,
* exponentially backing off on each retry. Throws an exception if it reaches
* the maximum number of retries. Throws an exception if the UrlFetchApp daily
* quota limit was reached.
*
* @param {string} url The URL to test.
* @return {number|string} The response code received when requesting the URL,
* or an error message.
*/
function requestUrl(url) {
var responseCode;
var sleepTime = QUOTA_CONFIG.INIT_SLEEP_TIME;
var numTries = 0;

while (numTries < QUOTA_CONFIG.MAX_TRIES && !responseCode) {
try {
// If UrlFetchApp.fetch() throws an exception, responseCode will remain
// undefined.
responseCode =
UrlFetchApp.fetch(url, {muteHttpExceptions: true}).getResponseCode();

if (CONFIG.THROTTLE > 0) {
Utilities.sleep(CONFIG.THROTTLE);
}
} catch(e) {
if (e.message.indexOf('Service invoked too many times in a short time:')
!= -1) {
Utilities.sleep(sleepTime);
sleepTime *= QUOTA_CONFIG.BACKOFF_FACTOR;
} else if (e.message.indexOf('Service invoked too many times:') != -1) {
throw EXCEPTIONS.LIMIT;
} else {
return e.message;
}
}

numTries++;
}

if (!responseCode) {
throw EXCEPTIONS.QPS;
} else {
return responseCode;
}
}

/**
* Throws an exception if the script is close to timing out.
*/
function checkTimeout() {
if (AdWordsApp.getExecutionInfo().getRemainingTime() <
CONFIG.TIMEOUT_BUFFER) {
throw EXCEPTIONS.TIMEOUT;
}
}

/**
* Returns the number of days between two dates.
*
* @param {Object} from The older Date object.
* @param {Object} to The newer (more recent) Date object.
* @return {number} The number of days between the given dates (possibly
* fractional).
*/
function dayDifference(from, to) {
return (to.getTime() - from.getTime()) / (24 * 3600 * 1000);
}

/**
* Builds a string to be used for withCondition() filtering for whether the
* label is present or not.
*
* @param {boolean} hasLabel True if the label should be present, false if the
* label should not be present.
* @return {string} A condition that can be used in withCondition().
*/
function labelCondition(hasLabel) {
return 'LabelNames ' + (hasLabel ? 'CONTAINS_ANY' : 'CONTAINS_NONE') +
' ["' + CONFIG.LABEL + '"]';
}

/**
* Retrieves an entity by name.
*
* @param {Object} selector A selector for an entity type with a Name field.
* @param {string} name The name to retrieve the entity by.
* @return {Object} The entity, if it exists, or null otherwise.
*/
function getEntityByName(selector, name) {
var entities = selector.withCondition('Name = "' + name + '"').get();

if (entities.hasNext()) {
return entities.next();
} else {
return null;
}
}

/**
* Retrieves a Label object by name.
*
* @param {string} labelName The label name to retrieve.
* @return {Object} The Label object, if it exists, or null otherwise.
*/
function getLabel(labelName) {
return getEntityByName(AdWordsApp.labels(), labelName);
}

/**
* Checks that the account has all provided labels and creates any that are
* missing. Since labels cannot be created in preview mode, throws an exception
* if a label is missing.
*
* @param {Array.<string>} labelNames An array of label names.
*/
function ensureLabels(labelNames) {
for (var i = 0; i < labelNames.length; i++) {
var labelName = labelNames[i];
var label = getLabel(labelName);

if (!label) {
if (!AdWordsApp.getExecutionInfo().isPreview()) {
AdWordsApp.createLabel(labelName);
} else {
throw 'Label ' + labelName + ' is missing and cannot be created in ' +
'preview mode. Please run the script or create the label manually.';
}
}
}
}

/**
* Removes all provided labels from the account. Since labels cannot be removed
* in preview mode, throws an exception in preview mode.
*
* @param {Array.<string>} labelNames An array of label names.
*/
function removeLabels(labelNames) {
if (AdWordsApp.getExecutionInfo().isPreview()) {
throw 'Cannot remove labels in preview mode. Please run the script or ' +
'remove the labels manually.';
}

for (var i = 0; i < labelNames.length; i++) {
var label = getLabel(labelNames[i]);

if (label) {
label.remove();
}
}
}

/**
* Validates the provided spreadsheet URL to make sure that it's set up
* properly. Throws a descriptive error message if validation fails.
*
* @param {string} spreadsheeturl The URL of the spreadsheet to open.
* @return {Spreadsheet} The spreadsheet object itself, fetched from the URL.
* @throws {Error} If the spreadsheet URL hasn't been set
*/
function validateAndGetSpreadsheet(spreadsheeturl) {
if (spreadsheeturl == 'YOUR_SPREADSHEET_URL') {
throw new Error('Please specify a valid Spreadsheet URL. You can find' +
' a link to a template in the associated guide for this script.');
}
return SpreadsheetApp.openByUrl(spreadsheeturl);
}

/**
* Validates the provided email addresses to make sure it's not the default.
* Throws a descriptive error message if validation fails.
*
* @param {Array.<string>} recipientEmails The list of email adresses.
* @throws {Error} If the list of email addresses is still the default
*/
function validateEmailAddresses(recipientEmails) {
if (recipientEmails &&
recipientEmails[0] == 'YOUR_EMAIL_HERE') {
throw new Error('Please either specify a valid email address or clear' +
' the RECIPIENT_EMAILS field.');
}
}

 

Como Configurar

 

3. Encontre Anomalias em Palavras-chave, Grupos de Anúncios e Anúncios – Por Russel Savage. O script pode identificar palavras-chave, grupos e anúncios e anúncios que estão com uma performance diferente dos outros, por exemplo, grupos de anúncios com apenas 2-3 palavras-chave trazendo todo tráfego ao site. O script também envia um e-mail resumindo as anomalias encontradas diariamente.

/**************************************
* Find the Anomalies
* Created By: Russ Savage
* Version: 1.2
* Changelog v1.2
* - Fixed divide by 0 errors
* - Changed SIG_FIGS to DECIMAL_PLACES
* Changelog v1.1
* - Added ability to tag ad anomalies as well
* FreeAdWordsScripts.com
**************************************/
var DATE_RANGE = 'LAST_30_DAYS';
var DECIMAL_PLACES = 3;
var STANDARD_DEVIATIONS = 2;
var TO = ['you@your_domain.com'];

function main() {
// This will add labels to and send emails about adgroups, keywords and ads. Remove any if you like.
var levels_to_tag = ['adgroup','keyword','ad'];
for(var x in levels_to_tag) {
var report = getContentRows(levels_to_tag[x]);
var entity_map = buildEntityMap(levels_to_tag[x]);
for(var parent_id in entity_map) {
var child_list = entity_map[parent_id];
var stats_list = Object.keys(child_list[0].stats);
for(var i in stats_list) {
var mean = getMean(child_list,stats_list[i]);
var stand_dev = getStandardDev(child_list,mean,stats_list[i]);
var label_name = stats_list[i]+"_anomaly";
report += addLabelToAnomalies(child_list,mean,stand_dev,stats_list[i],label_name,levels_to_tag[x]);
}
}
sendResultsViaEmail(report,levels_to_tag[x]);
}
}

//Takes a report and the level of reporting and sends and email
//with the report as an attachment.
function sendResultsViaEmail(report,level) {
var rows = report.match(/\n/g).length - 1;
if(rows == 0) { return; }
var options = { attachments: [Utilities.newBlob(report, 'text/csv', level+"_anomalies_"+_getDateString()+'.csv')] };
var email_body = "There are " + rows + " " + level + "s that have abnormal performance. See attachment for details.";
var subject = 'Abnormal ' + _initCap(level) + ' Entities Report - ' + _getDateString();
for(var i in TO) {
MailApp.sendEmail(TO[i], subject, email_body, options);
}
}

//Helper function to return a single row of the report formatted correctly
function toReportRow(entity,level,label_name) {
var ret_val = [AdWordsApp.currentAccount().getCustomerId(),
entity.getCampaign().getName()];
ret_val.push( (level == 'adgroup') ? entity.getName() : entity.getAdGroup().getName() );
if(level == 'keyword') {
ret_val = ret_val.concat([entity.getText(),entity.getMatchType()]);
} else if(level == 'ad') {
ret_val = ret_val.concat([entity.getHeadline(),entity.getDescription1(),entity.getDescription2(),entity.getDisplayUrl()]);
}
ret_val.push(label_name);
return '"' + ret_val.join('","') + '"\n';
}

//Helper function to return the column headings for the report
function getContentRows(level) {
var ret_val = ['AccountId','CampaignName','AdGroupName'];
if(level == 'keyword') {
ret_val = ret_val.concat(['KeywordText','MatchType']);
} else if(level == 'ad') {
ret_val = ret_val.concat(['Headline','Description1','Description2','DisplayUrl']);
}
ret_val.push('LabelName');
return '"' + ret_val.join('","') + '"\n';
}

//Function to add the labels to the entities based on the standard deviation and mean.
//It returns a csv formatted string for reporting
function addLabelToAnomalies(entites,mean,sd,stat_key,label_name,level) {
createLabelIfNeeded(label_name);
var report = '';
for(var i in entites) {
var entity = entites[i]['entity'];
var deviation = Math.abs(entites[i]['stats'][stat_key] - mean);
if(sd != 0 && deviation/sd >= STANDARD_DEVIATIONS) {
entity.applyLabel(label_name);
report += toReportRow(entity,level,label_name);
} else {
entity.removeLabel(label_name);
}
}
return report;
}

//This is a helper function to create the label if it does not already exist
function createLabelIfNeeded(name) {
if(!AdWordsApp.labels().withCondition("Name = '"+name+"'").get().hasNext()) {
AdWordsApp.createLabel(name);
}
}

//This function returns the standard deviation for a set of entities
//The stat key determines which stat to calculate it for
function getStandardDev(entites,mean,stat_key) {
var total = 0;
for(var i in entites) {
total += Math.pow(entites[i]['stats'][stat_key] - mean,2);
}
if(Math.sqrt(entites.length-1) == 0) {
return 0;
}
return round(Math.sqrt(total)/Math.sqrt(entites.length-1));
}

//Returns the mean (average) for the set of entities
//Again, stat key determines which stat to calculate this for
function getMean(entites,stat_key) {
var total = 0;
for(var i in entites) {
total += entites[i]['stats'][stat_key];
}
if(entites.length == 0) {
return 0;
}
return round(total/entites.length);
}

//This function returns a map of the entities that I am processing.
//The format for the map can be found on the first line.
//It is meant to work on AdGroups and Keywords
function buildEntityMap(entity_type) {
var map = {}; // { parent_id : [ { entity : entity, stats : entity_stats } ], ... }
var iter = getIterator(entity_type);
while(iter.hasNext()) {
var entity = iter.next();
var stats = entity.getStatsFor(DATE_RANGE);
var stats_map = getStatsMap(stats);
var parent_id = getParentId(entity_type,entity);
if(map[parent_id]) {
map[parent_id].push({entity : entity, stats : stats_map});
} else {
map[parent_id] = [{entity : entity, stats : stats_map}];
}
}
return map;
}

//Given an entity type (adgroup or keyword) this will return the parent id
function getParentId(entity_type,entity) {
switch(entity_type) {
case 'adgroup' :
return entity.getCampaign().getId();
case 'keyword':
return entity.getAdGroup().getId();
case 'ad':
return entity.getAdGroup().getId();
}
}

//Given an entity type this will return the iterator for that.
function getIterator(entity_type) {
switch(entity_type) {
case 'adgroup' :
return AdWordsApp.adGroups().forDateRange(DATE_RANGE).withCondition("Impressions > 0").get();
case 'keyword' :
return AdWordsApp.keywords().forDateRange(DATE_RANGE).withCondition("Impressions > 0").get();
case 'ad' :
return AdWordsApp.ads().forDateRange(DATE_RANGE).withCondition("Impressions > 0").get();
}
}

//This returns a map of all the stats for a given entity.
//You can comment out the things you don't really care about.
function getStatsMap(stats) {
return { // You can comment these out as needed.
avg_cpc : stats.getAverageCpc(),
avg_cpm : stats.getAverageCpm(),
avg_pv : stats.getAveragePageviews(),
avg_pos : stats.getAveragePosition(),
avg_tos : stats.getAverageTimeOnSite(),
bounce : stats.getBounceRate(),
clicks : stats.getClicks(),
cv : stats.getConversionRate(),
conv : stats.getConversions(),
cost : stats.getCost(),
ctr : stats.getCtr(),
imps : stats.getImpressions()
};
}

//Helper function to format todays date
function _getDateString() {
return Utilities.formatDate((new Date()), AdWordsApp.currentAccount().getTimeZone(), "yyyy-MM-dd");
}

//Helper function to capitalize the first letter of a string.
function _initCap(str) {
return str.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
}

// A helper function to make rounding a little easier
function round(value) {
var decimals = Math.pow(10,DECIMAL_PLACES);
return Math.round(value*decimals)/decimals;
}

 

 

4. Notificação de Anúncios Reprovados por Mensagem e E-mail – Por Derek Martin. Esse script identifica anúncios reprovados em uma planilha do Google e pode avisar por mensagem e e-mail.

/***************************************************************************************
* AdWords Account Audit -- Check Ads for disapprovals -- text if there are open issues
* Version 1.0
* Created By: Derek Martin
* DerekMartinLA.com
****************************************************************************************/

// This script was heavily inspired by Russell Savage so all credit where its due!
// Sign up at Twilio.com and get an API key (sid) and Auth code and place here
// Url: https://www.twilio.com/
var sid = 'ACxxxxxxx'; // looks like this:
var auth = 'xxxxxxxx';
var to_number = '+1234567890'; // put your phone number here
var from_number = '+1234567890'; // this is the phone number given to you by Twilio
var email_address = '[email protected]'; // put the email you want to send to here

function main() {
var campIter = AdWordsApp.campaigns().withCondition('Status = ENABLED').get();
var disapprovedList = [];

while (campIter.hasNext()) {
var camp = campIter.next();
adsIter = camp.ads().withCondition('Status = ENABLED').withCondition('ApprovalStatus = DISAPPROVED').get();

info('Checking ' + camp.getName());
numDisapproved = adsIter.totalNumEntities();

if (numDisapproved > 0) { // there are disapproved ads

while (adsIter.hasNext()) {
var ad = adsIter.next();

warn('Ad ' + ad.getId() + ' : Headline : ' + ad.getHeadline() + ' is currently DISAPPROVED.');
disapproved = new disapprovedAd(camp.getName(), ad.getAdGroup().getName(), ad.getHeadline(), ad.getDescription1(), ad.getDescription2(), ad.getDisplayUrl(), ad.getDestinationUrl(), ad.getDisapprovalReasons());
// info(camp.getName() + ' ' + ad.getAdGroup().getName() + ' ' + ad.getHeadline() + ' ' + ad.getDescription1() + ' ' + ad.getDescription2() + ' ' + ad.getDisapprovalReasons());
disapprovedList.push(disapproved);

} // dont do anything if disapproved ads are zero
// info('hitting the else statement');

// ads are collected, text message

// prepare spreadsheet and email and then text msg

info('Collected all disapproved ads, expect an email with report results momentarily');

var fileUrl = createSpreadsheet(disapprovedList);
info(' ');
info('Or you can find it here: ' + fileUrl);
var clientName = AdWordsApp.currentAccount().getName().split("-");
sendAnEmail(clientName[0], disapprovedList.toString(), fileUrl);

// The third parameter is what you want the text or voice message to say

var client = new Twilio(sid,auth);
var clientName = AdWordsApp.currentAccount().getName().split();
var warningMsg = 'ALERT: ' + clientName[0] + ' has ' + numDisapproved + ' disapproved ads in campaign: ' + camp.getName() + '\n' + '\n';
warningMsg += 'Click here: ' + fileUrl + ' to review the disapproved list.';
client.sendMessage(to_number,from_number,warningMsg);

} // end of campaign iteration
}
}

function createSpreadsheet(results) {
var newSS = SpreadsheetApp.create('disapprovedAds', results.length, 26);

var sheet = newSS.getActiveSheet();
var resultList = results;

var columnNames = ["Campaign", "Ad Group","Headline", "Description1","Description2","Display URL","Destination URL","Disapproval Reason"];

var headersRange = sheet.getRange(1, 1, 1, columnNames.length);

headersRange.setValues([columnNames]);

var i = 0;

for each (headline in resultList) {

var campaign, adgroup, headline, description1, description2, displayUrl, destinationUrl, disapprovalReasons;

campaign = resultList[i].campaign;
adgroup = resultList[i].adgroup;
headline = resultList[i].headline;
description1 = resultList[i].d1;
description2 = resultList[i].d2;
displayUrl = resultList[i].displayUrl;
destinationUrl = resultList[i].destinationUrl;
disapprovalReasons = resultList[i].disapprovalReasons;

sheet.appendRow([campaign, adgroup, headline, description1, description2, displayUrl, destinationUrl, disapprovalReasons]);

// Sets the first column to a width which fits the text
sheet.setColumnWidth(1, 300);
sheet.setColumnWidth(2, 300);
sheet.setColumnWidth(3, 300);
sheet.setColumnWidth(4, 300);
sheet.setColumnWidth(5, 300);
sheet.setColumnWidth(6, 300);
sheet.setColumnWidth(7, 300);
sheet.setColumnWidth(8, 300);

i++;
}

return newSS.getUrl();

}

function sendAnEmail (clientName, results, fileUrl) {

var data = Utilities.parseCsv(results, '\t');
var clientName = AdWordsApp.currentAccount().getName().split();
var today = new Date();
today = today.getMonth() + today.getDate() + today.getFullYear();

var filename = clientName[0] + 'disapproved-ads' + today;

// Send an email with Search list attachment
var blob = Utilities.newBlob(results, 'text/html', '');

MailApp.sendEmail(email_address, clientName + ' Disapproved Ad Results ', 'You can find the list of disapproved ads at the following URL:' + fileUrl, {
name: ' Client Disapproved Ads'
});

}

function disapprovedAd(campaign, adgroup, headline, d1, d2, displayUrl, destinationURL, reason) {
this.campaign = campaign;
this.adgroup = adgroup;
this.headline = headline;
this.d1 = d1;
this.d2 = d2;
this.displayUrl = displayUrl;
this.destinationUrl = destinationURL;
this.reason = reason;

}

// HELPER FUNCTIONS

function warn(msg) {
Logger.log('WARNING: '+msg);
}

function info(msg) {
Logger.log(msg);
}

// TWILIO ACCESS
function Twilio(e,t){function n(e){return{Authorization:"Basic "+Utilities.base64Encode(e.ACCOUNT_SID+":"+e.AUTH_TOKEN)}}this.ACCOUNT_SID=e;this.AUTH_TOKEN=t;this.MESSAGES_ENDPOINT="https://api.twilio.com/2010-04-01/Accounts/"+this.ACCOUNT_SID+"/Messages.json";this.CALLS_ENDPOINT="https://api.twilio.com/2010-04-01/Accounts/"+this.ACCOUNT_SID+"/Calls.json";this.sendMessage=function(e,t,r){var i={method:"POST",payload:{To:e,From:t,Body:r},headers:n(this)};var s=UrlFetchApp.fetch(this.MESSAGES_ENDPOINT,i).getContentText();return JSON.parse(s)["sid"]};this.makeCall=function(e,t,r){var i="http://proj.rjsavage.com/savageautomation/twilio_script/dynamicSay.php?alert="+encodeURIComponent(r);var s={method:"POST",payload:{To:e,From:t,Url:i},headers:n(this)};var o=UrlFetchApp.fetch(this.CALLS_ENDPOINT,s).getContentText();return JSON.parse(o)["sid"]}}

 

 

5. Alarme de Zero Impressões – Por Catalyst Canada Contributor. Seja notificado quando seus anúncios não estejam gerando impressões. Assim, você terá uma reação rápida quando houver algum problema com suas campanhas.

function main() {

// Enter your account name and email here:

var accountName = “Account name”;

var yourEmail = “[email protected]”;

var emailBody=”Yesterday, the following campaigns have had no impressions:<br>”;

var noImpCamp=0;

var campaignsIterator = AdWordsApp.campaigns().get();

while (campaignsIterator.hasNext()) {

var campaign = campaignsIterator.next();

var stats = campaign.getStatsFor(‘YESTERDAY’);

if ((stats.getImpressions() == 0)&&(campaign.isEnabled())) {

emailBody = emailBody + campaign.getName() + “<br>”;

noImpCamp++;

}

}

if (noImpCamp > 0) {

MailApp.sendEmail(yourEmail,”Alert: ” + accountName + ” – ” + noImpCamp + ” Campaigns with no impressions”,””,{htmlBody: emailBody})

}

}

 

6. Receba Ligações e Mensagens de Alertas com Scripts – Por Russel Savage. O script do Google envia mensagem faz ligações por meio de uma ferramenta de terceiros. Ideal para pessoas que por algum motivo não tem acesso ao e-mail.

 

Para usar este script, há algumas coisas que você precisa fazer. Primeiro, inscreva-se para uma conta Twilio. Depois de fazer isso, você deve ter um número de telefone com o qual possa usar para brincar, além de um SID da conta e um token de autenticação . Twilio pode não estar disponível em seu país ainda, mas esperamos que eles estejam lá em breve. Verifique se você está usando os números de telefone completos (incluindo os códigos de conta) ao fazer suas solicitações. Se você está usando apenas a versão gratuita, pode haver limites de uso, mas não tenho certeza.

O código é configurado para que possa ser copiado em qualquer script em que você precise enviar notificações. Depois de copiar o objeto Twilio no script, sempre que quiser que a notificação seja enviada, você deverá adicionar o seguinte código:

...
var sid = 'YOUR ACCOUNT SID GOES HERE';
var auth = 'YOUR AUTH TOKEN GOES HERE';
//First, create a new Twilio client
var client = new Twilio(sid,auth);
//Here is how you send a text message
// First number is the receiver (most likely, your cell phone)
// Second number is where is it coming from, which is the free number you got when
// you registered in Twilio
// The third parameter is what you want the text or voice message to say
client.sendMessage('+17245551234','+14155554321','WARNING: Your AdWords Account Is Not Serving Ads.');
client.makeCall('+17245551234','+14155554321',
'This is an automated call to warn you that your AdWords account is no longer serving ads.');
...

 

Naturalmente, sid, auth e client podem ser variáveis ​​globais que permitem que você tenha uma única linha em seu código para fazer chamadas telefônicas ou enviar mensagens. Você também pode configurar algum tipo de cadeia de encaminhamento para o caso de as pessoas perderem a chamada ou o texto.

Este é apenas um exemplo simples de começar a usar o UrlFetchApp para integrar scripts do Google AdWords a aplicativos de terceiros.

/*********************************
* Twilio Client Library
* Based on the Twilio REST API: https://www.twilio.com/docs/api/rest
* Version 1.0
* Created By: Russ Savage
* FreeAdWordsScripts.com
*********************************/
function Twilio(accountSid, authToken) {
this.ACCOUNT_SID = accountSid;
this.AUTH_TOKEN = authToken;

this.MESSAGES_ENDPOINT = 'https://api.twilio.com/2010-04-01/Accounts/'+this.ACCOUNT_SID+'/Messages.json';
this.CALLS_ENDPOINT = 'https://api.twilio.com/2010-04-01/Accounts/'+this.ACCOUNT_SID+'/Calls.json';

this.sendMessage = function(to,from,body) {
var httpOptions = {
method : 'POST',
payload : {
To: to,
From: from,
Body: body
},
headers : getBasicAuth(this)
};
var resp = UrlFetchApp.fetch(this.MESSAGES_ENDPOINT, httpOptions).getContentText();
return JSON.parse(resp)['sid'];
}

this.makeCall = function(to,from,whatToSay) {
var url = 'http://proj.rjsavage.com/savageautomation/twilio_script/dynamicSay.php?alert='+encodeURIComponent(whatToSay);
var httpOptions = {
method : 'POST',
payload : {
To: to,
From: from,
Url: url
},
headers : getBasicAuth(this)
};
var resp = UrlFetchApp.fetch(this.CALLS_ENDPOINT, httpOptions).getContentText();
return JSON.parse(resp)['sid'];
}

function getBasicAuth(context) {
return {
'Authorization': 'Basic ' + Utilities.base64Encode(context.ACCOUNT_SID+':'+context.AUTH_TOKEN)
};
}
}

 

 

7. Alterações no CTR – Por Sean Dolan. Esse script permite identificar mudanças na taxa de cliques pela planilha do Google. Você pode utilizar esse scripts para monitorar o desempenho de seus anúncios.

function main() {

//UPDATE WITH YOUR EMAIL
var email = "[email protected]";

//UPDATE WITH YOUR SPREADSHEET ADDRESSES
var SPREADSHEET_URL_increase = "INCREASE_URL"
var SPREADSHEET_URL_decrease = "DECREASE_URL"

//SPECIFY "decrease" OR "increase"
var accountChanges = "decrease";

if(accountChanges== "decrease"){
var SPREADSHEET_URL = SPREADSHEET_URL_decrease;}
if(accountChanges== "increase"){
var SPREADSHEET_URL = SPREADSHEET_URL_increase;}
var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = spreadsheet.getSheets()[0];
var sheet2 = spreadsheet.getSheets()[1];
var sheet3 = spreadsheet.getSheets()[2];

spreadsheet.getRangeByName("account_id").setValue(AdWordsApp.currentAccount().getCustomerId());
sheet.getRange(1, 2, 1, 1).setValue("Date");
sheet.getRange(1, 3, 1, 1).setValue(new Date());
sheet.getRange(7, 1, sheet.getMaxRows() - 7, sheet.getMaxColumns()).clear();

var adGroupsIterator = AdWordsApp.adGroups()
.withCondition("Status = 'ENABLED'")
.withCondition("CampaignStatus = 'ENABLED'")
.forDateRange("TODAY")
.orderBy("Ctr ASC")
.withLimit(500)
.get();

var today = getDateInThePast(0);
var oneWeekAgo = getDateInThePast(7);
var twoWeeksAgo = getDateInThePast(14);
var threeWeeksAgo = getDateInThePast(21);

var reportRows = [];
var ctrRows = [];
var bounceRate = [];

while (adGroupsIterator.hasNext()) {
var adGroup = adGroupsIterator.next();
// Let's look at the trend of the ad group's CTR.
var statsThreeWeeksAgo = adGroup.getStatsFor(threeWeeksAgo, twoWeeksAgo);
var statsTwoWeeksAgo = adGroup.getStatsFor(twoWeeksAgo, oneWeekAgo);
var statsLastWeek = adGroup.getStatsFor(oneWeekAgo, today);

if(accountChanges == "increase"){
// Week over week, the ad group is increaseing - record that!
if (statsLastWeek.getCtr() > statsTwoWeeksAgo.getCtr() && statsTwoWeeksAgo.getCtr() > statsThreeWeeksAgo.getCtr()) {
reportRows.push([adGroup.getCampaign().getName(), adGroup.getName(),
statsLastWeek.getCtr() * 100, statsLastWeek.getCost(),
statsTwoWeeksAgo.getCtr() * 100, statsTwoWeeksAgo.getCost(),
statsThreeWeeksAgo.getCtr() * 100, statsThreeWeeksAgo.getCost()]);
}
//Conv Rate
if (statsLastWeek.getConversionRate() > statsTwoWeeksAgo.getConversionRate() && statsTwoWeeksAgo.getConversionRate() > statsThreeWeeksAgo.getConversionRate()) {
ctrRows.push([adGroup.getCampaign().getName(), adGroup.getName(),
statsLastWeek.getConversionRate() * 100, statsLastWeek.getConversions(),
statsTwoWeeksAgo.getConversionRate() * 100, statsTwoWeeksAgo.getConversions(),
statsThreeWeeksAgo.getConversionRate() * 100, statsThreeWeeksAgo.getConversions()]);
}

//Bounce Rate
if (statsLastWeek.getBounceRate() > statsTwoWeeksAgo.getBounceRate() && statsTwoWeeksAgo.getBounceRate() > statsThreeWeeksAgo.getBounceRate()) {
bounceRate.push([adGroup.getCampaign().getName(), adGroup.getName(),
statsLastWeek.getBounceRate() * 100, statsLastWeek.getCost(),
statsTwoWeeksAgo.getBounceRate() * 100, statsTwoWeeksAgo.getCost(),
statsThreeWeeksAgo.getBounceRate() * 100, statsThreeWeeksAgo.getCost()]);
}
}

if(accountChanges== "decrease"){
// Week over week, the ad group is degrading - record that!
if (statsLastWeek.getCtr() < statsTwoWeeksAgo.getCtr() && statsTwoWeeksAgo.getCtr() < statsThreeWeeksAgo.getCtr()) {
reportRows.push([adGroup.getCampaign().getName(), adGroup.getName(),
statsLastWeek.getCtr() * 100, statsLastWeek.getCost(),
statsTwoWeeksAgo.getCtr() * 100, statsTwoWeeksAgo.getCost(),
statsThreeWeeksAgo.getCtr() * 100, statsThreeWeeksAgo.getCost()]);
}
//Conv Rate
if (statsLastWeek.getConversionRate() < statsTwoWeeksAgo.getConversionRate() && statsTwoWeeksAgo.getConversionRate() < statsThreeWeeksAgo.getConversionRate()) {
ctrRows.push([adGroup.getCampaign().getName(), adGroup.getName(),
statsLastWeek.getConversionRate() * 100, statsLastWeek.getConversions(),
statsTwoWeeksAgo.getConversionRate() * 100, statsTwoWeeksAgo.getConversions(),
statsThreeWeeksAgo.getConversionRate() * 100, statsThreeWeeksAgo.getConversions()]);
}

//Bounce Rate
if (statsLastWeek.getBounceRate() < statsTwoWeeksAgo.getBounceRate() && statsTwoWeeksAgo.getBounceRate() < statsThreeWeeksAgo.getBounceRate()) {
bounceRate.push([adGroup.getCampaign().getName(), adGroup.getName(),
statsLastWeek.getBounceRate() * 100, statsLastWeek.getCost(),
statsTwoWeeksAgo.getBounceRate() * 100, statsTwoWeeksAgo.getCost(),
statsThreeWeeksAgo.getBounceRate() * 100, statsThreeWeeksAgo.getCost()]);
}
}
}

if (reportRows.length > 0) {
sheet.getRange(7, 2, reportRows.length, 8).setValues(reportRows);
sheet.getRange(7, 4, reportRows.length, 1).setNumberFormat("#0.00%");
sheet.getRange(7, 6, reportRows.length, 1).setNumberFormat("#0.00%");
sheet.getRange(7, 8, reportRows.length, 1).setNumberFormat("#0.00%");

sheet.getRange(7, 5, reportRows.length, 1).setNumberFormat("#,##0.00");
sheet.getRange(7, 7, reportRows.length, 1).setNumberFormat("#,##0.00");
sheet.getRange(7, 9, reportRows.length, 1).setNumberFormat("#,##0.00");
}

if (ctrRows.length > 0) {
sheet2.getRange(7, 2, ctrRows.length, 8).setValues(ctrRows);
sheet2.getRange(7, 4, ctrRows.length, 1).setNumberFormat("#0.00%");
sheet2.getRange(7, 6, ctrRows.length, 1).setNumberFormat("#0.00%");
sheet2.getRange(7, 8, ctrRows.length, 1).setNumberFormat("#0.00%");

sheet2.getRange(7, 5, ctrRows.length, 1).setNumberFormat("#,##0.00");
sheet2.getRange(7, 7, ctrRows.length, 1).setNumberFormat("#,##0.00");
sheet2.getRange(7, 9, ctrRows.length, 1).setNumberFormat("#,##0.00");
}

if (bounceRate.length > 0) {
sheet3.getRange(7, 2, bounceRate.length, 8).setValues(bounceRate);
sheet3.getRange(7, 4, bounceRate.length, 1).setNumberFormat("#0.00%");
sheet3.getRange(7, 6, bounceRate.length, 1).setNumberFormat("#0.00%");
sheet3.getRange(7, 8, bounceRate.length, 1).setNumberFormat("#0.00%");

sheet3.getRange(7, 5, bounceRate.length, 1).setNumberFormat("#,##0.00");
sheet3.getRange(7, 7, bounceRate.length, 1).setNumberFormat("#,##0.00");
sheet3.getRange(7, 9, bounceRate.length, 1).setNumberFormat("#,##0.00");
}

// var email = spreadsheet.getRangeByName("email").getValue();
if (email) {
var body = [];

if(reportRows.length>0){
var subjectline = [];
if(accountChanges=="increase"){
body.push("The CTR of the following ad groups is increasing over the last three weeks.\n");
subjectline.push(" ad groups are increasing in AdWords account ");
for (var i = 0; i < reportRows.length; i ++) {
body.push(reportRows[i][0] + " < " + reportRows[i][1]);
body.push(" " + ctr(reportRows[i][6]) + " < " + ctr(reportRows[i][4]) + " < " + ctr(reportRows[i][2]) + "\n");
}
}

if(accountChanges=="decrease"){
body.push("The CTR of the following ad groups is decreasing over the last three weeks.\n");
subjectline.push(" ad groups are degrading in AdWords account ");
for (var i = 0; i < reportRows.length; i ++) {
body.push(reportRows[i][0] + " > " + reportRows[i][1]);
body.push(" " + ctr(reportRows[i][6]) + " > " + ctr(reportRows[i][4]) + " > " + ctr(reportRows[i][2]) + "\n");
}
}

body.push("Full report at " + SPREADSHEET_URL + "\n\n");
MailApp.sendEmail(email, "" +
reportRows.length + subjectline +
AdWordsApp.currentAccount().getCustomerId(), body.join("\n"));
}
}

else{
if(accountChanges=="increase"){
body.push("No ad groups have consistently increasing CTR for the past three weeks.\n");
}
if(accountChanges=="decrease"){
body.push("No ad groups have consistently decreasing CTR for the past three weeks.\n");
}
}
}

function ctr(number) {
return parseInt(number * 10000) / 10000 + "%";

}

// Returns YYYYMMDD-formatted date.
function getDateInThePast(numDays) {
var today = new Date();
today.setDate(today.getDate() - numDays);
return Utilities.formatDate(today, "PST", "yyyyMMdd");
}

 

 

8. Campanhas com CPA Elevados – por Sean Dolan. Seja alertado quando suas campanhas alcançarem o limite de CPA. Assim, você pode trabalhar na conta para diminuir esse CPA.

function main(){

//Define three variables: cpalimit, emailaddress, and timerange (choices are: TODAY,
//YESTERDAY, LAST_7_DAYS, THIS_WEEK_SUN_TODAY, LAST_WEEK, LAST_14_DAYS, LAST_30_DAYS,
//LAST_BUSINESS_WEEK, LAST_WEEK_SUN_SAT, THIS_MONTH, LAST_MONTH, ALL_TIMR)
var cpalimit = 100;
var emailaddress = "[email protected]";
var timerange = "LAST_7_DAYS"

//Array definition and get data
var numcampaigns=0;
var campaignNames =[];
var campaignIterator = AdwordsApp.campaigns()
.forDateRange("TODAY")
.withCondition("Status = ACTIVE")
.get();
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
var name = campaign.getName();
var stats = campaign.getStatsFor(timerange);
var Conv = stats.getStatsFor(timerange);
var Cost = stats.getCost();
var cpa = (Cost /Conv);

 

 

9. Alerta de Teste de Anúncios – por Sean Dolan. O script compara 2 grupos de anúncios com no mínimo 1000 impressões para verificar diferenças nos CTR dos dois.

function main() {
/*
This script will evaluate two groups of ads against one another to look for significant differences in CTR.
One thing to keep in mind, the script will check for 1000 impressions to assure an adequate sample size.
If these condition are not met, the script will inform you that you need more impressions.
*/

//A list of the labels you want to test. Make sure you keep
//the brackets and add any additional labels by inserting a
//comma and the keyword in ' '.
//Example var labelTest = "['Ad Test 1', 'Ad Test 2']; etc.
//This allows you to reconfigure your groupings as needed.

var labelTest = "['Ad Test 1']";
var labelControl = "['Control']";

//Insert the day you test started in YYYYMMDD format. This
//will ensure you only test ads that are running at the same time.
var dateStarted = " ";

//Enter your e-mail below if you would like to schedule the
//script to run and update you when results are reached.
var eMail = "[email protected]";

//Enter the account name you would like to appear in the e-mail alerts.
var accountName = "Account";

var codeURL = "https://s3.amazonaws.com/ppc-hero-tools/stat-sig.js";
var code = "";
function getCode(url) {
var stuff = UrlFetchApp.fetch(url).getContentText();
return stuff;
}
var code = getCode(codeURL);

eval(code);
}

 

 

10. Alertas Diários – por Sean Dolan. Mantenha-se informado recebendo alertas diários sobre sua conta do Google Ads com esse script.

function main() {

//Enter the name of the account. This will help title the e-mail.
var accountName = "Account Name";
//insert your e-mail here
var eMail = "[email protected]";
//how much variance do you want to allow before sending an alert?
//This is a percentage and the default is 20%
var VARIANCE_DAY_TO_DAY = 0.2;

var codeURL = "https://s3.amazonaws.com/ppc-hero-tools/daily-alert.js";
var code = "";
function getCode(url) {
var stuff = UrlFetchApp.fetch(url).getContentText();
return stuff;
}
var code = getCode(codeURL);

eval(code);
}