HipChatに日々の売上レポートを通知させたいですよね。
今回はGoogleAppScriptとHipchatのAPIを利用して実現してみます。
HipChatのAdmin API tokenを取得する
GoogleAppsScriptでAdSenseの売上を集計する
function addFigure(str) {
var num = new String(str).replace(/,/g, "");
while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
return num;
}
/*
* @example
* generateReport('2014-01-01')
*/
function generateReport(date){
var startDate = date;
var endDate = date;
var args = {
'metric': ['AD_REQUESTS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK', 'AD_REQUESTS_RPM', 'EARNINGS', 'CLICKS'],
'dimension': ['DATE'],
'useTimezoneReporting': true
};
var rows = AdSense.Reports.generate(startDate, endDate, args).getRows();
var row = rows[0];
var message = [
row[0],
'収益: ¥' + addFigure(row[5]),
'広告リクエスト: ' + addFigure(row[1]),
'広告リクエストCTR: ' + parseFloat(row[2]) * 100 + '%',
'CPC: ¥' + addFigure(row[3]),
'広告リクエストRPM: ¥' + addFigure(row[4])
].join("<br>");
sayMessage(message);
}
集計結果をHipChatAPIで通知する
var authToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
function getRequestURL(){
var url = "http://api.hipchat.com/v1/rooms/message";
return url + '?auth_token=' + authToken;
}
function sayMessage(message) {
var options = {
"contentType" : "application/x-www-form-urlencoded",
"method": "post",
"payload": {
"room_id": XXXXXX, // Found in the hipchat.com MyAccount > Rooms > API ID
"from": 'AdSense',
"notify": 0,
"message": message ? message : "",
"color": 'green',
"message_format": 'html'
},
//"muteHttpExceptions": true
};
var responseString = UrlFetchApp.fetch(getRequestURL(), options).getContentText();
Logger.log(responseString);
}