Skip to content

Instantly share code, notes, and snippets.

@siliconvallaeys
Last active May 30, 2024 05:20
Show Gist options
  • Save siliconvallaeys/fc9a0211f3b9ae36d7413359e477a65a to your computer and use it in GitHub Desktop.
Save siliconvallaeys/fc9a0211f3b9ae36d7413359e477a65a to your computer and use it in GitHub Desktop.
Change a Google Ads tROAS for a campaign based on temperature
function main() {
var units = "metric"; // imperial or metric
var lat = "37.384998";
var lon = "-122.106689";
var openWeatherAPIKey = ""; // get your own key for the One Call API from https://openweathermap.org/api
var campaignName = 'Search: Executive Summary Report'; // put your campaign name here
var bidAdjustment = 1.5; // this is the scaling factor of the current tROAS
var tempThreshold = 11; // this is the temperature below which the tROAS should be changed
var minTemp = getLowestTemperature(units, lat, lon, openWeatherAPIKey);
Logger.log("The minimum temperature will be: " + minTemp);
if(minTemp < tempThreshold) {
Logger.log("Setting a new tROAS because the temperature will be too low");
setCampaignTRoas(campaignName, bidAdjustment);
} else {
Logger.log("The temperature won't be cold enough to change the tROAS.")
}
}
function getLowestTemperature(units, lat, lon, APIKey) {
const weatherUrl = "https://api.openweathermap.org/data/2.5/onecall?units=" + units + "&lat=" + lat + "&lon=" + lon +
"&exclude=current,minutely,hourly,alerts&appid=" + APIKey;
const response = UrlFetchApp.fetch(weatherUrl);
Logger.log("weatherUrl: " + weatherUrl);
if(response.getResponseCode() == 200) {
var json = JSON.parse(response.getContentText());
} else {
throw "An error occured while trying to parse: "+weatherUrl;
}
var min = json.daily[0].temp.min;
Logger.log("min: " + min);
return min;
}
function setCampaignTRoas(name, bidAdjustment) {
var campaignIterator = AdsApp.campaigns()
.withCondition("campaign.name LIKE '" + name + "'")
.get();
while(campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
const currentTRoas = campaign.bidding().getTargetRoas();
var newTRoas = bidAdjustment * currentTRoas;
campaign.bidding().setTargetRoas(newTRoas);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment