Google SpreadSheet + Google Analytics + Slackbot

2020. 8. 25. 08:46·코드와 오류 기록

Small start-ups are difficult to set up daily to check the status data of their products. So it becomes dependent on Google Analytics and Firebase, and there is no big change in the data it sees every day. I wanted to receive only the data that I must see on the Slack channel every day. It looks like bellow.

 

Daily GA Slack bot @DeepNatural In

I had to implement this function myself because the engineer was blank in the squad where I was on the production floor and it was difficult to get help from other product teams. I decided to challenge ourselves because we thought it would be possible to use the script function of a spreadsheet that we have been using frequently.

Install the Google Analytics report through Add-ons on the spreadsheet.

It is easier to install by referring to the link below.

https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on

 

Google Analytics Spreadsheet Add-on

Philip Walton, Google Analytics Developer Programs Engineer – March 2014 The Google Analytics Spreadsheet add-on makes it easier for Google Analytics users to access, visualize, share, and manipulate their data in Google Spreadsheets. Introduction The Go

developers.google.com

 

Create a new project and run report. This produces several sheets, and I created one more additional sheet for connection with the slacks.

And I wrote a Google App script referring to previous work I did to link with Slack and load data. I had experience connecting vacation records to spread sheets or making slack bots that issue documents into spread sheets, so I could make it easy.

 

2020/04/17 - [프로덕트 매니지먼트] - 구글 스프레드 시트로 주기별 SQL 데이터 자동으로 수집하기

 

구글 스프레드 시트로 주기별 SQL 데이터 자동으로 수집하기

프로덕트 오너가 팀에 합류한 뒤에 가장 먼저 확인할 것은 제품의 건강함을 확인할 수 있는 기본적인 데이터 지표들의 축적 여부와 언제든지 지난 로그 데이터도 볼 수 있느냐이다. 물론 여기서

puture.tistory.com

The following code is implemented, starting with declaring a sheet that is basically used. This is the part of the function that pulls data from other sheets to the sheet that you want to aggregate. The reason why this is necessary is to manage the history.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("report");
var lastRow = sheet.getLastRow();
var i = lastRow + 1;
var eventBefore = "Event 2days ago Report"
var eventAfter = "Event Yesterday Report"
var sessionBefore = "Session 2days ago Report"
var sessionAfter = "Session Yesterday Report"
var userBefore = "User 2days ago Report"
var userAfter = "User Yesterday Report"
var range = "A12"
var logSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(eventBefore);
date = sheet.getRange(i, 1); // A
user = sheet.getRange(i, 2); // B
session = sheet.getRange(i, 3); // C
event = sheet.getRange(i, 4); // D

The important part of the code below is the postResponse part, which is connected to the slack encoding webhook.

function getReport() {
  setDate();
  getUser();
  getSession();
  getEvent();
  postResponse(Utilities.formatDate(new Date(), "GMT+1", "''dd"), user.getValue(), session.getValue(), event.getValue());
}

function setDate() {
  date.setValue(Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy"));
}

function getEvent() {
  beforeValue = getValue(eventBefore);
  afterValue = getValue(eventAfter);
  
  comparedValue = afterValue - beforeValue;
  
  rate = (comparedValue * 100)/beforeValue;
  
  var value = '';
  
  if (isNaN(rate)) {
    value = comparedValue + '(0%)';
  } else {
    value = comparedValue + '(' + rate + '%' + ')';
  }

  event.setValue(value);
}

function getSession() {
  beforeValue = getValue(sessionBefore);
  afterValue = getValue(sessionAfter);
  
  comparedValue = afterValue - beforeValue;
  
  rate = (comparedValue * 100)/beforeValue;
  
  var value = '';
  
  if (isNaN(rate)) {
    value = comparedValue + '(0%)';
  } else {
    value = comparedValue + '(' + rate + '%' + ')';
  }

  session.setValue(value);
}


function getUser() {
  beforeValue = getValue(userBefore);
  afterValue = getValue(userAfter);
  
  comparedValue = afterValue - beforeValue;
  
  rate = (comparedValue * 100)/beforeValue;
  
  var value = '';
  
  if (isNaN(rate)) {
    value = comparedValue + '(0%)';
  } else {
    value = comparedValue + '(' + rate + '%' + ')';
  }

  user.setValue(value);
}

function getValue(sheetName) {
  var logSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  return logSheet.getRange(range).getValue();
}
function postResponse(date, user, session, event) {

  var payload = {
    "channel": "#" + '[Channel Name]',
    "username": "[Bot Name]",
    "icon_emoji": ":mag:",
    "link_names": 1,
    "attachments":[
       {
          "fallback": "[Notification Message Preview]",
          "pretext": date + "일" + " 성장보고:rocket:",
          "mrkdwn_in": ["pretext"],
          "color": "#49A8E4",
          "fields":[
             {
                "title":"전일 대비 방문자 수",
                "value": user,
                "short":false
             },
             {
                "title":"전일 대비 세션 수",
                "value": session,
                "short":false
             },
             {
                "title":"전일 대비 문의 수",
                "value": event,
                "short":false
             }
          ]
       }
    ]
  };

Logger.log(payload);
  var url = '[Your Slack Bot URL]';
  var options = {
    'method': 'post',
    'payload': JSON.stringify(payload)
  };

  return UrlFetchApp.fetch(url,options);
}

If implemented in this way, a bot that connects Google Analytics, spreadsheet, and slack will be finally completed.

 

This is a machine-translated article.

 

저작자표시 비영리 변경금지 (새창열림)

'코드와 오류 기록' 카테고리의 다른 글

Athena Timezone 세팅 방법  (0) 2021.02.02
R ggmap 400 에러 날 때 '&key=xxx'  (0) 2021.01.21
namespace ‘rlang’ 0.x.x is already loaded 에러  (0) 2020.05.19
env: node: No such file or directory  (0) 2020.05.14
구글 스프레드 시트로 주기별 SQL 데이터 자동으로 수집하기  (0) 2020.04.17
'코드와 오류 기록' 카테고리의 다른 글
  • Athena Timezone 세팅 방법
  • R ggmap 400 에러 날 때 '&key=xxx'
  • namespace ‘rlang’ 0.x.x is already loaded 에러
  • env: node: No such file or directory
신사(SinSa)
신사(SinSa)
#취미 사진가 #IT 직장인 경험하고 배운 것들을 글로, 사진으로 기록하고 있어요
  • 신사(SinSa)
    신사(SinSa)
    신사(SinSa)
  • 전체
    오늘
    어제
    • View all (424)
      • 잡념과 생각 (103)
      • 코드와 오류 기록 (80)
      • 사진 이야기 (10)
      • 교육과 육아 (12)
      • Brand (2)
      • 자료 모음 (46)
      • 축구 이야기(deprecated) (171)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    경남FC
    아스날
    프로축구
    대치키즈
    프로덕트오너
    Product Manager
    승강제
    대한축구협회
    박주영
    fc서울
    국가대표팀 감독
    김주영
    축구협회
    Po
    아이폰 게임
    한국 축구
    애자일
    국가대표팀
    쿠웨이트전
    프로덕트 오너
    홍명보호
    맨유
    축구
    Product Owner
    PM
    프로덕트 매니저
    한국축구
    스타트업
    k리그
    아이폰 축구게임
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
신사(SinSa)
Google SpreadSheet + Google Analytics + Slackbot
상단으로

티스토리툴바