Speaker: Lee Wei
Tutorial
原本在App上處理的這些服務
未來都有可能被Chat Bot取代
e.g. 預約餐廳
用NLP精準的判斷使用者的意思,串到服務上
Just like the fifth step of...
by Van Oktop
(The Simplest ChatBot)
# Create a line_echobot project
django-admin startproject line_echobot
# Create an echobot app
python3 manage.py startapp echobot
不過這些值不該被git記錄
所以不該被寫死在settings.py
中
建議寫入環境變數
export SECRET_KEY='Your django secret key'
export LINE_CHANNEL_ACCESS_TOKEN='Your line channel access token'
export LINE_CHANNEL_SECRET='Your line channel secret'
# line_echobot/settings.py
......
def get_env_variable(var_name):
try:
return os.environ[var_name]
except KeyError:
error_msg = 'Set the {} environment variable'.format(var_name)
raise ImproperlyConfigured(error_msg)
SECRET_KEY = get_env_variable('SECRET_KEY')
LINE_CHANNEL_ACCESS_TOKEN = get_env_variable('LINE_CHANNEL_ACCESS_TOKEN')
LINE_CHANNEL_SECRET = get_env_variable('LINE_CHANNEL_SECRET')
設定一個Webhook URL
讓Line可以把Bot收到的訊息傳給我們
讓project找到app
# line_echobot/urls.py
......
import echobot
urlpatterns = [
......,
url(r'^echobot/', include('echobot.urls')),
]
......
將app的url導到相對應的function
# echobot/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url('^callback/', views.callback),
]
https://"your domain name"/echobot/callback/
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, WebhookHanlder
from linebot.exceptions import InvalidSignatureError, LineBotApiError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
透過line_bot_api傳訊息給Line,讓Line轉傳給使用者
line_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)
有兩種方法可以處理Line Server送過來的訊息
這裡先用Todo記著,待會再來補上
# TODO: Define Receiver
@csrf_exempt
def callback(request):
if request.method == 'POST':
signature = request.META['HTTP_X_LINE_SIGNATURE']
body = request.body.decode('utf-8')
# TODO: Handler when receive Line Message
return HttpResponse()
else:
return HttpResponseBadRequest()
確認這個request是不是從Line Server傳來的
要確認這件事,需要
signature = request.META['HTTP_X_LINE_SIGNATURE']
body = request.body.decode('utf-8')
取得body跟signature後
Line Bot API會在處理訊息的同時驗證訊息來源
Parse出訊息的所有欄位
e.g.
parser = WebhookParser(settings.LINE_CHANNEL_SECRET)
try:
events = parser.parse(body, signature)
except InvalidSignatureError:
return HttpResponseForbidden()
except LineBotApiError:
return HttpResponseBadRequest()
如果是文字訊息,就回傳給使用者
for event in events:
if isinstance(event, MessageEvent):
if isinstance(event.message, TextMessage):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(
text=event.message.text
)
)
針對每一種不同的訊息型態註冊一個處理器
只要收到這樣的訊息,就會丟給對應的處理器
handler = WebhookHandler(settings.LINE_CHANNEL_SECRET)
@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text)
)
@handler.default()
def default(event):
print(event)
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(
text='Currently Not Support None Text Message'
)
)
try:
handler.handle(body, signature)
except InvalidSignatureError:
return HttpResponseForbidden()
except LineBotApiError:
return HttpResponseBadRequest()
先把django的server run起來
python3 manage.py runserver
用ngrok將request導到本地端的port 8000
ngrok http 8000
再來到Line Bot的Line Developer
頁面
設定Webhook URL
然後就可以跟Bot聊天了
heroku config:set "env key":"env value"
requirements.txt
來判斷是否為Python專案runtime.txt
)
python-2.7.12
python-3.5.2
使用gunicorn部署到Heroku上
requirements.txt
加入gunicorn==19.0.0
Procfile
寫入web: gunicorn line_echobot.wsgi --log-file -
接著
git push heroku master
就部署到Heroku上了
如果使用者問:
要如何知道,他都是要詢問今天的天氣狀況
也就是使用者的「意圖」
同樣是天氣的問題
e.g.
if '天氣' in text:
if '今天' in text:
return today_s_weather
elif '明天' in text:
return tomorrow_s_weather
一款基於XML的markup language
這是最基本的AIML
<aiml version="1.0.1" encoding="UTF-8"?>
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User!
</template>
</category>
</aiml>
這些服務能透過標記和訓練
解析出這句話的每一個片段,所具有的意義
Wit.ai跟Luis, API.ai比較不同的地方是
從Wit.ai得到的是,我們設定的回覆
而不是一句話解析後的結果
how is the weather in the Taipei
{
"query": "how is the weather in the Taipei",
"topScoringIntent": {
"intent": "GetCurrentWeather",
"score": 0.50119406,
"actions": [
{
"triggered": false,
"name": "GetCurrentWeather",
"parameters": [
{
"name": "location",
"required": true,
"value": null
}
]
}
]
},
"entities": [],
"dialog": {"contextId": "80cd646a-d85d-4b40-873d-1b47fa49adc8",
"status": "Question",
"prompt": "Where would you like to get the current weather for?",
"parameterName": "location"
}
}
Hey Calendar, schedule lunch with
Mary Johnson at 12 pm tomorrow.
{
"action":"meeting.create",
"name":"Lunch with Mary Johnson",
"invitees":["Mary Johnson"],
"time":"2014-08-06T12:00:00-07:00"
}
不過就算做了這些分詞、判斷意圖
也不能保證使用者就會買單
有人稱Chat Bot為下一代的UX Design
更進一步是
如何設計一個有個性、有溫度的機器人