LineBotは話しかけられたことの応答だけでなく、UserId
などを指定してBotの方から話しかけること(Push通知)ができる
ハンズオンはDeveloper Trialプランを前提としているので、Push通知をするBotを作ってみる。
最初にテスト用に作っていたPushクラスを変更して、Push通知用のクラスにする。
******
のところは、Botをフォローしたときに教えてくれた自分のUserId(実際の開発時はデータベースなどから取得してくる)か、Message API の画面の一番下の Your user ID の値で書き換える。
package com.example.linebot;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.PushMessage;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.response.BotApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutionException;
@RestController
public class Push {
private static final Logger log = LoggerFactory.getLogger(Push.class);
// push先のユーザID(本来は、友達登録をした瞬間にDBなどに格納しておく)
private String userId = "******";
private final LineMessagingClient client;
@Autowired
public Push(LineMessagingClient lineMessagingClient) {
this.client = lineMessagingClient;
}
// ------------ 中略・変更なし ------------
// 時報をpushする
@GetMapping("timetone")
public String pushTimeTone() {
String text = DateTimeFormatter.ofPattern("a K:mm").format(LocalDateTime.now());
try {
PushMessage pMsg
= new PushMessage(userId, new TextMessage(text));
BotApiResponse resp = client.pushMessage(pMsg).get();
log.info("Sent messages: {}", resp);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
return text;
}
}
LinebotApplication を一度停止して、再起動する。
http://localhost:8080/timetone にブラウザでアクセスし、ブラウザに現在時刻が表示されることを確認する。同時に、LINEBotも時刻を発言していることを確認する。
難しいと感じる人は読み飛ばして次の手順に行っても良いです
LineMessagingClient
が、Line Messaging APIとの仲介をする。(Callbackの場合は、受信専用のクラスとして作るための@LineMessageHandler
が準備も自動化していた)client.pushMessage
メソッドに、ユーザIDと送信するMessageを渡したPushMessage
オブジェクトを渡し、get
メソッドを呼び出すことで、LineBotからユーザID宛てにMessageが送信される。- 複数人に同じメッセージを送るときは
Multicast
クラスとclient.multicast
メソッドを使う。(グループやトークループにpushはできない)