Search code examples
javaspring-bootactions-on-google

How to create actions on google using Spring Boot & Java Library


I am trying to create actions on google using Spring Boot & Dialogflow. In which I was trying to use the available java library https://github.com/actions-on-google/actions-on-google-java

But couldn't understand how should I implement these annotations in my Spring Boot Application. Eg: @ForIntent

I have tried the boilerplate code with App Engine entry point https://github.com/actions-on-google/dialogflow-webhook-boilerplate-java I was able to run this code, but couldn't understand its implementation in Spring boot Application.

In Spring Boot: We use @RestController in the application to map the requests

But with actions on google there would be only one request link, we can provide as Fulfillment webhook. So where should I use the @ForIntent in my code to identify the Intent and change Request body & Response body.


Solution

  • I actually did this at one point, and based it off of the Silly Name Maker sample. I based it on one of the Spring Boot canonical samples, so I'm not going to guarantee this is 'optimal', but it's a pretty clean implementation.

    You can keep the SillyNameMakerApp the same, unmodified. Instead of the ActionsServlet, you can create a Spring Boot wrapper like this:

    @SpringBootApplication
    public class HelloworldApplication {
        private static final Logger LOG = LoggerFactory.getLogger(SillyNameMakerApp.class);
        private final App actionsApp = new SillyNameMakerApp();
    
        @Value("${TARGET:World}")
        String message;
    
        @RestController
        class HelloworldController {
            @GetMapping("/")
            String serveAck() {
                return "App is listening but requires valid POST request to respond with Action response.";
            }
    
            @RequestMapping(value = "/", method = RequestMethod.POST, produces = { "application/json" })
            String serveAction(@RequestBody String body, @RequestHeader Map<String, String> headers) {
                try {
                    return actionsApp.handleRequest(body, headers).get();
                } catch (InterruptedException | ExecutionException e) {
                    return handleError(e);
                }
            }
    
            private String handleError(Exception e) {
                e.printStackTrace();
                LOG.error("Error in App.handleRequest ", e);
                return "Error handling the intent - " + e.getMessage();
            }
        }
    
        public static void main(String[] args) {
            SpringApplication.run(HelloworldApplication.class, args);
        }
    }