[JAVA] Return audio data with api.ai webhook

Overview

Implementation

It's not like *, but if you want to return audio data, for example, we will implement the following json return.

fulfillment


"fulfillment": {
      "messages": [
        {
          "payload": {
            "facebook": {
              "attachment": {
                "payload": {
                  "url": "https://hogehoge/audio/description.mp3"
                },
                "type": "audio"
              }
            }
          },
          "type": 4
        }
      ]
    }

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();
	}
}

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);
	}
}

reference

Recommended Posts

Return audio data with api.ai webhook
Return partial template (partial) with helper