Easy to make LINE BOT with Java Servlet

I will introduce how to easily create LINE BOT using Java Servlet. The complete source code I introduced can be found at https://github.com/riversun/line-bot-servlet-examples.git

Preparing to make a LINE BOT

I will write on the assumption that the Messaging API can be used. I will leave the registration method etc. to another article.

Registration is here https://business.line.me/ja/services/bot

Create a LINE BOT with Servlet

Create a LINE BOT with ** HttpServlet **.

LINE official Github (https://github.com/line/line-bot-sdk-java) introduces an example of using Spring Boot (*).

This time, I would like to make a LINE BOT with ** Suppin's HttpServlet ** instead of Spring Boot.

As you know, using Spring Boot makes it quite easy to create a LINE BOT, ** HttpServlet ** aims to be as easy as the Spring Boot example.

For that purpose, we have prepared a helper library. Even though it is a library, it is a thin wrapper that uses https://github.com/line/line-bot-sdk-java internally, so I think you can use it by incorporating the source into your own Servlet. .. The method name is also based on the Spring Boot example.

** Click here for helper library source ** https://github.com/riversun/line-bot-helper

_ * The official SDK (currently v1.6.0) also has a line-bot-servlet. Looking at the contents, it seems that a simple helper class (signature verification etc.) for HttpServlet is prepared. It seems that event mapping like Spring Boot will not be done. _

Create a reply BOT to the message

This is a sample in which when a user sends a text message to a BOT, the BOT responds in text.

The code looks like this:

LineBotExample01Servlet.java


@SuppressWarnings("serial")
public class LineBotExample01Servlet extends LineBotServlet {

	// CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN can be specified as a character string as it is
	private static final String CHANNEL_SECRET ="Put what you got" ;
	private static final String CHANNEL_ACCESS_TOKEN ="Put what you got";
	@Override
	protected ReplyMessage handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws IOException {

		//Messages sent by users to BOT
		TextMessageContent userMessage = event.getMessage();

		//Get the user's profile
		UserProfileResponse userProfile = getUserProfile(event.getSource().getUserId());

		//Reply message from BOT
		String botResponseText = userProfile.getDisplayName() + "Mr."
				+ "「" + userMessage.getText() + "I said";

		TextMessage textMessage = new TextMessage(botResponseText);

		return new ReplyMessage(event.getReplyToken(), Arrays.asList(textMessage));
	}

	@Override
	protected ReplyMessage handleDefaultMessageEvent(Event event) {
		//Do nothing if you receive a message that is not overridden(Returns null)
		return null;
	}

	@Override
	public String getChannelSecret() {
		return CHANNEL_SECRET;
	}

	@Override
	public String getChannelAccessToken() {
		return CHANNEL_ACCESS_TOKEN;
	}

Operation image

line_bot_small.png

Commentary

When you receive a text message from a user

ReplyMessage handleTextMessageEvent(MessageEvent<TextMessageContent> event)

Will be called, so do the necessary processing in this method. In this example, the user's remark (text) is acquired, processed a little, and replied.

If you return a ReplyMessage as shown below, the reply will be sent to the user.

return new ReplyMessage(event.getReplyToken(), Arrays.asList(textMessage));

Here

return null;

If set to, no reply will be sent.

By the way,

Arrays.asList(textMessage)

The reason for this is that multiple messages can be returned at the same time. For example, if you want to return an image and text at the same time,

Arrays.asList(imageMessage,textMessage)

To do.

In this example, handleTextMessageEvent was overridden, but you can also receive each event by overriding the following methods.

protected ReplyMessage handleImageMessageEvent(MessageEvent<ImageMessageContent> event)
protected ReplyMessage handleLocationMessageEvent(MessageEvent<LocationMessageContent> event)  
protected ReplyMessage handleStickerMessageEvent(MessageEvent<StickerMessageContent> event)  
protected ReplyMessage handleAudioMessageEvent(MessageEvent<AudioMessageContent> event)  
protected ReplyMessage handleVideoMessageEvent(MessageEvent<VideoMessageContent> event)  
protected void handleUnfollowEvent(UnfollowEvent event) 
protected ReplyMessage handleFollowEvent(FollowEvent event) 
protected ReplyMessage handleJoinEvent(JoinEvent event) 
protected void handleLeaveEvent(LeaveEvent event) 
protected ReplyMessage handlePostbackEvent(PostbackEvent event) 
protected ReplyMessage handleBeaconEvent(BeaconEvent event) 

Finally,


@Override
    protected ReplyMessage handleDefaultMessageEvent(Event event) {
        //Do nothing if you receive a message that is not overridden(Returns null)
        return null;
    }

However, it is called when an event that is not overridden is received.

In order to include the helper library that includes the above ** LineBotServlet **, in Gradle / Maven, specify as follows.

Gradle compile 'org.riversun:line-bot-helper:1.0.0'

Maven

<dependency>
	<groupId>org.riversun</groupId>
	<artifactId>line-bot-helper</artifactId>
	<version>1.0.0</version>
</dependency>

Easy to try on your local PC

The purpose of this article is to create a Servlet, but as a bonus, I will also write about how to try it on a local PC.

It's been a lot easier to create a Servlet, but it's still weak if you can try it right away.

It is troublesome to start and deploy Tomcat etc., so let's use the container ** Jetty ** that allows you to easily try servlets.

Jetty is very easy to use.

First, add the following to Gradle / Maven.

Gradle compile 'org.eclipse.jetty:jetty-server:9.4.0.v20161208' compile 'org.eclipse.jetty:jetty-webapp:9.4.0.v20161208'

Maven


<dependency>
	<groupId>org.eclipse.jetty</groupId>
	<artifactId>jetty-server</artifactId>
	<version>9.4.0.v20161208</version>
</dependency>
<dependency>
	<groupId>org.eclipse.jetty</groupId>
	<artifactId>jetty-webapp</artifactId>
	<version>9.4.0.v20161208</version>
</dependency>

Start Jetty and access servlet

After writing in Gradle / Maven, write and execute the code as follows.

AppMain.java


public class AppMain {

	public static void main(String[] args) throws Exception {

		ServletHandler handler = new ServletHandler();

		handler.addServletWithMapping(LineBotExample01Servlet.class, "/callback");

		// loclahost:Launch Jetty at 3000
		Server jetty = new Server(3000);

		jetty.setHandler(handler);
		jetty.start();
		jetty.join();

	}

}

handler.addServletWithMapping(LineBotExample01Servlet.class, "/callback");

As shown in, accept the ** LineBotExample01Servlet ** created earlier with the path ** / callback **.

If you run it on your local PC, you will be able to access the LINE BOT Servlet at http://127.0.0.1:3000/callback.

Make the created LINE BOT Servlet accessible from the outside

Even if you launch it locally, you need to deploy it to the server and publish it to the outside in order to behave as a LINE BOT. Let's make the server created using Jetty accessible from the outside so that you can easily try it for testing purposes.

Here, we use a service called ngrok that is perfect for this purpose.

Download ngrok from the following https://ngrok.com/download

At the command line ngrok http -region=ap 127.0.0.1:3000

Then ngrok will start and the following screen will be displayed ngrok.png

With just this The url https://xxxxx.ap.ngrok.io has been mapped to https://127.0.0.1:3000!

_ (The xxxxx part changes randomly every time you start ngrok. You can fix it by signing up) _

This is convenient because https is required for the web hook url of LINE BOT.

At this point, all you have to do is register the following url in the Web Hook URL. https://xxxxx.ap.ngrok.io/callback

** ngrok tips ** If you specify **-region = ap **, the Asia Pacific region will be selected. Accessing from Japan has a latency advantage over the default US region.

I will do it

When you enter a message from the LINE app on your smartphone line_bot_small.png

It went well

Summary

--This time, I introduced an example of creating a simple LINE BOT with HttpServlet. --By hosting Servlet with Jetty and making it accessible from the outside using ngrok, we were able to test actually send a message from the LINE app on the smartphone to the BOT. --The complete source code introduced can be found at https://github.com/riversun/line-bot-servlet-examples.git

Next time would like to try an example of increasing the materials to be handled a little more, such as sending and receiving images.

Recommended Posts

Easy to make LINE BOT with Java Servlet
Easy to make LINE BOT with Java Servlet Part 2: I tried image messages and templates
Easy to make Slack Bot in Java
How to make a Discord bot (Java)
Easy to trip with Java regular expressions
I tried to make Basic authentication with Java
Make Java Stream line breaks nice with eclipse
How to make LINE messaging function made with Ruby
Let's make a LINE Bot with Ruby + Sinatra --Part 2
Let's make a LINE Bot with Ruby + Sinatra --Part 1
I used to make nc (netcat) with JAVA normally
[Java] How to start a new line with StringBuilder
Easy BDD with (Java) Spectrum?
Java to play with Function
Java --How to make JTable
Connect to DB with Java
Connect to MySQL 8 with Java
[Beginner] Try to make a simple RPG game with Java ①
Volume 1 of wanting to make your favorite SCANDAL LINE bot
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Java to learn with ramen [Part 1]
[Java] Points to note with Arrays.asList ()
How to make a Java container
SpringBoot + Redis Easy to make demo
Dare to challenge Kaggle with Java (1)
I tried to interact with Java
[Java] LINE integration with Spring Boot
Java, arrays to start with beginners
Easy database access with Java Sql2o
How to make a Java array
I want to make a button with a line break with link_to [Note]
I tried to make an Android application with MVC now (Java)
Interface Try to make Java problem TypeScript 7-3
How to make a Java calendar Summary
[Java] How to compare with equals method
Make something like Java Enum with Typescript
Introduction to algorithms with java --Search (depth-first search)
[Swift] Easy to implement modal with PanModal
[Java] Beginners want to make dating. 1st
Java: How to send values from Servlet to Servlet
[Java] Make programs 10x faster with parallelStream
line bot
[LINE BOT] I made a ramen BOT with Java (Maven) + Heroku + Spring Boot (1)
How to make an app with a plugin mechanism [C # and Java]
Introduction to algorithms with java --Search (breadth-first search)
[LINE @] I tried to make a Japanese calendar Western calendar conversion BOT [Messaging API]
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
Hello World with Java Servlet and JSP (Easy web server startup with Maven + Jetty)
Challenge to deal with garbled characters with Java AudioSystem.getMixerInfo ()
Interact with LINE Message API using Lambda (Java)
Make SpringBoot1.5 + Gradle4.4 + Java8 + Docker environment compatible with Java11
Introduction to algorithms with java --Search (bit full search)
Deploy Java web app to Azure with maven
I did Java to make (a == 1 && a == 2 && a == 3) always true
Try to link Ruby and Java with Dapr
How to use Java framework with AWS Lambda! ??
Conversation status (context) management (session management?) With LINE BOT
I want to use java8 forEach with index
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
String operation Try to make Java problem TypeScript 9-3