なぜNginxなのか?
→LINEのBOTのWebhookは、SSLに対応している必要がある。そのため、Nginxのリバースプロキシを使いSSL化する。
とりあえずおうむ返しするBOTを作る。
必要なもの:
- VPS(サーバー)
- ドメイン
私は、Vultr VPSを使いました。
また、Google domainsにて、line.risaton.netにAレコードを設定。
- ライブラリのインストール
私はPipenv派なので、
pipenv --python 3
pipenv install flask
pipenv install python-dotenv
pipenv install line-bot-sdk
2. コードを書く
#main.py
import os
from dotenv import load_dotenv
from flask import Flask, request, abort
from linebot.v3 import (
WebhookHandler
)
from linebot.v3.exceptions import (
InvalidSignatureError
)
from linebot.v3.messaging import (
Configuration,
ApiClient,
MessagingApi,
ReplyMessageRequest,
TextMessage
)
from linebot.v3.webhooks import (
MessageEvent,
TextMessageContent
)
load_dotenv()
app = Flask(__name__)
configuration = Configuration(access_token=os.environ.get('TOKEN'))
handler = WebhookHandler(os.environ.get('SECRET'))
# print('TOKEN is: '+os.environ.get('TOKEN'))
# print('SECRET is :'+os.environ.get('SECRET'))
@app.route("/callback", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[TextMessage(text=event.message.text)]
)
)
# if __name__ == "__main__":
app.run(port=os.getenv('PORT', default=3000))
3. サーバーにNginxをインストールし、SSL化する
apt install nginx certbot python3-certbot-nginx
certbot certonly -d <ドメイン名> -m <メールアドレス> --nginx
vim /etc/nginx/sites-enabled/default
こんな感じにNginxを設定します。
4. tar cvf line-bot.tar <line botのpath>
5. scp line-bot.tar <サーバー>
6. サーバー上でtmuxなりで pipenv run python main.py
7. vim .env で、TOKENとSECRETを設定
8. LINE DevelopersでMessaging APIを適切に設定すれば動きます。
コメントを残す