본문 바로가기
Research/Google products

Appscript_구글시트로 스크래핑한 데이터를 Slack 채널에 전송

by RIEM 2023. 4. 19.

목표

스크래핑 한 구글시트 데이터를 슬랙 메시지로 보낼 것이다. 스크래핑은 구글시트 자체적으로 지원하는 IMPORTXML 함수를 사용해서 데이터를 가져왔다. Slack 메시지는 Slack의 webhook을 사용한다.

Appscript의 스케쥴러 기능을 활용하면 특정시간마다 스크래핑한 데이터를 전송하는 기능을 매우 간단하게 만들 수 있을 것으로 보인다.

구현

 

IMPORTXML의 두번째 인자는 Xpath 문법이다. 스크래핑 시 데이터를 가져오는 방식은 다양한데, 그중 하나가 Xpath다.

function sendSlackMessage() {
  
  // Google sheet
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  
  // Collect the data
  const sourceSheet = ss.getSheetByName('headlines');
  const sourceRange = sourceSheet.getRange('A2:A30');
  const sourceVals = sourceRange.getValues(); // 2차 배열로 헤드라인 값들 반환

  let msg = "*Reuters*\n";
  // A2~A30 중 빈 셀은 제외하고 내용 추가
  sourceVals.forEach(el => {
    if(el[0].length > 1) {
      msg += `- ${el}\n`
    }
  })

  const url = <SLACK webhook URL>; 
  const params = {
    method: "post", 
    contentType: "application/json", 
    muteHttpExceptions: true, 
    payload: JSON.stringify({
      "text": msg 
    }) 
  };

  const sendMsg = UrlFetchApp.fetch(url, params)
  var respCode = sendMsg.getResponseCode()
  Logger.log(sendMsg)
  Logger.log(respCode)
}

결과

댓글