5
2

More than 3 years have passed since last update.

Node.jsでSlack Slashコマンドアプリを作る

Last updated at Posted at 2020-06-20

Slackのslashコマンドから動かせるシンプルなメモアプリケーションを作ってみます。
超初心者向けです。

完成イメージ

slackから /note hogeと打つと、hogeを記録してくれる。

設計

  • ローカルサーバでnodeアプリケーション(express)を起動する。
  • ngrokでローカルサーバを外部に公開
  • slack slashコマンドを作成し、送信先に公開用URLを指定

以上です。お試し版なので、本番環境へのデプロイやDB接続など面倒くさいことはしません。

expressアプリを作成

Udemyで速習しました。(https://www.udemy.com/course/nodejs-part2-express/)
express環境の構築は割愛します。
index.jsに下記を記載。

index.js

const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
const bodyParser = require("body-parser");
const Joi = require("joi");

app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));

const notes = [];


app.get("/", (req, res) => {
    res.send("Hello, World!");
});

app.get("/notes", (req, res) =>{
    res.send(notes);
})

app.post("/notes", (req, res) => {
    console.log(req)
    console.log(req.query)
    let course = {
        id: notes.length + 1,
        name: req.body.text
    };
    notes.push(course);
    res.send(notes);
});

app.listen(port, () =>{
    console.log(`ポート番号${port}で立ち上がりました。`)
});![ezgif.com-video-to-gif.gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/501910/d4b332de-e9f9-13ba-ba10-55c9577a4e0b.gif)
![ezgif.com-video-to-gif.gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/501910/7ce635f7-583e-012c-e7eb-72cf7d3852d4.gif)

機能は以下の通りです。

  • 3000番ポートで、/notes パスでのPOSTリクエストを受け取る
  • リクエストbody内のtextキーの値をnotesに格納し、notesをレスポンスとして返す

nodemonコマンドで起動させます。

nodemon

ngrokで公開

ngrokとはローカルホストサーバーをパブリックネットワークに公開できるサービス。
https://ngrok.com/ からインストールします。

インストールできたら、下記コマンドで3000番ポートを外部公開します。

ngrok http 3000

Forwarding欄に外部公開用のURLが発行されます。
スクリーンショット 2020-06-16 22.39.59.png

注意

  • 発行されるURLには有効期限があります。
  • インターネット上どこからでもアクセスできてしまうため、一時的な利用に留めましょう

Slack Slashコマンドを作成

公式サイト通りに設定をします。
https://api.slack.com/interactivity/slash-commands#getting_started

slack appの作成

https://api.slack.com/apps?new_app=1
AppNameとSlack workspaceを入力し、Create App

slashコマンドの作成

noteコマンドを作成。
Request URLに[ngrokのURL]/notesを入力。
スクリーンショット 2020-06-16 22.53.00.png

Slackから操作してみる

アプリケーションを設定したslackのワークスペースから下記コマンドを入力すると、JSON形式でノートが帰ってきます。

/note hoge
/note fuga

ezgif.com-video-to-gif.gif

コマンドの内容はPOSTリクエストとして設定したURLに送信され、引数の文字列はbodyの中に、textとして含まれています。

以上で、アプリ作成が完了しました!

参考

ソースコードはこちらで公開(https://github.com/xinkent/slack_note)

5
2
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
5
2