Skip to content

Latest commit

 

History

History
88 lines (61 loc) · 3.72 KB

08.md

File metadata and controls

88 lines (61 loc) · 3.72 KB

Botから話しかける(Push通知)

はじめに

LineBotは話しかけられたことの応答だけでなく、UserId などを指定してBotの方から話しかけること(Push通知)ができる

⚠️ただし利用するには、友達人数・メッセージ配信数に制限のある開発用・無料のDeveloper Trialプランか、有料のPro(API)プランの契約が必要。LINE@プラン・料金の「MessagingAPIで利用できる料金プラン」を参考にしてください

ハンズオンはDeveloper Trialプランを前提としているので、Push通知をするBotを作ってみる。

Pushクラスを変更

最初にテスト用に作っていた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はできない)

戻る