LINE DevelopersのMessaging APIを参考に動かしてみました。
「Python+Flask+Heroku」を使って、アプリケーション作成、ローカル環境でテスト、サーバへデプロイした備忘録です。環境
- macOS High Sierra
- Python3.7.1
- Flask
- Heroku
アプリケーションをつくる:Python+Flask
作業フォルダを作成します。
$ mkdir flask-app
フォルダに移動します。
$ cd flask-app
アプリ用のPython環境をpyenvを使って準備します。インストール済みのPythonバージョン、インストール可能なバージョンを確認し、Pythonをインストールします。インストール後、作業フォルダで有効化し、有効化されているか確認します。
$ pyenv versions
$ pyenv install --list
$ pyenv install 3.7.1
$ pyenv local 3.7.1
$ pyenv version
必要なパッケージをインストールします。
$ pip install Flask gunicorn line-bot-sdk
フォルダに3つのファイルを作成します。
Procfile | ProcfileはHerokuでアプリケーションをデプロイした際に最初に実行されるコマンドを記述するためのファイル |
---|---|
requirements.txt | Herokuのサーバーにアップロードした際に自動的にpipでHerokuのサーバーにインストールするライブラリを記述するためのファイル |
app.py | Flaskで作成されたアプリケーションのPythonファイル |
Procfileファイルに以下を記述します。
web: gunicorn app:app
以下のコマンドを使用して、Python環境にインストールされているライブラリをrequirements.txtに反映します。
$ pip freeze > requirements.txt
requirements.txtの中身は以下の通りです。
certifi==2018.11.29
chardet==3.0.4
Click==7.0
Flask==1.0.2
future==0.17.1
gunicorn==19.9.0
idna==2.8
itsdangerous==1.1.0
Jinja2==2.10
line-bot-sdk==1.8.0
MarkupSafe==1.1.0
requests==2.21.0
urllib3==1.24.1
Werkzeug==0.14.1
アプリケーションファイルを作成します。以下はオウム返しするサンプルです。
from __future__ import unicode_literals
import os
import sys
from argparse import ArgumentParser
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookParser
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(__name__)
# get channel_secret and channel_access_token from your environment variable
channel_secret = "YOUR_CHANNEL_SECRET"
channel_access_token = "YOUR_CHANNEL_ACCESS"
if channel_secret is None:
print('Specify LINE_CHANNEL_SECRET as environment variable.')
sys.exit(1)
if channel_access_token is None:
print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
sys.exit(1)
line_bot_api = LineBotApi(channel_access_token)
parser = WebhookParser(channel_secret)
@app.route("/callback", methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# parse webhook body
try:
events = parser.parse(body, signature)
except InvalidSignatureError:
abort(400)
# if event is MessageEvent and message is TextMessage, then echo text
for event in events:
if not isinstance(event, MessageEvent):
continue
if not isinstance(event.message, TextMessage):
continue
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text)
)
return 'OK'
if __name__ == "__main__":
arg_parser = ArgumentParser(
usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
)
arg_parser.add_argument('-p', '--port', type=int, default=8000, help='port')
arg_parser.add_argument('-d', '--debug', default=False, help='debug')
options = arg_parser.parse_args()
app.run(debug=options.debug, port=options.port)
ローカル環境でテストする:ngrok
app.pyファイルを起動します。
$ python app.py
別のターミナルから、app.pyと同じローカルのポート番号でngrokを起動します。
$ ngrok http 8000
LINE Developersのチャネル基本設定にアクセスし、Webhook URL欄に、ngrokのURLを設定して、QRコードを読みとり友達追加し、LINEの画面でテストします。チャネル基本設定でWebhookを利用するに設定します。
アプリケーションをデプロイする:Heroku
Herokuにログインします。
$ heroku login
作業フォルダでgitを初期化し、リポジトリに追加し、コミットします。
$ git init
$ git add .
$ git commit -m "first commit"
Herokuにアプリケーションを作成します。
$ heroku create
ローカルで作成したFlaskのアプリケーションのリポジトリをプッシュします。
$ git push heroku master
さいごに
「Python+Flask+Heroku」を使って、オウム返しLINE Botをサーバーへデプロイできました。これをベースに便利なLINE Botをつくっていきましょう!