[GAS][Slack]定型的な投稿にBotを用いる
「定例会議の案内」や「書類提出リマインド」など、『定型的な文章』をSlackに投稿する場合、Google Apps Scriptを用いてBotから投稿したほうが便利なことがあります。
※Botの作成手順は以下過去記事をご参照ください。
※Botから投稿したメッセージが削除できない場合は以下過去記事をご参照ください。
以下の手順で実装/確認します。
1_スプレッドシートの用意
以下のスプレッドシートを用意します。
1行目にチャンネル名、2行目に投稿メッセージを入力します。
2_GASのスクリプト
スクリプトはこちら。
function slackBot_02() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const channel = sheet.getRange(1, 2).getValue();
const message = sheet.getRange(2, 2).getValue();
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);
}
2つのfunctionではそれぞれ以下の処理を実行します
【function slackBot_02】
・セルB1をchannel、セルB2をmessageとしてそれぞれ値を取得
・channelとmessageを引数として渡しfunction postMessageを実行
【function postMessage】
・トークンをプロパティストアより取得
・function slackBot_02から受け取った引数を元にSlackに投稿
3_GAS実行
GASを実行すると指定したチャンネルにメッセージが投稿されます。
4_メンション
メッセージにメンションを含めたい場合は
以下の通り表記します。
以下のメッセージを作成しGASを実行すると、
以下のようにメンションがつき投稿が出来ます。
5_投稿先チャンネルの切替
投稿先チャンネルを都度切り替えたい場合は別シートで「channelリスト」を作成し、「データの入力規則」を用いてプルダウンにすると便利です
6_チャンネル名ではなくチャンネルIDを用いる
上記のスクリプトでは、Slackのチャンネル名を変更されると投稿が出来なくなってしまうため、現実的な運用としては「チャンネル名-チャンネルID」を別シートにDBとして保持したほうが好ましいでしょう。
スクリプトはこちら。
function slackBot_02_2() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
const channelName = sheet.getRange(1, 2).getValue();
const message = sheet.getRange(2, 2).getValue();
const channelArray = ss.getSheetByName('channelリスト').getDataRange().getValues();
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 findValue】にて、チャンネル名を受け取るとチャンネルIDを返す仕組みを実装しました。
※続きの記事を書きました。
この記事が気に入ったらサポートをしてみませんか?