Introduction
The currently supported version is Python2. You have to follow the Python2 syntax while writing the code.
The following libraries are already imported to help you implement various use-cases:
This document contains the following:
- Examples
- Use existing properties & set new properties
- Send message
- Make API call & send message
- Importing python's internal libs
- Parse Rest API block response
- How to write code using any IDE.
1. Examples
Please follow the examples below to learn how to write code for different use-cases. You can also find all the below-mentioned example codes here.
1.1 Use existing properties
Use existing properties to get the current context of the conversation like the user's first name, etc.
package com.altin.custom_code; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import morph.base.actions.StringVariable; import morph.base.actions.impl.SetVariableAction; import morph.base.beans.CustomCodeResponse; import java.util.Collections; import java.util.Map; // Please don't change the class name 'MorphCustomCode' public class MorphCustomCode implements RequestHandler<Map<String, Object>, CustomCodeResponse> { @Override public CustomCodeResponse handleRequest(Map<String, Object> input, Context context) { CustomCodeResponse customCodeResponse = new CustomCodeResponse(); // Write your code here. Please refer to the docs to learn more - https://morphdesk.freshdesk.com/en/support/solutions/articles/60000664433 //Access exiting properties like this: Map<String, Object> userVariables = (Map<String, Object>) input.get("userVariables"); String firstName = String.valueOf(userVariables.get("First Name")); //Set property SetVariableAction setFirstNameCapsA = new SetVariableAction(); setFirstNameCapsA.setVariableTitle("First Name Caps"); setFirstNameCapsA.setVariable(new StringVariable().value(firstName.toUpperCase())); //Set action in response customCodeResponse.setActions(Collections.singletonList(setFirstNameCapsA)); return customCodeResponse; } }
1.2 Send Message
package com.altin.custom_code; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import morph.base.actions.impl.PublishMessageAction; import morph.base.beans.CustomCodeResponse; import morph.base.beans.simplifiedmessage.SimplifiedMessage; import morph.base.beans.simplifiedmessage.SimplifiedMessagePayload; import morph.base.beans.simplifiedmessage.TextMessagePayload; import java.util.Collections; import java.util.Map; // Please don't change the class name 'MorphCustomCode' public class MorphCustomCode implements RequestHandler<Map<String, Object>, CustomCodeResponse> { @Override public CustomCodeResponse handleRequest(Map<String, Object> input, Context context) { CustomCodeResponse customCodeResponse = new CustomCodeResponse(); // Write your code here. Please refer to the docs to learn more - https://morphdesk.freshdesk.com/en/support/solutions/articles/60000664433 // Access exiting properties like this: Map<String, Object> userVariables = (Map<String, Object>) input.get("userVariables"); String firstName = String.valueOf(userVariables.get("First Name")); // Create message SimplifiedMessagePayload textMessagePayload = new TextMessagePayload() .text("Hello " + firstName + ", how can I help you?"); SimplifiedMessage messageData = new SimplifiedMessage(); messageData.setMessages(Collections.singletonList(textMessagePayload)); // Send message PublishMessageAction publishMessageAction = new PublishMessageAction(); publishMessageAction.setSimplifiedMessage(messageData); // Set action in response customCodeResponse.setActions(Collections.singletonList(publishMessageAction)); return customCodeResponse; } }
1.3 Make API call & send message
package com.altin.custom_code; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import morph.base.actions.impl.PublishMessageAction; import morph.base.beans.CustomCodeResponse; import morph.base.beans.simplifiedmessage.SimplifiedMessage; import morph.base.beans.simplifiedmessage.SimplifiedMessagePayload; import morph.base.beans.simplifiedmessage.TextMessagePayload; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.jackson.JacksonFeature; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import java.util.Collections; import java.util.Map; // Please don't change the class name 'MorphCustomCode' public class MorphCustomCode implements RequestHandler<Map<String, Object>, CustomCodeResponse> { final static Client HTTP_CLIENT = ClientBuilder.newBuilder() .withConfig(new ClientConfig().property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)) .register(JacksonFeature.class).build(); @Override public CustomCodeResponse handleRequest(Map<String, Object> input, Context context) { CustomCodeResponse customCodeResponse = new CustomCodeResponse(); // Write your code here. Please refer to the docs to learn more - https://morphdesk.freshdesk.com/en/support/solutions/articles/60000664433 try { // Call API WebTarget target = HTTP_CLIENT .target("http://180.149.246.197/RoxyCinemasWebServ/api/service/GetNowShowing?cinemaid=&userid=0" + "&platform=4&Flag=home"); Invocation.Builder builder = target.request(); Response response = builder.get(); JsonNode jsonNode = response.readEntity(JsonNode.class); // Create message StringBuilder message = new StringBuilder("Hello, please select the movie from below.\n\n"); ArrayNode nowShowingList = (ArrayNode) jsonNode.get("nowShowingList"); for (int i = 0; i < nowShowingList.size(); i++) { JsonNode show = nowShowingList.get(i); message.append(i).append(". ").append(show.get("'Title'").asText()).append("\n"); } SimplifiedMessagePayload textMessagePayload = new TextMessagePayload().text(message.toString()); SimplifiedMessage messageData = new SimplifiedMessage(); messageData.setMessages(Collections.singletonList(textMessagePayload)); // Send message PublishMessageAction publishMessageAction = new PublishMessageAction(); publishMessageAction.setSimplifiedMessage(messageData); // Set action in response customCodeResponse.setActions(Collections.singletonList(publishMessageAction)); } catch (Exception e) { // } return customCodeResponse; } }
1.4 Importing standard python library
Any python's standard library can be imported. For eg. in the below code, we will be using random lib.
package com.altin.custom_code; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import morph.base.actions.StringVariable; import morph.base.actions.impl.SetVariableAction; import morph.base.beans.CustomCodeResponse; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; // Please don't change the class name 'MorphCustomCode' public class MorphCustomCode implements RequestHandler<Map<String, Object>, CustomCodeResponse> { @Override public CustomCodeResponse handleRequest(Map<String, Object> input, Context context) { CustomCodeResponse customCodeResponse = new CustomCodeResponse(); // Write your code here. Please refer to the docs to learn more - https://morphdesk.freshdesk.com/en/support/solutions/articles/60000664433 List<String> givenList = Arrays .asList("Dolittle", "The Gentlemen", "Birds of Prey", "The Lovebirds", "Mulan", "The Beatles: Get Back", "The King’s Man", "Black Widow"); // Randomly select a movie Random rand = new Random(); String randomMovieName = givenList.get(rand.nextInt(givenList.size())); //Set property SetVariableAction setMovieNameA = new SetVariableAction(); setMovieNameA.setVariableTitle("Movie Name"); setMovieNameA.setVariable(new StringVariable().value(randomMovieName)); //Set action in response customCodeResponse.setActions(Collections.singletonList(setMovieNameA)); return customCodeResponse; } }
1.5 Parse Rest API block response
Sometimes, we use the Rest API block to make an API call but we want to write the code to parse the response.
This is a similar example where we made an API (using Rest API block) call to fetch employee detail and we want to parse the result to find the name of the employee. We used a dummy API, which gives the following response:
{ "status": "success", "data": { "id": "2", "employee_name": "Garrett Winters", "employee_salary": "170750", "employee_age": "63", "profile_image": "" } }
Now, let's write the code to parse this response.
package com.altin.custom_code; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import morph.base.actions.StringVariable; import morph.base.actions.impl.SetVariableAction; import morph.base.beans.CustomCodeResponse; import java.io.IOException; import java.util.Collections; import java.util.Map; // Please don'o't change the class name 'MorphCustomCode' public class MorphCustomCode implements RequestHandler<Map<String, Object>, CustomCodeResponse> { @Override public CustomCodeResponse handleRequest(Map<String, Object> input, Context context) { CustomCodeResponse customCodeResponse = new CustomCodeResponse(); // Write your code here. Please refer to the docs to learn more - https://morphdesk.freshdesk.com/en/support/solutions/articles/60000664433 // Access Rest API block response Map<String, Object> flowVariables = (Map<String, Object>) input.get("flowVariables"); String apiResponse = String.valueOf(flowVariables.get("API Response")); try { // Parse response ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readValue(apiResponse, JsonNode.class); // Use the response JsonNode data = jsonNode.get("data"); String employeeName = data.get("employee_name").asText(); // Set property SetVariableAction setEmployeeNameA = new SetVariableAction(); setEmployeeNameA.setVariableTitle("Name"); setEmployeeNameA.setVariable(new StringVariable().value(employeeName)); //Set action in response customCodeResponse.setActions(Collections.singletonList(setEmployeeNameA)); } catch (IOException e) { // } return customCodeResponse; } }
How to write code using any IDE
You can write the code using the default Code block editor, but if needed you can write the code in your own IDE too. To do the same you need to install Morph.ai's code python SDK. Please follow the steps below to do the same:
Gradle
repositories { ..... maven { url "http://104.155.191.79:8081/nexus/content/repositories/thirdparty" ..... } ....... ...... compile group: 'com.altin', name: 'custom-code', version: '1.0.4'
Maven
... <repositories> ... ... <repository> <id>morph</id> <name>morph</name> <url>http://104.155.191.79:8081/nexus/content/repositories/thirdparty</url> </repository> ... ... </repositories> ... ... ... <dependency> <groupId>com.altin</groupId> <artifactId>custom-code</artifactId> <version>1.0.4</version> </dependency> ... ...