昨天我們在 n8n 中模擬了 LINE Bot 的運作流程,但只是「假裝」有訊息進來。
今天要來真的把 LINE 官方 Bot 串起來,讓 LINE 使用者的訊息經過 n8n 傳到 Dify,由 AI 回覆後再傳回 LINE,
正式完成「智慧客服」或「AI 助手」的自動化架構!
首先,前往 LINE Developers Console。
使用你的 LINE 帳號登入後,畫面會出現「Provider」與「Channel」的管理介面。
點選「Create a new provider」,輸入名稱(例如:n8n-Dify Lab)
進入該 Provider 後,點「Create a Messaging API Channel」
填寫:
同意條款並建立完成,接著會進入 Channel 設定頁。
在「Messaging API」頁面中找到以下資訊,稍後都會用到:
項目 | 說明 |
---|---|
Channel secret | 驗證簽章時使用 |
Channel access token (long-lived) | 呼叫 LINE API 時使用 |
Webhook URL | 稍後要設定為 n8n 提供的 Webhook URL |
這個流程主要會包含四個節點:
Webhook → Function → HTTP Request (Dify) → HTTP Request (LINE)
新增一個 Webhook 節點,設定如下:
項目 | 值 |
---|---|
HTTP Method | POST |
Path | line-webhook |
Authentication | None |
Respond | Using 'Respond to Webhook' Node |
測試時網址會是:
http://localhost:5678/webhook-test/line-webhook
LINE 傳來的資料格式如下:
{
"events": [
{
"type": "message",
"message": { "type": "text", "text": "你好" },
"replyToken": "abcd1234..."
}
]
}
所以我們加一個 Function 節點,用這段程式碼解析出「訊息內容」與「回覆 token」:
const event = $json["body"]["events"][0];
return [{
json: {
user_message: event.message.text,
replyToken: event.replyToken
}
}];
這樣下一步就能直接用 {{$json["user_message"]}}
來讀取使用者訊息。
在這裡,我們把剛剛解析的使用者訊息送進 Dify。
項目 | 值 |
---|---|
Method | POST |
URL | https://api.dify.ai/v1/chat-messages |
Headers | Authorization: Bearer <你的 Dify API 金鑰> 、Content-Type: application/json |
Body Content Type | JSON |
JSON Body |
{
"inputs": {},
"query": "={{$json['user_message']}}",
"response_mode": "blocking",
"user": "line-bot"
}
接著,讓 AI 的回答透過 LINE 官方 API 回傳給使用者。
項目 | 值 |
---|---|
Method | POST |
URL | https://api.line.me/v2/bot/message/reply |
Headers | Authorization: Bearer <你的 LINE Channel Access Token> 、Content-Type: application/json |
Body Content Type | JSON |
JSON Body |
{
"replyToken": "={{$json['replyToken']}}",
"messages": [
{
"type": "text",
"text": "={{$json['answer']}}"
}
]
}
最後補上一個「Respond to Webhook」節點。
設定:
http://伺服器IP或網域/webhook/line-webhook