Over a million developers have joined DZone.

Make Slack Bots in Java in Minutes

Read up on BotKit — a framework on GitHub that lets you make your own cloud-ready Slack bot in mere moments.

· Integration Zone

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA Technologies.

Welcome to BotKit Framework — LEGO for building bots.

BotKit is a Java application (inspired by Howdyai's Botkit) to make Slack (Facebook and Twitter coming soon) bots in minutes. It provides all the boilerplate code needed so that you can make your bot live right away.

You can start talking with your bot in just four easy steps:

  1. Clone this project $ git clone git@github.com:ramswaroop/botkit.git and $ cd botkit.
  2. Create a Slack bot and get your Slack token.
  3. Paste the token in application.properties file.
  4. Run the application by running BotKitApplication in your IDE or via command line $ mvn spring-boot:run.

That's it.

Why Use Botkit for Slack?

  • Provides you with all the boilerplate code which handles underlying websocket connections and other complexities.
  • Supports a few extra events in addition to all the events supported by Slack RTM API, which makes your work a lot easier.
  • Receiving and sending messages is as easy as defining a controller method and calling reply(), you don't need to manually parse any events nor manually encode any messages before sending.
  • The conversation feature of Botkit makes talking to your bot a breeze.
  • Well-tested with unit tests.

Basic Usage

The main function of a bot is to receive and reply messages. With this kit, receiving messages is as easy as just writing a simple controller and replying to it by calling the reply() method as shown below:


@Controller(events = EventType.MESSAGE)
public void onReceiveDM(WebSocketSession session, Event event) {
    reply(session, event, new Message("Hi, I am a Slack Bot!"));
}


All the code for your bot goes in the SlackBot class, which extends Bot from the core package. You can have as many bots as you want, just make the class extend Bot class and it gets all the powers of a Slack Bot.

Building a Slack Integration with Botkit

You can integrate your services into Slack by any of the following ways:

And Botkit currently supports:

Bots interact with Slack through RTM API or technically via Web Sockets. Slash Commands are nothing but GET andPOST calls to your app. Finally, Webhooks can be of two types, Incoming and Outgoing. Incoming webhooks is where you POST data from outside (i.e, your app) to Slack, and Outgoing webhooks is where Slack POST data to an endpoint you specify.

Setting up your app

You need to first paste your tokens/URLs in the application.properties file:


slackBotToken=xoxb-50014434-slacktokenx29U9X1bQ
slashCommandToken=X73Fv3tokenx242CdpEq
slackIncomingWebhookUrl=https://hooks.slack.com/services/T02WEBHOOKURLV7oOYvPiHL7y6


The core package contains all of Botkit code. You can create packages outside core package and put your custom code there. To make a

  • Slack Bot ⇒ Extend Bot class.
  • Slash Command Handler ⇒ Annotate your class with Spring's @Controller and have a method with the required @RequestMapping path receiving a set of request params as shown in the sample.
  • Slack Incoming Webhook ⇒ Just make a POST call with RichMessage whenever you want to update your Slack users about something.
  • Slack Outgoing Webhook ⇒ Same as Slash Command Handler.

Receiving Messages

For Bots, you receive a message as Events. For almost all actions, Slack fires a relevant event for it. Unfortunately, it does not fire appropriate events when someone directly messages the bot (direct message) or mentions the bot on a channel (like @bot). It just fires an event of type message for all the messages (directly to bot and to channels where bot is a member) sent.

But guess what, you're at the right place now — BotKit handles that for you. It supports three extra events EventType.DIRECT_MESSAGE, EventType.DIRECT_MENTION, and EventType.ACK in addition to all the currently supported Slack events. The first two events are self-explanatory, but the EventType.ACK event is nothing but an acknowledgement event that acknowledges the delivery of a previously sent message.

To receive and parse slack bot events you just need to have this:


@Controller(events = {EventType.DIRECT_MENTION, EventType.DIRECT_MESSAGE})
public void onReceiveDM(WebSocketSession session, Event event) {
    if (event.getText().contains("hi")) {
        reply(session, event, new Message("Hi, I am " + slackService.getCurrentUser().getName()));
    }
}


What you're doing here is annotating a method with the @Controller annotation and passing an array of events to that annotation that you want to listen to. By default, your controller will listen to EventType.MESSAGE events if you do not specify any events explicitly.

You can also add regular expressions to your @Controller annotation like:


@Controller(events = EventType.MESSAGE, pattern = "([a-zA-Z ]{1,})(\\d+)([a-zA-Z ]{1,})")
public void onReceiveMessage(WebSocketSession session, Event event, Matcher matcher) {
    reply(session, event, new Message("First group: " + matcher.group(0) + "\n" +
            "Second group: " + matcher.group(1) + "\n" +
            "Third group: " + matcher.group(2) + "\n" +
            "Fourth group: " + matcher.group(3)));
}


You can optionally have the matcher as a formal parameter in the method if you want to work on the values sent by the user. But do keep the order of parameters as shown above.

Sending Messages

In Bots, you can use the reply() method defined in the Bot class to send messages to Slack. You just need to set the text you want to send in Message and everything else will be taken care by BotKit. But you can set other fields if you want such as id in the message.

Here is an example:


@Controller(events = EventType.MESSAGE)
public void onReceiveMessage(WebSocketSession session, Event event) {
    reply(session, event, new Message("Hi, this is a message!"));
}


Under the hood, the message sent is nothing but a json like below:

{
    "id": 1,
    "type": "message",
    "channel": "C024BE91L",
    "text": "Hi, this is a message!"
}


NOTE: Event, Message, and RichMessage are generic classes. Not all the time, all the attributes present in them will have values. In other words, Slack sends different responses for different events.

Conversations

This is the most wonderful feature of BotKit — with this, you can literally talk to your bot and have a conversation. See below for an example as to how your bot sets up a meeting for your team by asking some simple questions one after the other.

conversations on slack


    /**
     * Conversation feature of Botkit. This method is the starting point of the conversation (as it
     * calls {@link Bot#startConversation(Event, String)} within it. You can chain methods which will be invoked
     * one after the other leading to a conversation. You can chain methods with {@link Controller#next()} by
     * specifying the method name to chain with.
     *
     * @param session
     * @param event
     */
    @Controller(pattern = "(setup meeting)", next = "confirmTiming")
    public void setupMeeting(WebSocketSession session, Event event) {
        startConversation(event, "confirmTiming");   // start conversation
        reply(session, event, new Message("Cool! At what time (ex. 15:30) do you want me to set up the meeting?"));
    }


You can start a conversation by calling startConversation(event, nextMethodName) within your controller. You can pass the event and the name of the next controller method.


    /**
     * This method is chained with {@link SlackBot#setupMeeting(WebSocketSession, Event)}.
     *
     * @param session
     * @param event
     */
    @Controller(next = "askTimeForMeeting")
    public void confirmTiming(WebSocketSession session, Event event) {
        reply(session, event, new Message("Your meeting is set at " + event.getText() +
                ". Would you like to repeat it tomorrow?"));
        nextConversation(event);    // jump to next question in conversation
    }


This is your next method in the conversation. After your desired work is done, do not forget to call nextConversation(event) to jump to the next method. You can specify the next method to call in next attribute of the Controller annotation.


    /**
     * This method is chained with {@link SlackBot#confirmTiming(WebSocketSession, Event)}.
     *
     * @param session
     * @param event
     */
    @Controller(next = "askWhetherToRepeat")
    public void askTimeForMeeting(WebSocketSession session, Event event) {
        if (event.getText().contains("yes")) {
            reply(session, event, new Message("Okay. Would you like me to set a reminder for you?"));
            nextConversation(event);    // jump to next question in conversation  
        } else {
            reply(session, event, new Message("No problem. You can always schedule one with 'setup meeting' command."));
            stopConversation(event);    // stop conversation only if user says no
        }
    }

    /**
     * This method is chained with {@link SlackBot#askTimeForMeeting(WebSocketSession, Event)}.
     *
     * @param session
     * @param event
     */
    @Controller
    public void askWhetherToRepeat(WebSocketSession session, Event event) {
        if (event.getText().contains("yes")) {
            reply(session, event, new Message("Great! I will remind you tomorrow before the meeting."));
        } else {
            reply(session, event, new Message("Oh! my boss is smart enough to remind himself :)"));
        }
        stopConversation(event);    // stop conversation
    }


To end the conversation, call stopConversation(event) inside your controller method.

NOTE:

  • Only the first method in a conversation can define a pattern. A pattern attribute in theController annotation has no effect for rest of the methods in a conversation.
  • The first method in the conversation doesn't need to call nextConversation(event), but the rest of the methods do need to.

Deploy to the Cloud

BotKit is Heroku-ready. To deploy, you need to perform the below simple steps:

  1. Clone this project $ git clone git@github.com:ramswaroop/botkit.git and $ cd botkit.
  2. Get your Slack bot token or slash command token or incoming webhook URL.
  3. Paste the above tokens/URLs in the application.properties file.
  4. Download Toolbelt for your system.
  5. $ heroku login — Log into Heroku.
  6. $ heroku create — Create an app on Heroku.
  7. $ git push heroku master — Push your code to Heroku.
  8. $ heroku ps:scale web=1 — Start your application.

This is just the tip of the iceberg. To explore/contribute/complain/donate, please visit BotKit on GitHub.

The Integration Zone is brought to you in partnership with CA Technologies.  Use CA Live API Creator to quickly create complete application backends, with secure APIs and robust application logic, in an easy to use interface.

Topics:
java ,spring-boot ,bot ,bot framework ,slack bots ,slack

Published at DZone with permission of Ram Patra. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}