LoginSignup
3
4

More than 5 years have passed since last update.

はじめてのGAS - Slackにメッセージを送る

Posted at

概要

今回はGoogle Apps ScriptでSlackへユーザーメッセージを投稿してみます。
ボットユーザーでメッセージを投稿する方法はまた異なりますのでご注意ください。

Slackアプリの登録&設定

1. Slackアプリ一覧画面を開きます

Slack APIのページを開き、 右上の 「Your Apps」リンクを押します。

1.png

2. Slackアプリを作成します。

「Your Apps」の下にある「Create New App」ボタンを押します。

2.png

アプリ名、動作させるワークスペースの欄を入力して「Create App」
アプリ名は後から変更出来ますが、ワークスペースは変更ができないので注意が必要です。

3.png

3. アプリに権限を追加します。

アプリが無事作成されると、アプリの管理画面が開きます。
左のメニューから「OAuth & Permissions」を選択し、Scopesというブロックまで下にスクロールします。

4.png

セレクトボックスでchat:write:userを探して選択します。
キーボードで入力することで絞り込み(インクリメンタルサーチ)されます。
選択後は Save Changes ボタンを押すの忘れずに

5.png

4. アプリをワークスペースにインストールします。

一番上までスクロールして、「Install App to Workspace」ボタンをおします。
完了すると、OAuth Access Token が発行されます。

6.png

GASコード

GASプロジェクトを作成しコーディングしていきましょう。

function testPost() {
  const app_auth_token = PropertiesService.getScriptProperties().getProperty('slack_app_auth_token');
  const channel = PropertiesService.getScriptProperties().getProperty('channel');

  const result = postMessageToSlackChannel(
    app_auth_token, 
    channel, 
    "It is sample message!!"
  );
  Logger.log(result);
}

/**
 * messageをSlackチャンネルにポストする関数
 */
function postMessageToSlackChannel(app_auth_token, channel, message){
  const payload = {
    "token" : app_auth_token,
    "channel" : channel,
    "text" : message
  };
  const options = {
    "method" : "post",
    'contentType': 'application/x-www-form-urlencoded',
    "payload" : payload
  };

  return UrlFetchApp.fetch("https://slack.com/api/chat.postMessage", options);
}

実行

testPost関数を実行すると、外部サービスに接続するための権限確認のダイアログが表示されます。

7.png

8.png

参考リンク

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4