LoginSignup
6
2

More than 5 years have passed since last update.

なる早でslackのスラッシュコマンドを作ってみる

Last updated at Posted at 2019-02-28

はじめに

Serverless Framework使えば割と簡単にスラッシュコマンド作れるのでは?と思いどれくらいで作成できるのか試してみました。
あんまりいいアイディアが出てこなかったので三角関数の値を返すスラッシュコマンドを作ろうと思います。

/tri-func sin 30
0.5
/tri-func cos 60
0.5
/tri-func tan 45
1.0

こんな感じで(sinhとかconhがないのは勘弁)

APIを作る

プロジェクトを作成

$ mkdir <project> && cd <project>
$ sls create -t aws-python3 -n tri-func  
$ tree
.
├── handler.py
└── serverless.yml

pipenvの導入

標準のmathライブラリを使用してもいいのですが最近serverless-python-requirementsdockerizePipという依存関係があるライブラリをAmazonLinuxのDockerImageからビルドしてくれるものがあると知ったので、今回はnumpyを使用して三角関数の値を返します。
今回はpipenvserverless-python-requirementsを使用してライブラリを使用します。

pipenvで仮想環境を作りnumpyをインストールする

$ pipenv install --python 3.6.5
$ pipenv install numpy

serverless-python-requirementsのインストール

$ sls plugin install -n serverless-python-requirements

serverless.ymlを編集

profileを指定しない場合はdefaultが使用されます

serverless.yml
service: tri-func

provider:
  name: aws
  runtime: python3.6
  stage: stg
  region: ap-northeast-1
  profile: <hogehoge> #profileが複数あるので指定する

functions:
  get:
    handler: handler.get_tri
    events: #APIGatewayの設定
      - http: GET /

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    usePipenv: true # pipenvを使用する
    dockerizePip: non-linux # amazonlinuxでビルドする

handler.pyを編集

handler.py

import json
import numpy as np


def get_tri(event, context):
    # event['multiValueQueryStringParameters']['text']にコマンドの引数が入ってくる
    text = event['multiValueQueryStringParameters']['text'][0]
    text = text.split()

    try:
        tri = text[0]
        theta = int(text[1])
        if tri == 'sin':
            result = np.sin(np.pi*theta/180)
        elif tri == 'cos':
            result = np.cos(np.pi*theta/180)
        elif tri == 'tan':
            result = np.tan(np.pi*theta/180)
        else :
            result = 'エラー'
    except Exception as e:
        result = 'エラー'

    body = {
        'text': '結果: {}'.format(result),
    }

    response = {
        'statusCode': 200,
        'isBase64Encoded': False,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(body)
    }


    return response

デプロイ

$ sls deploy -v

Serverless: Stack update finished...
Service Information
service: tri-func
stage: stg
region: ap-northeast-1
stack: tri-func-stg
resources: 9
api keys:
  None
endpoints: # URLをメモっておく
  GET - https://xxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/stg
functions:
  get: tri-func-stg-get
layers:
  None

デプロイを行うとエンドポイントが表示されるのでメモしておく

Slackでスラッシュコマンドを登録する

Slack > 管理 > カスタムインテグレーション > Slash > 設定を追加 からCommands からスラッシュコマンドを作成する

デプロイした際に表示されたエンドポイントをURLにペーストする
スクリーンショット 2019-02-28 17.00.33.png
そして作成!

スラッシュコマンドを使ってみる

とりあえずsin30, cos60, tan45でテスト
スクリーンショット 2019-02-28 17.02.35.png
スクリーンショット 2019-02-28 17.04.36.png
スクリーンショット 2019-02-28 17.05.15.png

成功ですね(桁は許して)

結局どれくらいかかった?

Serverless Frameworkの環境が整っていればおそらく10分程度でスラッシュコマンドが作れるのではないでしょうか。
ちなみにこの記事を書きながら作成していたので私は約1時間くらいでした。

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