LINE BOT入門 vol.4:SpringBootプロジェクト作成
■①SpringBootプロジェクトを作成する
・名前:任意 ※今回は「line_bot」とする
・型:Gradle(Buildship 3.x)
・Javaバージョン:11
【依存関係】
・Spring Boot DevTools
・Lombok
・Spring Web
■②文字コードを「UTF-8」に変更
「ウィンドウ」⇒「設定」⇒「一般」⇒「ワークスペース」を押下し、文字コードを「UTF-8」に変更する
■③Herokuでデプロイする時にエラーにならないようにアノテーションを使用可能にする
プロジェクトを「右クリック」⇒「プロパティー」⇒「Javaコンパイラー」⇒「注釈処理」を押下し、「プロジェクト固有の設定を可能にする」と「注釈処理を使用可能にする」にチェックを入れる
■④依存関係に「Line Bot Spring Boot」を追加する
「Maven Repository」で「line-bot-spring-boot」を検索すると下記が見つかる
https://mvnrepository.com/artifact/com.linecorp.bot/line-bot-spring-boot
「build.gradle」ファイルの「dependencies」ブロックに下記を追記する
implementation 'com.linecorp.bot:line-bot-spring-boot:4.2.0'
■⑤Gradleプロジェクトをリフレッシュする
「build.gradle」ファイルを右クリックして「Gradle」⇒「Gradleプロジェクトのリフレッシュ」を押下
■⑥LINEと連携可能にする為にJavaファイルを編集する
「LINE Messaging API SDK」にアクセスし、「sample-spring-boot-echo」の「EchoApplication.java」を参考に作成したプロジェクトの「LineBotApplication.java」を編集する
LINE Messaging API SDK
編集するJavaファイル ⇒ LineBotApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.linecorp.bot.model.event.Event;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
@SpringBootApplication
@LineMessageHandler
public class LineBotApplication {
public static void main(String[] args) {
SpringApplication.run(LineBotApplication.class, args);
}
@EventMapping
public Message handleTextMessageEvent(MessageEvent<TextMessageContent> event) {
final String originalMessageText = event.getMessage().getText();
return new TextMessage(originalMessageText);
}
@EventMapping
public void handleDefaultMessageEvent(Event event) {
System.out.println("event: " + event);
}
}
下記アノテーションを忘れないようこと
@LineMessageHandler
■⑦application.propertiesにトークンとシークレットを追記する
前回の記事でコピーしておいた「Channel access token」と「Channel secret」を追記
更にハンドラーパスも追記する
line.bot.channel-token=トークン
line.bot.channel-secret=シークレット
line.bot.handler.path=/