13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AdSenseの日時売上レポートをHipChatにレポートする方法

Last updated at Posted at 2014-02-20

HipChatに日々の売上レポートを通知させたいですよね。
今回はGoogleAppScriptとHipchatのAPIを利用して実現してみます。

HipChatのAdmin API tokenを取得する

Admin API Key

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で通知する

Rooms APIの仕様

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);
}

出来上がり

スクリーンショット 2014-02-20 20.43.15.png

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?