Skip to content

Instantly share code, notes, and snippets.

@pavi2410
Created November 14, 2017 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavi2410/ce58d76ca3b71a6c31b89dc8917e0437 to your computer and use it in GitHub Desktop.
Save pavi2410/ce58d76ca3b71a6c31b89dc8917e0437 to your computer and use it in GitHub Desktop.
Generate AdSense report and send it to Slack automatically
function doGet() {
getAdReports();
}
function getAdReports() {
var start = "today-6d"; //one week ago
var end = "today";
var clients = AdSense.Adclients.list().getItems();
var args = {
'filter': ['AD_CLIENT_ID==' + clients[0].getId()],
'metric': ['PAGE_VIEWS', 'EARNINGS'],
'dimension': ['DATE']
};
var report = AdSense.Reports.generate(start, end, args).getRows();
var fields = [];
for (var i=0; i<report.length; i++) {
var row = report[i];
var getDate = row[0];
var getPageViews = row[1];
var getEarnings = row[2];
var field = {
"title": getDate,
"value": "Money Earned: €" + getEarnings + "\nPage Views: " + getPageViews
}
fields.push(field)
}
sendToSlack(fields);
}
function sendToSlack(fields) {
var url = "https://hooks.slack.com/services/..."; //Slack incoming webhook url
var payload = {
"text": "Daily Earnings Summary",
"fallback": "Failed!",
"attachments":
[
{
"fallback":"Failed to retrieve data!",
"color":"good",
"fields": fields
}
]
}
var options = {
"method": "post",
"contentType": "application/json",
"payload": JSON.stringify(payload)
};
return UrlFetchApp.fetch(url, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment