Skip to content

Instantly share code, notes, and snippets.

@ikemonn
Created December 14, 2013 22:20
Show Gist options
  • Save ikemonn/7965693 to your computer and use it in GitHub Desktop.
Save ikemonn/7965693 to your computer and use it in GitHub Desktop.
GASを使ってGoogle AnalyticsとChatWorkを連携させる
function postCW() {
try {
var startDate = getLastNdays(7);
var endDate = getLastNdays(0);
var header = "【" + startDate + "〜" + endDate + "のPVが多いページランキング】" + "\n\n";
var data = "";
var firstProfile = getFirstProfile();
var results = getReportDataForProfile(firstProfile, startDate, endDate);
//ChatWork出力用にデータを整形
for(var i in results.getRows()) {
data += results.getRows()[i][0] + "\n"
+ "閲覧数: " + results.getRows()[i][1] + "PV\n"
+ "滞在時間: " + Math.round(results.getRows()[i][2]) + "秒\n"
+ "直帰率: " + Math.round(results.getRows()[i][3]) + "%\n"
+ "----------------------" + "\n";
}
sendChatWork(header + data);
} catch(error) {
Browser.msgBox(error.message);
}
}
function getLastNdays(nDaysAgo) {
var today = new Date();
var before = new Date();
before.setDate(today.getDate() - nDaysAgo);
return Utilities.formatDate(before, 'GMT', 'yyyy-MM-dd');
}
function getFirstProfile() {
var accounts = Analytics.Management.Accounts.list();
if (accounts.getItems()) {
var firstAccountId = accounts.getItems()[1].getId();
var webProperties = Analytics.Management.Webproperties.list(firstAccountId);
if (webProperties.getItems()) {
var firstWebPropertyId = webProperties.getItems()[0].getId();
var profiles = Analytics.Management.Profiles.list(firstAccountId, firstWebPropertyId);
if (profiles.getItems()) {
var firstProfile = profiles.getItems()[0];
return firstProfile;
} else {
throw new Error('No views (profiles) found.');
}
} else {
throw new Error('No webproperties found.');
}
} else {
throw new Error('No accounts found.');
}
}
function getReportDataForProfile(firstProfile, startDate, endDate) {
var profileId = firstProfile.getId();
var tableId = 'ga:' + profileId;
var resultCount = 10;
var optArgs = {
'dimensions': 'ga:pageTitle', //ページタイトルごとに結果を取得
'sort': '-ga:pageviews', //PV数でソート
'max-results': resultCount //出力データの件数
};
var results = Analytics.Data.Ga.get(
tableId,
startDate,
endDate,
'ga:pageviews,ga:avgTimeOnPage,ga:visitBounceRate', //PV,滞在時間、直帰率を取得
optArgs);
if (!results.getRows()) {
throw new Error('No views (profiles) found');
}
return results;
}
function sendChatWork(msg){
var cw = ChatWorkClient.factory({token: 'ChatWork APIのトークン'});
cw.sendMessage({room_id: 'ルームID', body: msg});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment