iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 18
1
AI & Machine Learning

ChatBot&Chatbase系列 第 18

Day18[Line ChatBot]!未解決!Dialogflow&LineBot之間的連接問題

繼Day17的製作以後
原本是想繼續做,讓Line輸入訊息後
傳送到Dialogflow來進行語句分析
接著再回傳entity
並用python給予相對應的回應
最後回傳至Line給使用者
但還不知道怎麼讓兩者結合
因此卡關!

以下還是先把我的嘗試過程做個解釋
1.首先我先把兩個程式碼都貼到同一個檔案XD
想說比較好剪貼做整合
第一部分為Day17所說的在取得Dialogflow輸入訊息後用python來定義回應的內容

@app.route("/", methods=['GET'])
def hello():
    return "Hello World!"

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)
    res = makeWebhookResult(req)
    res = json.dumps(res, indent=4)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def makeWebhookResult(req):
    if req.get("result").get("action") != "askweather":
        return {}
    result = req.get("result")
    parameters = result.get("parameters")
    zone = parameters.get("weatherlocation")
    cost = {'Taipei':'18', 'Kaohsiung':'20', 'Taichung':'10','Tainan':'25'}
    speech = "The temperatrue of " + zone + " is " + str(cost[zone])
    return {
        "speech": speech,
        "displayText": speech,
        "source": "agent"
    }

第二部分為Line處理訊息

@app.route("/", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    print("Request body: " + body, "Signature: " + signature)
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
       abort(400)
    return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    msg = event.message.text
    #print(type(msg))
    msg = msg.encode('utf-8')
    if event.message.text == "你好":
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.message.text))
        return 'OK2'

根據我個人的理解
要讓兩者結合
應該是要讓使用者在Line上輸入的文字成為Dialogflow的輸入
並在Dialogflow分析完成後將回應回傳之後,再回到Line回覆給使用者

結合之路1:
可以明顯看出來兩個都有使用Webhook route
因此遇到Q1
Q1:兩個route可以使用同一個嗎?
首先我先讓兩個接收訊息的route先改成同一個

@app.route('/', methods=['POST'])
def webhook():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    body2 = request.get_json(silent=True, force=True))
    print("Request body: " + body, "Signature: " + signature)
    res = makeWebhookResult(body2)
    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
       abort(400)
    return r

在 signature = request.headers['X-Line-Signature'] 便會出錯
因Dialogflow要makeWebhookResult給回應時
所得到的輸入參數跟request.headers['X-Line-Signature']有衝突的樣子
所以無法成功被執行
而刪除此行會造成Line收發訊息有問題
(以上程式碼在LineBot也無法成功收到回應,需把try到abort(400)這幾行貼到body2下才行)
總之弄到同一個route的結合之路似乎不太順暢
但要呼叫不同route去執行這個方法...我還在找資料,不知道是否可行

2.拆Json檔來對應 (不知道這樣的說法對不對)
我想表達的意思如下:
下圖是在Line輸入訊息會讀取到的Json格式內容
https://ithelp.ithome.com.tw/upload/images/20180116/201071444UvNoZWCRS.png
而這張圖是在Dialogflow測試輸入訊息會讀取到的Json格式內容
https://ithelp.ithome.com.tw/upload/images/20180116/20107144p2d4cAuzj3.png
Q2:如果讓兩紅框之處相同時,再進行處理與回送訊息或許可行?
遇到的問題在於找不到Dialogflow輸入的入口點在哪邊
因此在輸入時首先就遇到問題...

總之在兩者之間如何溝通上
或許是寫法抑或是想法
我還沒有真正的搞懂以及理解
在程式能力上當然也還需要非常大的努力加強
仍然在繼續理解與研究中!
如果有什麼方向或建議或方法,請大家多多指教!!!
/images/emoticon/emoticon41.gif

當然,如果解決了也會再更新此篇!!


上一篇
Day17[Line ChatBot]Dialogflow&python
下一篇
Day19[Line ChatBot]Line一下爬好爬滿(上)
系列文
ChatBot&Chatbase30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
henryhuang
iT邦新手 5 級 ‧ 2018-10-27 00:05:17

我找到連接Line及Dialog flow的方法
以下次是我的方法apiai好像非dialog flow正式官方的Api,但依然可以順利執行

  1. 安裝Pip install apiai #https://pypi.org/project/apiai/

  2. Create an API.AI account <http://api.ai>_.在 dialog flow上

  3. ai = apiai.ApiAI('YOUR_CLIENT_ACCESS_TOKEN')

  4. def parse_user_text(user_text):
    '''
    Send the message to API AI which invokes an intent
    and sends the response accordingly
    '''
    request = ai.text_request()
    request.query = user_text
    #request.session_id = "123456789"
    response = request.getresponse().read().decode('utf-8')
    responseJson = json.loads(response)

    return responseJson

    Diaresponse = parse_user_text( event.message.text ) #抓下Dialog flow進行NLP後的JSON檔 檔案我將它存成Dict

我要留言

立即登入留言