Easy to make Slack Bot in Java

Introducing an easy way to create SlackBot in Java

The complete source code I introduced can be found at https://github.com/riversun/slacklet-examples.git

Get API Token for BOT

First, go here and get the API Token for the BOT https://my.slack.com/services/new/bot

--Once you have decided on a BOT username, click Add bot integration

slack_reg_01.png

--The API Token is now generated. We will make SlackBot using this API Token in the future. slack_reg_02.png

Slack protocol and preparation

The protocol is Websocket-based Slack RTM (Realtime Messaging API), and the library is Simple Slack API. It uses a wrapper library called Slacklet based on -slack-api.git).

Slacklet Slacklet can be obtained from maven / gradle or direct download of jar from the following. maven/gradle Download slacklet.jar directly

Join BOT to the channel

First, invite the BOT you created earlier to join any channel.

ex00_00_join.png

1. 1. Slack bot returning echo

This is a simple example of returning an echo as it is when someone speaks.

Example00.java



public class Example00 {

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

		String botToken ="Obtained API Token" ;

		SlackletService slackService = new SlackletService(botToken);

		//Add slacklet
		slackService.addSlacklet(new Slacklet() {

			@Override
			public void onMessagePosted(SlackletRequest req, SlackletResponse resp) {
				//Message posted by user

				//Get the channel where the message was posted
				SlackChannel channel = req.getChannel();

				if ("random".equals(channel.getName())) {
					// #If it was a random channel

					//Get message body
					String content = req.getContent();

					//Send a message from the BOT to the channel to which the message was posted
					resp.reply("「" + content + "I said.");

				}

			}
		});

		//Launched slacklet service(Connect to slack)
		slackService.start();

	}

}

Source code for this sample

Execution example

If you say "Hello" on the Slack, it will be returned echo from the BOT. ex00_01.png

Description

Create ** SlackletService ** as above and add ** Slacklet ** with ** # addSlacklet **. ** Slacklet ** is like ** Servlet **, overriding the required methods.

** # onMessagePosted ** is called when a user posts a message to a channel. If you want to reply by limiting the channel, identify the channel name and reply as in the above example.

2. Receive Direct Message

Override ** Slacklet # onDirectMessagePosted ** if you want to receive direct messages posted to the BOT by the user:

@Override
public void onDirectMessagePosted(SlackletRequest req, SlackletResponse resp) {
	//A direct message addressed to BOT was posted

	String content = req.getContent();

	//Get mention of the user who sent the message
	String mention = req.getUserDisp();

	//Reply to the user who sent the direct message
	resp.reply(mention + "Thank you for your direct message.\n「" + content + "I said");
}

Source code for this sample

Execution example

If you send a direct message to the BOT as shown below, you will receive a reply.

ex01_00.png

3. 3. Reacts only when @mentioned

Message user Mention the BOT, for example, if you want to receive a ** "@ smilebot Hello" ** and posted a message will override the ** Slacklet # onMentionedMessagePosted ** as follows:

@Override
public void onMentionedMessagePosted(SlackletRequest req, SlackletResponse resp) {
	//A message with a mention to this BOT was posted on a channel(Example "@smilebot Good morning ")

	String content = req.getContent();

	String mention = req.getUserDisp();
	resp.reply("Hello," + mention + "Mr. "" + content + "I said.");
}

Source code for this sample

Execution example

You will receive a reply only when you mention the BOT by specifying the BOT name with ** @username **.

ex01_01_mentioned.png

4. Send a direct message to the user

This is an example of sending a direct message from a BOT to a user. Use this when you want to send a message first from the BOT instead of replying to a message from the user.


public class Example02 {

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

		String botToken ="Obtained API Token"; 

		SlackletService slackService = new SlackletService(botToken);
		slackService.start();

		//Send a direct message (not a reply) to the user
		String userName = "riversun";
		slackService.sendDirectMessageTo(userName, "Hello ~");

		//End connection with slack
		slackService.stop();

	}

}

Source code for this sample

Execution example

When executed, you will receive a direct message from the BOT like this.

ex02_00_direct_left.png

ex02_01_direct.png

5. Send a message to the specified channel

public class Example03 {

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

		String botToken = ResourceBundle.getBundle("credentials").getString("slack.bot_api_token");

		SlackletService slackService = new SlackletService(botToken);
		slackService.start();

