這幾天我們已經學會建構,測試,部署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,今天先以簡單的回應為例:
當Azure Functions收到line的帳號關注事件(Follow event)和訊息事件(Message event)時
我們只根據event訊息格式撰寫簡單的程式,判斷後即可回應用戶。
至於該如何回應訊息呢?我們將在下一小節做介紹!
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 ,並記得將lineWebhook url 填入官方帳號的Webhook settings
可參考-Day [7] Azure Functions-將函式部署至Azure-Day [8] Azure Functions-使用 LINE Messaging API