![見出し画像](https://assets.st-note.com/production/uploads/images/79595242/rectangle_large_type_2_d7c09a0b20f7204e0cd04b0ec578848d.jpeg?width=800)
[GAS][Slack]定型的な投稿にBotを用いる(その2)
前回、「GASで『定型的な文章』をSlack Botに投稿」という記事を書きました。
別のパターンを構築してみます。
ひとつのメッセージを複数のチャンネルに投稿
以下のスプレッドシートを用意します。
![](https://assets.st-note.com/img/1653313479830-eCH6XE4Wpv.png?width=800)
メッセージをセルB1に入力し、3行目以降に設けたチャンネル一覧より
送信したいチャンネルにチェックを入れます。
※別シート「channelリスト」で「チャンネル名-チャンネルID」のDBを用意します。
![](https://assets.st-note.com/img/1653314303790-yEpl54X0bf.png?width=800)
スクリプトはこちら。
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;
}
チャンネル数が多い場合はプルダウンで
チャンネル数が多い場合はプルダウンで実装するのも良いかと思います。
![](https://assets.st-note.com/img/1653723512794-A6IeUqTRLi.png)
スクリプトはこちら。(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;
}
※
続きの記事を書きました。
この記事が気に入ったらサポートをしてみませんか?