Log.d(myLife);

プログラミングを中心に趣味など。

7月2週

今週やったこと

基本的に写経を中心に新しい技術を学んでいきます。

参考資料

~ ToDo 活用 ~ GAS をつかって Slack から削除されたメッセージを Google スプレッドシートにアーカイブする

~ ToDo 活用 ~ Slack メッセージに絵文字リアクションをつけると Google スプレッドシートにアーカイブする

成果物

f:id:vam-py-re:20190714115944p:plain

内容

基本的には上記参考資料のコードを写経した上で、自分なりのアレンジを加えた形になっています。

まず、メインとなるコード。

function doPost(e) {
    const json = JSON.parse(e.postData.getDataAsString());
    const event = json.event;
  
  if(!event.reaction) return;
  if(event.reaction !== 'added') return;
  
  const token = PropertiesService.getScriptProperties().getProperty('Slackトークン');
  const channel = PropertiesService.getScriptProperties().getProperty('Channel_url');
  
  const apiUrl = 'https://slack.com/api/channels.history';
  const msgTs = event.item.ts;
  const msgTsDate = new Date(msgTs * 1000);
  const reactTs = event.event_ts;
  const reactTsDate = new Date(reactTs * 1000);
  
  const payload = {
    token : token,
    channel : channel,
    oldest : msgTs,
    latest : msgTs,
    inclusive : true
  };
  
  const options = {
    method : 'POST',
    contentType : 'application/x-www-form-urlencoded',
    payload : payload
  };
  
  const resp = UrlFetchApp.fetch(apiUrl, options);
  const contentText= JSON.parse(resp.getContentText());
  const msg = contentText.messages[0].text;
  const fetchedMsg = fetchData(msg, '<', '>');
  
  if(!judgeUrl(fetchedMsg)) return;
  
  const title = urlToTitle(fetchedMsg);
  
  const ss = SpreadsheetApp.openById('id');
  const sh = ss.getSheetByName('name');
  const result = checkColumn(sh, 'A:A');
  
  const input = [title, fetchedMsg, reactTsDate, msgTsDate];
  if(result.toString().match(input[0])) {
    return;
  }
  
  sh.appendRow(input);
  deleteMessage(token, channel, msgTs)
}

次にMainの中で使用している関数たち。

Slackで投稿したメッセージ(基本的に技術系記事のUrl)を取得してくると、文字列として取得したUrlは<~http~>という形になります。

下の関数は<>を取り除くための関数です。

function fetchData(str, pre, suf) {
    const reg = new RegExp(pre + '.*?' + suf);
    try {
        var data = str.match(reg)[0].replace(pre, "").replace(suf, "");
        return data;
    } catch(e) {
        data = 'error';
        return data;
    }
}

次にスプレッドシートに登録するテキストはURLだけにしたいので、文字列がURLか否かを判断する関数を定義しました。

URLはhttpから始まるだろという前提で書いてしまったのでコードとしては良くないかもしれません。

function judgeUrl(str) {
    if(str.match(/http/)) {
        return true;
    } else {
        return false;
    }
}

次に重複するメッセージの登録を避けるための関数を定義します。

  • テキストが入っているセルの情報を取得
  • Main関数内でif文を用いてチェック
function checkColumn(sh, column) {
    var result = new Array();
    var values = sh.getRange(column).getValues();
    for each(var value in values) {
        if(value != null && value != "") {
            result.push(value);
        }
    }
    return result;
}

最後にSlackのメッセージを削除する関数

function deleteMessage(token, channel, msgTs) {
    const chatDeleteUrl = 'https://slack.com/api/chat.delete';
    const payload = {
        token : token,
        channel : channel,
        ts : msgTs
    };
    
    const options = {
        method : 'post',
        contentType : 'application/x-www-form-urlencoded',
        payload : payload
    };
    
    UrlFetchApp.fetch(chatDeleteUrl, options);
}