LoginSignup
5
5

More than 5 years have passed since last update.

api.aiのwebhookで音声データを返す

Last updated at Posted at 2017-08-02

概要

  • api.aiでは単なるテキストだけではなく、Custom Payloadとして音声データや動画、ファイルなどのリッチメッセージを返すことができます。
    • 参考)Rich Messages
    • 全てのintegrationが対応しているわけではないっぽい
  • facebookメッセンジャーでのwebhook時にどういったレスポンスを返せばいいかの備忘録です。

実装

  • というほどのものではないですが、例えば音声データを返したいというときは以下のようなjsonを返す実装をしていきます。
fulfillment
"fulfillment": {
      "messages": [
        {
          "payload": {
            "facebook": {
              "attachment": {
                "payload": {
                  "url": "https://hogehoge/audio/description.mp3"
                },
                "type": "audio"
              }
            }
          },
          "type": 4
        }
      ]
    }
  • Controllerです。何やらFulfillmetをそのまま返すとExceptionが発生してしまうので文字列で返してます。
MainController.java
@Controller
public class MainController {

    private final MainService mainService;

    public MainController(MainService mainService) {
        this.mainService = mainService;
    }

    @ResponseBody
    @PostMapping(value="/webhook")
    public String webhook(HttpServletRequest request) {
        return mainService.createFulfillmentJson();
    }
}
  • json作ります。
  • リッチメッセージに合わせて、ResponseMessageを継承したResponseSpeechResponseImageResponsePayloadなどがそれぞれ用意されています。
MainService.java
@Slf4j
@Service
public class MainService {
    private final Gson gson = GsonFactory.getDefaultFactory().getGson();

    public String createFulfillmentJson() {
        JsonObject urlJson = new JsonObject();
        urlJson.addProperty("url", "https://hogehoge/audio/description.mp3");

        JsonObject payloadJson = new JsonObject();
        payloadJson.add("payload", urlJson);
        payloadJson.addProperty("type", "audio");

        JsonObject attachmentJson = new JsonObject();
        attachmentJson.add("attachment", payloadJson);

        JsonObject facebookJson   = new JsonObject();
        facebookJson.add("facebook", attachmentJson);

        ResponsePayload responsePayload = new ResponsePayload();
        responsePayload.setPayload(facebookJson);

        List<ResponseMessage> messages = Collections.singletonList(responsePayload);

        Fulfillment fulfillment = new Fulfillment();
        fulfillment.setMessages(messages);

        return gson.toJson(fulfillment);
    }
}

* こんな感じで音声データが返されます。
fb-mess.png

参考

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5