2020/08/05
2021/03/16 (補充)
2021/03/23 (更新資料)
Messaging API / Messaging API 介紹
Webhook Event Objects 這是Line Server傳給line bot的內容
Send reply message 這是從line bot回應給Line Server
提供了一些Java 類別可以直接使用,如果使用maven,要在pom.xml裡加上:
<dependency>
<groupId>com.linecorp.bot</groupId>
<artifactId>line-bot-spring-boot</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>com.linecorp.bot</groupId>
<artifactId>line-bot-model</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>com.linecorp.bot</groupId>
<artifactId>line-bot-api-client</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>com.linecorp.bot</groupId>
<artifactId>line-bot-servlet</artifactId>
<version>4.3.0</version>
</dependency>
使用這個範例時,要記得根據/src/main/resources/application-template.yml,改為/src/main/resources/application.yml,並設定Channel Token、Channel Secret及對應路徑。
line.bot:
channel-token: 'Put Your Channel Token Here.'
channel-secret: 'Put Your Channel Secret Here.'
handler.path: /callback
使用Ngrok的好處是相對簡單,如果沒有註冊的話就要常常(20分鐘)重新產生新的url,如果註冊的話,就不用這麼麻煩。
先下載ngrok ,利用ngrok產生公用url:
ngrok http 8080
就會得到一組public url。
登入Line Developers ,可以點選使用Line帳號登入。
接下來,新增一個開發者的帳號,再產生一個Provider帳號。
選擇Create a Message API channel
輸入email等資料
在Basic Setting裡
Channel access token 按"issue" (如果token不存在的話)
在Message API下,可以看到QR Code,掃QR code,把ngrok產生的url放進Web hook URL,每次執行ngrok時都會產一組臨時的URL,每次重開機後就要改一次。記得要再產生的Web hook URL後面加上"/callback"
https://65343c46a1c7.ngrok.io/callback
確認use webhook已經打開
接下來,clone學義學長的範例專案
git clone https://github.com/jack19990504/LineBot_Demo.git
把Message API底下,Channel access token按Issue。將Channel access token裡的token貼到LineKeys.java,把XXX換掉。
package com.example.demo.keys;
public interface LineKeys {
String accessToken = "XXX";
}
啟動spring專案。
在line console按verify,在vs code裡可以看到
ReplyToken : 00000000000000000000000000000000
Text : Hello, world
UserId : Udeadbeefdeadbeefdeadbeefdeadbeef
Resp Code:400; Resp Message:Bad Request
回復失敗
到Line Official Account Manager
到"自動回應訊息",將"自動回應訊息"關閉。並且到"聊天",確認"自動回應訊息"設為"停用",這樣才能看到我們的回應內容。
這時候利用line就可以輸入訊息,line bot會回應我們輸入的訊息了。並且在vs code裡可以看到
ReplyToken : 6324542fe52b409d9493d1b8ab803132
Text : hello
UserId : U4e438124561034bf1852da3159c8831c
Resp Code:200; Resp Message:OK
成功回復
**注意,每次重開機就要重覆進行以下動作:
執行ngrok
更新webhook URL
要確認自動回應訊息被關閉了。
試著回應輸入的內容加上自己的內容,如:輸入"hello",輸出"hello from Ben"。
試著當輸入內容是特定關鍵字時,有不同的回應,如:輸入"hello",輸出"hello from Ben"。輸入"hi",輸出"hi, there"。
Line bot環境設定
ngrok
Line developer
建立line developer帳號
登入
新增provider
新增channel 及相關設定
Spring專案
Line official account manager
帳號管理
智慧聊天
圖文選單