Heroku

1.申請帳號

line@manager --> massaging api設定 --> 自動回應不取消 不會影響後續api回覆設定

參考連結:

[1] http://www.evanlin.com/create-your-line-bot-golang/

2.在Heroku建立app(Flask)

2-1. 先登入Heroku然後在New選擇Create new app

2-2. 建立完成後在Deployment method選擇Heroku Git,所以需要安裝Git相關設定(參考連結[1])

Heroku頁面中的語法(建議再裝個小烏龜TortiseGit比較好操作,沒裝就乖乖用cmd):

(1) 先在cmd中切換到新的專案資料夾,再用git init初始化一個Repository

(2) 與heroku app連接(heroku git:remote -a appName)

(3) 把app所需要的檔案放到資料夾中,主要有四個: requirements.txt --> 需要安裝在python環境中的套件(記得加gunicorn),每次push時會檢查有無心套件需要安裝 runtime.txt --> 指定python版本(用最新的比較保險 吧) Procfile --> 指定需要運行的py檔 app.py --> 就是設定restful api(flask)的py檔,檔名必須要跟Procfile內容一樣

(4) 把這些檔案加到git的repository中(git add .),commit後再push到heroku上,每次修改app.y都需要commit+push

可在Heroku網頁中看log,方便找api的bug不然根本黑盒子
https://dashboard.heroku.com/apps/你的app名稱/logs

2-3. 把Line developers頁面中的Channel secret、Channel access token加到app.py中

# coding='utf-8'
# 回音機器人app.py
from flask import Flask,jsonify
from flask import request
from flask import abort
from datetime import datetime

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import *
import requests
import json

app = Flask(__name__)

line_bot_api = LineBotApi('Access token')
handler = WebhookHandler('Channel secret')


@app.route('/callback', methods=['POST'])
def callback():
    # get X-Line-Signature header value
    try:
        signature = request.headers['X-Line-Signature']
    except Exception as ex:
        app.logger.info("X-Line-Signature error")
        status.update({'error-X-Line-Signature':str(ex)})

    try:
        # get request body as text
        body = request.get_data(as_text=True)
        app.logger.info("Request body: " + body)
    except Exception as ex:
        app.logger.info("Request body error")
        status.update({'error-request.get_data':str(ex)})

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'Hello, World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    # 說啥就回啥
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text))

    return 0

if __name__ == '__main__':
    app.run()

參考連結:

[1] https://github.com/twtrubiks/Deploying-Flask-To-Heroku

[2] https://github.com/twtrubiks/line-bot-tutorial

python linebot doc --> https://pypi.python.org/pypi/line-bot-sdk

董大大的教材 --> https://hackmd.io/s/SJMM4Afpb

聞魚的參考連結 --> https://elements.heroku.com/buttons/abechen/line-bot-python-heroku

https://medium.com/hondtour/line-chatbot-%E9%96%8B%E7%99%BC%E6%8C%87%E5%8D%97-%E4%B8%80-969fd592c08e

Last updated