Interact with LINE Message API using Lambda (Java)

Service used

Development environment, etc.

Purpose

What I have omitted in this article

procedure

  1. LINE Message API

  2. Open an account

  3. Webhook URL setting

  4. AWS API Gateway

  5. Resource creation

  6. Link the created resource with the Lambda Function

  7. Lambda Function

3.1. Create Input class to receive JSON by POJO 3.2. Create Output class 3.3. Get replyToken and text from Input and store in Output. In addition, the information required for Reply Message is also set. 3.4. Convert Output to JSON 3.5. Generate and send a request 3.6. Whole code

3.1. Create Input class to receive JSON by POJO

Since the following JSON object is sent, the Input class is also constructed accordingly.

{
  "events": [
    {
      "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
      "type": "message",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U206d25c2ea6bd87c17655609a1c37cb8"
      },
      "message": {
        "id": "325708",
        "type": "text",
        "text": "Hello, world"
      }
    },
    {
      "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
      "type": "follow",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U206d25c2ea6bd87c17655609a1c37cb8"
      }
    }
  ]
}

Input.java


package jp.linebot;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Input {
	
	private Events[] events;
	
}

Events.java


package jp.linebot;

import org.joda.time.DateTime;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Events {
	private String replyToken;
	private String type;
	private Long timestamp;
	private Source source;
	private Message message;	
}

Source.java


package jp.linebot;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Source {
	private String type;
	private String userId;
}

Message.java


package jp.linebot;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {
	private String id;
	private String type;
	private String text;	
}

3.2. Create Output class

Output.java


package jp.linebot;

import java.util.ArrayList;
import java.util.List;

import lombok.Data;

@Data
public class Output {

	private String replyToken;
	private List<Messages> messages = new ArrayList<>();
}

Messages.java


package jp.linebot;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Messages {

	private String type;
	private String text;
}

3.3. Get replyToken and text from Input and store in Output. In addition, the information required for Reply Message is also set.

Output output = new Output();
output.setReplyToken(input.getEvents()[0].getReplyToken());
Messages outMessage = new Messages();
outMessage.setType("text");
outMessage.setText(input.getEvents()[0].getMessage().getText() + "?");
output.getMessages().add(outMessage);

3.4. Convert Output to JSON

Gson gson = new Gson();
context.getLogger().log(gson.toJson(output));

3.5. Generate and send a request

httpPost = new HttpPost("https://api.line.me/v2/bot/message/reply");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + "{Channel Access Token}");
StringEntity entity = new StringEntity(gson.toJson(output), StandardCharsets.UTF_8);
httpPost.setEntity(entity);

try (CloseableHttpClient client = HttpClients.createDefault();
     CloseableHttpResponse resp = client.execute(httpPost);
     BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent(), StandardCharsets.UTF_8)))
{
        int statusCode = resp.getStatusLine().getStatusCode();
        switch (statusCode) {
        case 200:
            br.readLine();
            break;
        default:
        }
    } catch (final ClientProtocolException e) {
    } catch (final IOException e) {
}
return null;

3.6. Whole code

LambdaFunctionHandler.java


package jp.linebot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.google.gson.Gson;

public class LambdaFunctionHandler implements RequestHandler<Input, Object> {

	@Override
	public Object handleRequest(Input input, Context context) {
		// TODO Auto-generated method stub

		context.getLogger().log("token : " + input.getEvents()[0].getReplyToken());
		context.getLogger().log("text : " + input.getEvents()[0].getMessage().getText());
		
		Output output = new Output();
		output.setReplyToken(input.getEvents()[0].getReplyToken());
		Messages outMessage = new Messages();
		outMessage.setType("text");
		outMessage.setText(input.getEvents()[0].getMessage().getText() + "?");
		output.getMessages().add(outMessage);

		HttpPost httpPost = new HttpPost("https://api.line.me/v2/bot/message/reply");
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setHeader("Authorization", "Bearer " + "{Channel Access Token}");

		Gson gson = new Gson();
		context.getLogger().log(gson.toJson(output));
		StringEntity entity = new StringEntity(gson.toJson(output), StandardCharsets.UTF_8);
		httpPost.setEntity(entity);
		try (CloseableHttpClient client = HttpClients.createDefault();
                CloseableHttpResponse resp = client.execute(httpPost);
                BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent(), StandardCharsets.UTF_8)))
        {
            int statusCode = resp.getStatusLine().getStatusCode();
            switch (statusCode) {
            case 200:
                br.readLine();
                break;
            default:
            }
        } catch (final ClientProtocolException e) {
        } catch (final IOException e) {
        }
		return null;
	}
	
}

Reference link

Recommended Posts

Interact with LINE Message API using Lambda (Java)
How to use Java API with lambda expression
Use Lambda Layers with Java
Using Mapper with Java (Spring)
Handle exceptions coolly with Java 8 lambda expressions and Stream API
Create a SlackBot with AWS lambda & API Gateway in Java
Java lambda expressions learned with Comparator
Export issues using JIRA's Java API
Try using Redis with Java (jar)
I tried to interact with Java
I tried using Java8 Stream API
Using Java with AWS Lambda-Eclipse Preparation
Html5 development with Java using TeaVM
[Java] LINE integration with Spring Boot
Getting started with Java lambda expressions
Using proxy service with Java crawling
Sample of using Salesforce's Bulk API from Java client with PK-chunking
I tried using Elasticsearch API in Java
Make Ruby Kurosawa with Ruby (Ruby + LINE Messaging API)
Using Java with AWS Lambda-Implementation-Check CloudWatch Arguments
Implement API Gateway Lambda Authorizer in Java Lambda
Data processing using stream API from Java 8
API integration from Java with Jersey Client
Using Java with AWS Lambda-Implementation-Stop / Launch EC2
Try using the Stream API in Java
Using JupyterLab + Java with WSL on Windows 10
Nowadays Java lambda expressions and Stream API
Try using JSON format API in Java
AWS Lambda with Java starting now Part 1
Game development with two people using java 2
I tried using OpenCV with Java + Tomcat
Game development with two people using java 1
When calling API with java, javax.net.ssl.SSLHandshakeException occurs
Working with huge JSON in Java Lambda
Game development with two people using java 3
Try using the Wii remote with Java
Create API using Retrofit2, Okhttp3 and Gson (Java)
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse
How to use Java framework with AWS Lambda! ??
Specify ClassPath when using jupyter + Java with WSL
Try using GCP's Cloud Vision API in Java
Make Java Stream line breaks nice with eclipse
Using Gradle with VS Code, build Java → run
[Java] Get images with Google Custom Search API
Docker Container Operations with Docker-Client API for Java
Easy to make LINE BOT with Java Servlet
Try using the COTOHA API parsing in Java
[Java] How to operate List using Stream API
Java Stream API
Hello Java Lambda
[Java] Lambda expression
Java lambda expression
Using Java 8 with Bluemix (on Liberty Runtime & DevOps Service)
Getting started with Java programs using Visual Studio Code
How to deploy Java to AWS Lambda with Serverless Framework
[Java] Sort the list using streams and lambda expressions
I tried using Google Cloud Vision API in Java
Use Java lambda expressions outside of the Stream API
Create two or more line graphs using MPAndroidChart [Java]
Implement API client with only annotations using Feign (OpenFeign)