atiek
2/25/2017 - 9:07 AM

Hacker Newsを日本語訳してSlackに通知(Google Apps Script)

Hacker Newsを日本語訳してSlackに通知(Google Apps Script)

// 使用ライブラリ
// https://github.com/soundTricker/SlackApp
// https://github.com/roana0229/spreadsheets-sql

// SpreadSheet設定
var spreadSheetId = '';
var sheetName = '';
var sheetObj = SpreadSheetsSQL.open(spreadSheetId, sheetName);

// Slack設定
var slackToken = "";
var targetChannelName = '';
var botUserName = '';

// ハッカーニュースをSlackに送る
function postNewHackerNews() {
  var storyIds = getTopStoryIds();
  var stories = [];
  var postStr = "";
  
  var existStoryIds = getExistStoryIds(storyIds);
  
  for each(var id in storyIds){
    if(existStoryIds.indexOf(id) == -1) {
      var story = getStory(id);
      
      if(story.url !== undefined)
      {
        stories.push(deleteStoryElem(story));
        
        postStr += "<https://translate.google.co.jp/translate?u=" + story.url +  "|" + LanguageApp.translate(story.title, 'en', 'ja') + ">"
                 + "(<" + story.url + "|" + story.title +">)\n"
                 + "score:*" + story.score + "*    date:" + new Date(story.time * 1000).toLocaleString() + "\n\n";
        
        // translate連続実行制限を避けるため
        Utilities.sleep(100)
      }
    }
  }
  
  // 記事を保存
  addStory(stories);
  // Slackに送信
  postMessage(postStr);
}

// すでに取得済みの記事IDを取得
function getExistStoryIds(storyIds) {
  var idStr = storyIds.join(',');
  
  var rows = sheetObj.select(['id']).filter('id IN ' + idStr).result();
  return rows.map(function(row, index){
    return row.id;
  });
}

// 記事データの不要な要素を削除
function deleteStoryElem(story) {
  delete story['deleted'];
  delete story['type'];
  delete story['text'];
  delete story['dead'];
  delete story['parent'];
  delete story['kids'];
  delete story['parts'];
  delete story['descendants'];
  
  return story;
}

// 記事を取得
function getStory(id) {
  var url = "https://hacker-news.firebaseio.com/v0/item/" + id + ".json";
  var json = UrlFetchApp.fetch(url).getContentText();
  var jsonData = JSON.parse(json);
  
  return jsonData;
}

// 記事を保存
function addStory(stories) {
  sheetObj.insertRows(stories);
}

// 最新人気記事IDを取得
function getTopStoryIds() {
  var url = "https://hacker-news.firebaseio.com/v0/topstories.json";
  var json = UrlFetchApp.fetch(url).getContentText();
  var jsonData = JSON.parse(json);
  
  return jsonData;
}

// 1週間以上前の保存した記事を削除
function deleteStory() {
  var today = new Date();
  var beforeWeek = new Date();
  beforeWeek.setDate(today.getDate() - 7);
  var beforeWeekTime = Math.floor(beforeWeek.getTime() / 1000);
  
  sheetObj.deleteRows('time < ' + beforeWeekTime);
}

// Slackにメッセージを送る
function postMessage(mssage) {
  var slackApp = SlackApp.create(slackToken);

  var channels = slackApp.channelsList().channels;
  var targetChannel = channels.filter(function(row, index){
    return row.name === targetChannelName;
  })[0];
  
  slackApp.postMessage(targetChannel.id, mssage, {
    username : botUserName
  });
}