0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptでSlack slash commandを作ってみる

0
Last updated at Posted at 2019-03-06

やること

TypeScriptを使ってSlackのslash commandを作ってみようと思います。botも便利ですがslash commandも使い慣れると便利ですよ!最近JavaScriptで色々作れるので他の言語触らなくなりつつある...良いのか悪いのか(´・ω・`)

作るもの

コマンド

/timecard [in/out] [id]

仕様

  • 社内の勤怠APIに対してパラメータを付与してAPIにGETリクエストをする。
  • パラメータは2つ。

Slash command作成

パッケージのインストール

適当にディレクトリを作ってnpm init -yを実行して、パッケージをインストール。

npm i express typescript ts-node body-parser @types/express @types/body-parser

package.jsonのscriptsに以下を追加しておく。

"start": "./node_modules/.bin/ts-node app.ts"

枠を作る

ルートディレクトリにapp.tsを作成して以下のコードを記述。動作確認用のAPI(仮)も用意しておきます。

import * as http from 'http';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import nodeFetch from 'node-fetch';

const app = express();

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

app.get('/api', (req, res) => {
    res.json({
        message: "Hello!"
    });
});

app.post('/', (req, res) => {
    console.log(req.body.text);
});

http.createServer(app).listen(8081);

Slack slash commandはPOSTで飛んでくるのでapp.postで受けます。

Slack App設定

Slackで作成したslash commandを使えるようにしていきます。

アプリの登録

作成したslash commandを使いたいワークスペースにログインした状態でslack apiにアクセス。右上のメニューにあるYour AppsをクリックしてCreate an Appボタンをクリック。
モーダルダイアログが表示されるので以下を入力(内容は適当に)。

App Name: アプリ名
Development Slack Workspace: 利用するワークスペースを選ぶ

入力したらCreate Appボタンをクリック。
作成が終わったらメニューのFeaturesからSlash Commandsを選択してCreate New Commandをクリックします。
画面全体にモーダルが表示されるので以下を入力(内容は適当に)。

Command: slash command名。ex. /scsample
Request URL: Slash commandがリクエストするURL。ex. https://example.com/sc
Short Description: Slash command概要。ex. xxxAPIを叩く
Usage Hint: パラメータのヒント。ex. [in/out] [id]

URLはテスト段階ならngrokとかで一時的に公開する形で良いかと思います。
入力が終わったらSaveをクリック。

Slackへのインストール

メニュー上のプルダウンが先程作成したApp名になっているかと思います。その状態でメニューのSettingsからInstall Appをクリック。Install App to Workspaceをクリックします。インストール確認画面になるので許可するボタンをクリックします。

動かしてみる

Slackを開いてインストールしたワークスペースで先程登録したslash commandを実行してみましょう。slash commandを実行してtestと表示されればOKです!terminal上でパラメータの確認ができますので、パラメータを送ってみてください。

作り込んでいく

import * as http from 'http';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import nodeFetch from 'node-fetch';

const app = express();

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

// API Stub
app.get('/api', (req, res) => {
    res.json({
        message: "Hello!"
    });
});

app.post('/', (req, res) => {
    console.log(req.body.text);
    nodeFetch('http://xxx.api/api')
        .then(aRes => {
            if (!aRes.ok) throw new Error(`Sorry. API HTTP Status code ${aRes.status}`);
            return aRes;
        })
        .then(aRes => aRes.json())
        .then(json => {
            res.send(json);
        })
        .catch(err => {
            // for error
            console.dir(err);
            res.send("Sorry. Server error.");
        });
});

http.createServer(app).listen(8081);

これをベースに作り込んでいけばOKかなと思います。

最後に

やってみたらそんなに難しいことじゃ無かったです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?