iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
1
Microsoft Azure

白眼狼的30天Azure跳槽計畫系列 第 9

Day [9] Azure Functions-Line Chatbot實作(ㄧ)

  • 分享至 

  • twitterImage
  •  

處理Webhook Event

這幾天我們已經學會建構,測試,部署Azrue Functions並接收Line Webhook事件,當官方帳號有事件發生時
Azure Functions 將收到下列Webhook Event資料,JSON格式範例如下:

{
  "destination": "xxxxxxxxxx",
  "events": [
    {
      "replyToken": "0f3779fba3b349968c5d07db31eab56f",
      "type": "message",
      "mode": "active",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U4af4980629..."
      },
      "message": {
        "id": "325708",
        "type": "text",
        "text": "Hello, world"
      }
    },
    {
      "replyToken": "8cf9239d56244f4197887e939187e19e",
      "type": "follow",
      "mode": "active",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U4af4980629..."
      }
    }
  ]
}

當Azure Functions 收到上述的Webhook Event資料後就可以根據Chatbot的需求處理Webhook事件嘍!

還記得目標嗎?

Day[3] Why Azure Functions?-目標需求我們想要完成口罩餘額查詢的Chatbot,今天先以簡單的回應為例:

https://ithelp.ithome.com.tw/upload/images/20200924/20108281shCXEAUq89.png

當Azure Functions收到line的帳號關注事件(Follow event)和訊息事件(Message event)時
我們只根據event訊息格式撰寫簡單的程式,判斷後即可回應用戶。
至於該如何回應訊息呢?我們將在下一小節做介紹!

Reply messages & Push messages

Line Messaging API 回應用戶有2種方法

2種回應訊息分別使用replyToken, userId(可由上一小節Webhook Event資料取得)
特別注意:replyToken有效的時間是30秒,且只能使用一次!

了解後撰寫一隻簡單的程式即可根據用戶的行為處理Webhook Event回應訊息了
範例程式:

import { Client } from '@line/bot-sdk'

const client = new Client({
    channelAccessToken: '<YOUR_CHANNEL_ACCESS_TOKEN>',
    channelSecret: '<YOUR_CHANNEL_SECRET>'
});

export const replyMessage = (replyToken: string, message: string) => {
    client.replyMessage(replyToken, {
        type: 'text',
        text: message
    });
}

export const pushMessage = (userId: string, message: string) => {
    client.pushMessage(userId, {
        type: 'text',
        text: message
    });
}

重新部署Azure functions

撰寫完成後記得要重新部署Azure Functions ,並記得將lineWebhook url 填入官方帳號的Webhook settings
https://ithelp.ithome.com.tw/upload/images/20200925/20108281LVLhBl8mhn.jpg

可參考-Day [7] Azure Functions-將函式部署至Azure-Day [8] Azure Functions-使用 LINE Messaging API


上一篇
Day [8] Azure Functions-使用 LINE Messaging API
下一篇
Day [10] Azure Functions-Line Chatbot實作(二)
系列文
白眼狼的30天Azure跳槽計畫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言