Try   HackMD

快速打造Line Chatbot

tags: fly.io deploy chatbot line 聊天機器人 教學

使用python部署至 fly.io

建立帳號

  • 首先進入:https://manager.line.biz ,建立chatbot的帳號

  • 個人使用的話按"使用LINE帳號登入"

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 用自己的帳號密碼或是掃QR code登入

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • "建立LINE商用ID"

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • "建立LINE官方帳號"

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 輸入完相關資訊後,按下確認。
    到下一頁確認無誤後,按下完成。

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 頁面會顯示"您的LINE官方帳號已建立完成",按下"稍後進行認證(前往管理會面)",再次按下"同意"後,進入管理畫面。

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 此時網址應是https://manager.line.biz/account/{@your_id}/
    這個{@your_id}就是這個帳號的id,可以透過id加入好友。
    於此同時,剛剛建立好的帳號會自動加入好友,並傳送一段訊息。
    到這一步,最基本的建立帳號已經完成!

  • 如果只是要單純的特定訊息自動回應,點選左側的"自動回應訊息",便可建立最基本的自動回應內容,簡易的chatbot就完成了。

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 要注意的是,如果要用接下來的步驟使用程式控制chatbot,先將Default的回覆刪除,不然不管傳什麼訊息都會有這則回覆。

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

帳號設定

  • 忘記id不要緊張,可以從 https://manager.line.biz 選擇帳號

  • 進入https://manager.line.biz/account/{@your_id}/頁面,點選上方列的'聊天'

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • "前往回應設定頁面"

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 點選左側的"Messaging API"

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • "啟用Messaging API"

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 輸入使用者名稱及email後,輸入服務提供者名稱(隨便填),隱私權政策及服務條款先不填寫,直接按"確定",啟用Messaging API,會看到Messaging API畫面變成這樣,Webhook網址先空著,最後再來填上。

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 回到回應設定,將"Webhook"及"自動回應訊息"開啟。

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

取得Token

  • 這是很重要的一步,我們要拿到Channel access tokenChannel secret
  • 前往 https://developers.line.biz/console ,選擇剛建立的帳號。
  • 在"Basic settings"頁面中可以找到Channel secret
  • 接著是Channel access token,選擇"Messaging API"
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
  • 在頁面的最下面會看到
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
  • 勇敢的按下"Issue"後,會看到一長串的亂碼,那就是我們要的Channel access token
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
  • Channel access tokenChannel secret兩個重要的資訊記下來後,就可以進入python的部分了。

Python

  • 先安裝line套件,如果沒有要在本機測試,可以跳過這步。

    ​​​​pip install line-bot-sdk
    
  • 建立一個{app_name}.py,{app_name}為自己的檔名

    ​​​​# coding: utf-8
    ​​​​from flask import Flask, request, abort
    ​​​​from linebot import LineBotApi, WebhookHandler
    ​​​​from linebot.exceptions import InvalidSignatureError
    ​​​​from linebot.models import MessageEvent, TextMessage, TextSendMessage
    
    ​​​​#line token
    ​​​​channel_access_token = '{Channel_access_token}'
    ​​​​channel_secret = '{Channel_secret}'
    ​​​​line_bot_api = LineBotApi(channel_access_token)
    ​​​​handler = WebhookHandler(channel_secret)
    
    ​​​​app = Flask(__name__)
    
    ​​​​# 監聽所有來自 /callback 的 Post Request
    ​​​​@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:
    ​​​​        abort(400)
    ​​​​    return 'OK'
    
    ​​​​@handler.add(MessageEvent, message=TextMessage)
    ​​​​def handle_message(event):
    ​​​​    #echo
    ​​​​    msg= event.message.text
    ​​​​    message = TextSendMessage(text=msg)
    ​​​​    line_bot_api.reply_message(event.reply_token,message)
    
    ​​​​import os
    ​​​​if __name__ == "__main__":
    ​​​​    port = int(os.environ.get('PORT', 5000))
    ​​​​    app.run(host='0.0.0.0', port=port)
    
  • 輸入剛剛存下來的Channel access tokenChannel secret

    ​​​​channel_access_token = '{Channel_access_token}'
    ​​​​channel_secret = '{Channel_secret}'
    
  • 這邊只做最簡單的回聲機器人,chatbot會復述剛剛輸入的話,可以針對所需再進行修改。

    ​​​​@handler.add(MessageEvent, message=TextMessage)
    ​​​​def handle_message(event):
    ​​​​    #echo
    ​​​​    msg= event.message.text
    ​​​​    message = TextSendMessage(text=msg)
    ​​​​    line_bot_api.reply_message(event.reply_token,message)
    
  • 其他回覆方式可參考line-bot-sdkGitHubLINE官方文件

  • 範例檔案可參考 https://github.com/littlehsun/linechatbot-demo

部署至 fly.io

  • 需要先建立兩個檔案:Procfilerequirements.txt

  • 建立Procfile,要注意Procfile沒有副檔名

    ​​​​web: python {app_name}.py
    
  • 建立requirements.txt

    ​​​​line-bot-sdk
    ​​​​flask
    
  • {app_name.py}Procfilerequirements.txt三個檔案放至同一個資料夾{project_folder}

  • 安裝flyctl(MacOS),其他作業系統請參考fly官網
    如果有homebrew的話,執行:

    ​​​​brew install flyctl
    

    沒有就執行:

    ​​​​curl -L https://fly.io/install.sh | sh
    
  • 註冊

    ​​​​flyctl auth signup
    
  • 登入

    ​​​​flyctl auth login
    
  • 進入專案資料夾

    ​​​​cd {project_folder}
    
  • 啟動專案

    ​​​​flyctl launch
    

    如果原本有Procfile檔,會問是否要overwrite,選No就好。

    輸入專案的名稱{project_name}

    選擇喜歡的伺服器,比較近的應該是香港跟東京。
    如果沒有要使用資料庫,就都選No。


    執行完成後,會發現{project_folder}資料夾中多了一個fly.toml檔,不用動它

  • 開始部署:

    ​​​​flyctl deploy
    


    等待執行完成

  • 執行flyctl status查看專案狀況,其中hostname:{project_name}.fly.dev便是webhook所需要的網域

  • 可參考 https://hackmd.io/@littlehsun/r1RK0QDwj

設定Webhook

  • 獲得{project_name}.fly.dev後,由於程式內的設定是@app.route("/callback", methods=['POST']),因此webhook網址是https://{project_name}.fly.dev/callback

  • https://manager.line.biz 的 "Messaging API"頁面,輸入https://{project_name}.fly.dev/callback ,按下儲存。

  • 或是到 https://developers.line.biz/console 的 "Messaging API"分頁,找到Webhook settings,輸入 https://{project_name}.fly.dev/callback 並update後,執行verify,跳出Success就完成了。比較推薦這個方法,因為可以verify這個webhook是不是有成功運作。

完成!

  • 簡單的echo chatbot就大功告成了!
  • 可以搭配LINE內建的自動回應功能,更豐富chatbot的完整性