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
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
--The API Token is now generated. We will make SlackBot using this API Token in the future.
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
First, invite the BOT you created earlier to join any channel.
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();
}
}
If you say "Hello" on the Slack, it will be returned echo from the BOT.
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.
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");
}
If you send a direct message to the BOT as shown below, you will receive a reply.
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.");
}
You will receive a reply only when you mention the BOT by specifying the BOT name with ** @username **.
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();
}
}
When executed, you will receive a direct message from the BOT like this.
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();
}
}
The BOT sends a message to the ** # random ** channel.
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);
}
It looks like the conversation is ongoing because it remembers the number of conversations in the session. It is stored uniquely for each user.
[** 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