本篇將使用
Python + Django + Ngrok 快速架設一個Line回應聊天機器人
主要分為三個部分:
1.Line開發者帳號申請與設定
2.Python本地架設 與 Django 環境開發
3.Ngrok設定與部署
1.Line開發者帳號申請與設定
至 Linedevelopers 創建帳號
https://developers.line.biz/zh-hant/
建立 Provider
Create new Channel > Messaging API > Confirm > Create
建立好後點選進入剛才創建的 Provider
主要會使用到的有以下欄位:
1. Channel secret
2. Channel access token (點選右側 Issue生成)
3. Use webhooks 點選右側 Edit 將選項由 Disable 改為 Enable > Update)
4. Webhook URL 這邊需要SSL憑證,所以大家會推薦使用 ngrok 或是 Heroku 部署,本篇後續會使用 ngrok
5. Auto-reply messages 點選右側 Set message,將自動回應停用
2.Python本地架設 與 Django 環境開發
1.安裝 python
至 Python 官網 下載 python for windows ,目前我這邊是3.8.0的版本
https://www.python.org/downloads/
安裝好 python 後,需要進行環境變數的設定
至本機(我的電腦) 點選右鍵>內容> 進階系統設定(左側) > 環境變數 > 使用者環境變數 >點選點數為 Path 的條目 >編輯
貼上剛才安裝的 python 路徑 ,Python/Scripts 路徑
※查看路徑的方式: 對安裝好的 python捷徑右鍵更多開啟檔案位置,在對捷徑右鍵內容查看目標(檔案路徑)
以下為範例:
你的路徑\Python\Python38-32\
你的路徑\Python\Python38-32\Scripts
測試:
打開cmd(命例提示字元)
輸入 python 查看是否正確進入python環境 exit() 離開
輸入pip 查看是否有從 Scripts找到 pip 套件
2. 安裝Django與相關套件
進入 cmd
安裝 django、line_bot_sdk
pip install django==2.27
pip3 install line-bot-sdk
接著架設django環境
創建一個資料夾,作為主目錄,並使用django語法創建專案
mkdir linebot
cd linebot
django-admin startproject mylinebot #創建mylinebot專案
cd mylinebot
python manage.py runserver 0.0.0.0:8080 #運行django
接著創建django 中的 app,專門運行 linebot
python manage.py startapp bot
目前我們的目錄是這個樣子的
E:. │ TREE.TXT │ └─── mylinebot │ db.sqlite3 │ manage.py │ ├───bot │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ __init__.py │ │ └───mylinebot settings.py urls.py wsgi.py __init__.py
mylinebot 是我們專案的主目錄,裡面包含有settings專案設定檔案 、urls 主路徑檔案(會在這include其他app中的url路徑)
bot 則是我們剛才創建的 app ,會在此目錄的 view撰寫linebot程式、在url建立路徑
首先撰寫我們的linebot程式
開啟 bot/views.py
# import 必要的函式庫 from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from linebot import LineBotApi, WebhookParser from linebot.exceptions import InvalidSignatureError, LineBotApiError from linebot.models import MessageEvent, TextSendMessage line_bot_api = LineBotApi("Channel_secret") #在 line_developer取得 parser = WebhookParser("Channel_access_token") #在 line_developer取得 @csrf_exempt def callback(request): if request.method == 'POST': signature = request.META['HTTP_X_LINE_SIGNATURE'] body = request.body.decode('utf-8') try: events = parser.parse(body, signature) except InvalidSignatureError: return HttpResponseForbidden() except LineBotApiError: return HttpResponseBadRequest() for event in events: if isinstance(event, MessageEvent): line_bot_api.reply_message( event.reply_token, TextSendMessage(text=event.message.text) ) return HttpResponse() else: return HttpResponseBadRequest()
設定 bot 中的 url 路徑,
from django.conf.urls import include, url from . import views urlpatterns = [ url('^callback/', views.callback), ]
最後設定mylinebot 中的 url 檔案
要將bot 的 urls 檔案 include 進來,以下為程式碼:
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^bot/', include('bot.urls')), ]
※ 此時 url路徑為 /bot/callback/ ,就會運行 bot 底下的 callback 函數
運行 django
python manage.py runserver 0.0.0.0:8080 #運行django
3.Ngrok設定與部署
※透過 ngrok 監聽 django 的 port ,來取得 SSL 網址
DOWNLOAD for Windows
解壓縮後運行 ngrok.exe
剛才我們 django 是用 8080 port runserver ,所以這裡要監聽 8080 port
輸入 ngrok http 8080
ngrok http 8080 ############################################# ngrok by @inconshreveable Session Status online Session Expires 7 hours, 26 minutes Version 2.3.35 Region United States (us) Web Interface http://127.0.0.1:4040 Forwarding http://d421944a.ngrok.io -> http://localhost:8080 Forwarding https://d421944a.ngrok.io -> http://localhost:8080
複製那段 https的網址
回到 Linedeveloper頁面
在 Webhook URL Requires SSL 右側 Edit
https://d421944a.ngrok.io/bot/callback/
點選 update
拉到最下方掃描 qrcode ,開始你的 Line Bot 吧!
參考:
留言列表