[Line Bot] Linebot + Django 實作

ycpin
7 min readAug 21, 2023

--

targets: Linebot + Django framework, chatbot implementation.

Django 是一個基於 Python 的網頁框架,其架構不同於三大前端框架

  • Django: Model-Template-Views (MTV) 架構
  • React.js / Angular.js / Vue.js: Model-View-Contorller (MTC) 架構
Django 架構
  1. Model: 取用後端資料
  2. Template: 原始 html
  3. Views: 顯示出來的網頁內容

完整流程

Django 完整運作流程

實作專案

  • 建立虛擬環境
pip install virtualenv

# 建立虛擬環境
virtualenv 'linebot-env'

# 啟動虛擬環境
.\linebot-env\Scripts\activate

# 退出虛擬環境
deactivate
# Windows PowerShell
Set-ExecutionPolicy RemoteSigned

安裝相關套件

pip install Django
pip install line-bot-sdk

建立專案

cd D:/
django-admin startproject '專案名稱'
cd '專案名稱'
  • 建立 APP:可以進行多個 Line Bot 開發
python manage.py startapp 'APP名稱'

基礎設定 setting.py

1. 新增兩個資料夾

md static
md templates
  • static 用於靜態資料如圖片、檔案
  • templates 用於放寫好的 html

2. 設定 Channel Access Token & Channel Secret

3. 於 INSTALLED_APPS 中設定建立的 APP 名稱

4. 於 TEMPLATES 中設定 templates 的資料夾路徑

5. 語系、時區的設定

6. 新增 static 路徑

7. 開發階段設定

8. 資料庫遷移的初始化

python manage.py makemigrations
python manage.py migrate

9. 建立管理者帳號

python manage.py createsuperuser

10. 執行 runserver 進行測試

python manage.py runserver
# 開啟瀏覽器進入 127.0.0.1:8000/admin
  • 登入畫面

設定 urls.py

from django.contrib import admin
from django.urls import path
from example import views

urlpatterns = [
path('admin/', admin.site.urls),
path('callback', views.callback),
]

設定 views.py

from django.shortcuts import render

# Create your views here.
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(settings.LINE_CHANNEL_ACCESS_TOKEN)
parser = WebhookParser(settings.LINE_CHANNEL_SECRET)


@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):
mtext=event.message.text
message=[]
message.append(TextSendMessage(text=mtext))
line_bot_api.reply_message(event.reply_token,message)

return HttpResponse()
else:
return HttpResponseBadRequest()

說明

  • LINE server 收到訊息後主動傳送 LINE BOT,因此需要告訴 server,當收到訊息時的傳送位置,此為 webhook URL
  • 當 callback 函數被呼叫時,是收到由 LINE server 發過來 LINE BOT 的 webhook

ngrok 設定

下載網址:https://ngrok.com/download

1. 開啟 Django 伺服器 + 啟動 ngrok

python manage.py runserver
./ngrok http 8000

2. LINE Developer 後台貼上 webhook URL

# webhook URL範例
https://yourdomain_name/callback

完成!

Github Repo

Related Article

--

--

ycpin

[技術、遊記、攝影] 在夢與現實中徘徊,專注資訊技術,懷抱文人風骨