Created
November 14, 2017 00:14
-
-
Save pavi2410/ce58d76ca3b71a6c31b89dc8917e0437 to your computer and use it in GitHub Desktop.
Generate AdSense report and send it to Slack automatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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