		//Send a message (not a reply) to a channel
		String channelName = "random";
		slackService.sendMessageTo(channelName, "random channel of everybody, Hello!");

		slackService.stop();

	}

}

Source code for this sample

Execution example

The BOT sends a message to the ** # random ** channel. ex03.png

6. Use session functionality (user-specific context)

Slacklet is designed with multi-user in mind. Allows one user to interact with the BOT while the other user interacts independently. To achieve this, there is a session function to hold various states for each user. Like servlet, ** SlackletRequest .getSession ** gets the session and holds the state in it.


@Override
public void onDirectMessagePosted(SlackletRequest req, SlackletResponse resp) {

	String content = req.getContent();

	//Get a session (session is unique to each user)
	SlackletSession session = req.getSession();

	//Get an integer for counting the number of remarks from the session. If nothing is entered yet, the default value is 1.
	Integer num = (Integer) session.getAttribute("num", 1);

	resp.reply(req.getUserDisp() + "Is" + num + "The second time "" + content + "I said.");

	//Increment the number of times to update the session
	num++;
	session.setAttribute("num", num);

}

Source code for this sample

Execution example

It looks like the conversation is ongoing because it remembers the number of conversations in the session. It is stored uniquely for each user. ex04.png

Expansion tips

[** Session persistence **] When implementing a full-fledged dialogue, you definitely need a ** context **. ** Context ** contains the conversation status, various statuses, etc.

The default implementation of Slacklet keeps the session on-memory and you forget it when you exit the program. If you want to persist the session, implement SletPersistManager including the persistence code. Then, set it with ** SlackletService # setSessionPersistenceManager **.

[** Multi-user support **] Each user is processed in a separate thread so that interactions with multiple users can be processed at the same time, but I think it is better to adjust the size of the executor and thread pool as appropriate according to the number of users handled by the BOT.

[** Display log **] Output the log to stderr as follows

org.riversun.xternal.log.Logger.setEnabled(true);

[** Deeper expansion **] Below Slacklet is an extension of the Simple Slack API. If you want to extend it deeper, you can refer to Simple Slack API.

Recommended Posts

Easy to make Slack Bot in Java
Easy to make LINE BOT with Java Servlet
How to make a Discord bot (Java)
Make Blackjack in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
Java --How to make JTable
Refactoring: Make Blackjack in Java
I tried to make a login function in Java
Easy way to check method / field list in Java REPL
I just wanted to make a Reactive Property in Java
I tried to make a client of RESAS-API in Java
Multithreaded to fit in [Java] template
How to make a Java container
SpringBoot + Redis Easy to make demo
How to learn JAVA in 7 days
Log output to file in Java
How to use classes in Java?
How to name variables in Java
Try to implement Yubaba in Java
How to make a Java array
How to concatenate strings in java
Easy to make LINE BOT with Java Servlet Part 2: I tried image messages and templates
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
Java reference to understand in the figure
Try to implement n-ary addition in Java
How to do base conversion in Java
Change List <Optional <T >> to Optional <List <T >> in Java
Convert SVG files to PNG files in Java
How to implement coding conventions in Java
How to embed Janus Graph in Java
[Java] Beginners want to make dating. 1st
Post to Slack from Play Framework 2.8 (Java)
How to get the date in java
Do TensorFlow in Java. It's easy, though. .. .. ..
Add footnotes to Word documents in Java
Let's migrate to make Java more comfortable
[Java Bronze] 5 problems to keep in mind
Easy to trip with Java regular expressions
Sample to unzip gz file in Java
Java to C and C to Java in Android Studio
Add SameSite attribute to cookie in Java
I tried to make a talk application in Java using AI "A3RT"
Two ways to start a thread in Java + @
I tried to make Basic authentication with Java
Partization in Java
I want to send an email in Java.
How to display a web page in Java
CORBA seems to be removed in Java SE 11. .. ..
Code to escape a JSON string in Java
I did Java to make (a == 1 && a == 2 && a == 3) always true
Try to create a bulletin board in Java
Changes in Java 11
Increment behavior Try to make Java problem TypeScript 3-4
I tried to implement deep learning in Java
Rock-paper-scissors in Java
How to get Class from Element in Java
There seems to be no else-if in java
String operation Try to make Java problem TypeScript 9-3
rsync4j --I want to touch rsync in Java.