見出し画像

[GAS][Slack]定型的な投稿にBotを用いる(その2)

前回、「GASで『定型的な文章』をSlack Botに投稿」という記事を書きました。

別のパターンを構築してみます。

ひとつのメッセージを複数のチャンネルに投稿

以下のスプレッドシートを用意します。

メッセージをセルB1に入力し、3行目以降に設けたチャンネル一覧より
送信したいチャンネルにチェックを入れます。

※別シート「channelリスト」で「チャンネル名-チャンネルID」のDBを用意します。

スクリプトはこちら。

function slackBot_03() {

  const ss      = SpreadsheetApp.getActiveSpreadsheet();
  const sheet   = ss.getActiveSheet();
  const message = sheet.getRange(1, 2).getValue();
  const lastRow = sheet.getLastRow();

  const channelArray = ss.getSheetByName('channelリスト').getDataRange().getValues();

  for (let i = 3; i <= lastRow; i++) {
    const isSend = sheet.getRange(i, 1).getValue();
    if (isSend) {
      const channelName = sheet.getRange(i, 2).getValue();
      const channel     = findValue(channelArray, channelName);
      postMessage(channel, message);
    }
  }
}

function postMessage(channel, message) {

  const token = PropertiesService.getScriptProperties().getProperty('SlackBot_token');

  const options = {
    "method": "post",
    "contentType": "application/x-www-form-urlencoded",
    "payload": {
      "token": token,
      "channel": channel,
      "text": message
    }
  };

  const url = 'https://slack.com/api/chat.postMessage';
  UrlFetchApp.fetch(url, options);

}

function findValue(values, key) {

  for (const i in values) {
    if (values[i][0] === key) {
      return values[i][1];
    }
  }
  return;
}

チャンネル数が多い場合はプルダウンで

チャンネル数が多い場合はプルダウンで実装するのも良いかと思います。

スクリプトはこちら。(function postMessage以下は共通)

function slackBot_03_2() {

  const ss      = SpreadsheetApp.getActiveSpreadsheet();
  const sheet   = ss.getActiveSheet();
  const message = sheet.getRange(1, 2).getValue();
  const lastRow = sheet.getLastRow();

  const channelArray = ss.getSheetByName('channelリスト').getDataRange().getValues();

  for (let i = 3; i <= lastRow; i++) {
    const channelName = sheet.getRange(i, 2).getValue();
    const channel = findValue(channelArray, channelName);
    postMessage(channel, message);
  }
}


function postMessage(channel, message) {

  const token = PropertiesService.getScriptProperties().getProperty('SlackBot_token');

  const options = {
    "method": "post",
    "contentType": "application/x-www-form-urlencoded",
    "payload": {
      "token": token,
      "channel": channel,
      "text": message
    }
  };

  const url = 'https://slack.com/api/chat.postMessage';
  UrlFetchApp.fetch(url, options);

}

function findValue(values, key) {

  for (const i in values) {
    if (values[i][0] === key) {
      return values[i][1];
    }
  }
  return;
}


続きの記事を書きました。


この記事が気に入ったらサポートをしてみませんか?