Building a simple Slack Bot using Spring Boot and MongoDB

Building a simple Slack Bot using Spring Boot and MongoDB

Step by step tutorial of building a simple Slack Bot using Spring Boot and MongoDB as a worker

A simple step by step tutorial of building a simple Slack Bot using Spring Boot and MongoDB as a Worker. Slack is an acronym for Searchable Log of All Conversation and Knowledge. Slack offers many IRC-like features, including persistent chat rooms (channels) organized by topic, private groups, and direct messaging. Content, including files, conversations, and people, is all searchable within Slack. Users can add emoji buttons to their messages, on which other users can then click to express their reactions to messages. This Slack Bot application using the JBot library. Actually, there's a lot of Slack Bot library for Java (find here), but we just want to try this JBot library.

Table of Contents:

  • Create a Slack App
  • Generate Spring Boot Application
  • Create Java Model or Entity Class
  • Create Java Repository Interface for BadWord Model
  • Add and Configure JBot Java Library
  • Implement Bot Method on Spring Boot Java Application
  • Run and Test the Spring Boot MongoDB Slack Bot

Bots are like having a virtual team member, they can help you manage tasks, run your team standup, poll the office, and more.

The Scenario for this tutorial is simple, just a Slack Bot for catch the keyword from a conversation or chats that contain harsh words or bad words (ex: fuck, sht, b*tch) then save it to MongoDB include with User who sends it. The Slack will count that words from MongoDB until getting 5 words then the Bot will send back the message to channels to warns the sender of bad words.

The following tools, frameworks, and library are required for this tutorial:

  1. Java 8
  2. Spring Boot
  3. Spring Data MongoDB
  4. MongoDB https://www.mongodb.com/
  5. JBot
  6. Terminal or Command Line
  7. IDE or Text Editor (we are using Netbeans)
  8. Spring Initalizr

We assume that you have installed Java 8, MongoDB and IDE or Text Editor. So, we can continue straight forward to the steps of the tutorial.

Create a Slack App

We need a Slack token before moving to Spring Boot MongoDB Slack Bot tutorial. For that, on the browser go to https://yourworkspace.slack.com/services/new/bot. You will redirect to the login form if not logged in yet. Log in using your workspaces user then you will entering Slack Bot configuration page.

Spring Boot + MongoDB Slack Bot Example - Slack Bot Page

Give username for your bot then click Add Bot Integration button. That's it, now you have your Bot token that ready to use. Save that code somewhere in your local, do not try to save it on public repositories or the bot will be disabled by Slack.

Spring Boot + MongoDB Slack Bot Example - Integration Settings

Generate Spring Boot Application

As our previous Spring Boot tutorial, we will generate a Spring Boot application online by going to Spring Initalizr on the browser.

Spring Boot + MongoDB Slack Bot Example - Spring Initializr

Choose to generate a Gradle project with Java and Spring Boot 1.5.9. In Project metadata fill artifact coordinate group with your package ID (example: com.djamware) and artifact by your app name (example: slackbot). Search dependencies for the term of MongoDB. Finally, click Generate Project button to generate and download a zip file contains the initial Spring Boot project.

Extract that zip file to your workspace or projects folder. Now, open the project in the Netbeans. It will load all dependencies automatically, just wait until finished. After that, you will see the directory structure like this in the files navigation.

Spring Boot + MongoDB Slack Bot Example - Directory Structure

Create Java Model or Entity Class

Every bad word catch from Slack message save to MongoDB collection including the sender of the message. For that, we have to create a Java class that represents a model for bad words collection. If you are using Netbeans (similar with some IDE), right-click project name then click New then click Java Class.

Spring Boot + MongoDB Slack Bot Example - Create Java Class

Fill necessary fields like above screenshot then click Finish button. Netbeans will automatically open the newly created file, replace all codes with this.

package com.djamware.slackbot.models;

import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "badwords")
public class BadWord {
    @Id
    String id;
    String user;
    String word;
    Date updateDate = new Date();

    public BadWord() {
    }

    public BadWord(String user, String word, Date updateDate) {
        this.user = user;
        this.word = word;
        this.updateDate = updateDate;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }
}

That BadWord class mapping to badword collections of MongoDB which has 4 fields (id, user, word, updateDate). Each field has getter and setter except for updateDate has a default value for the current date.

Don't forget to add MongoDB configuration to the src/main/recources/application.properties.

spring.data.mongodb.database=slackbot
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

Create Java Repository Interface for BadWord Model

Now, we need to create an interface for connecting the BadWord model and controller. On Netbeans right-click project name on projects left panel then choose New then choose Java Interface. On the New Java Interface dialog, git it name BadwordRepository and package name com.djamware.slackbot.repositories then click Finish button.

Next, replace all codes with these few lines of codes.

package com.djamware.slackbot.repositories;

import com.djamware.slackbot.models.BadWord;
import org.springframework.data.repository.CrudRepository;

public interface BadwordRepository extends CrudRepository<BadWord, String> {

}

Add and Configure JBot Java Library

Back to business, open and edit build.gradle from the root of the project folder. Add JBot dependencies to dependencies block.

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-mongodb')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    compile("me.ramswaroop.jbot:jbot:3.0.2")
}

Then run compile by open the Run menu then choose compile file or just click on F9 key. Now, the library is ready to use with your Java application.

Implement Bot Method on Spring Boot Java Application

It's time to make a Java Slack Bot with Spring Boot. Open application.properties on the src/main/resources folder then add these lines of codes.

rtmUrl=https://slack.com/api/rtm.start?token={token}&simple_latest&no_unreads
slackBotToken=your-slack-bot-token

Next, create a Class file in the package com.djamware.slackbot.bot with the name of the file SlackBot.java. After the new class file opened, add extends to the class name and add annotation above the class name.

@Component
public class SlackBot extends Bot {

}

Declare the variable for logger on the first line of the class body.

private static final Logger logger = LoggerFactory.getLogger(SlackBot.class);

Declare a variable for getting the token which handles by JBot library.

@Value("${slackBotToken}")
private String slackToken;

Next, create getter methods for token and JBot library.

@Override
public String getSlackToken() {
    return slackToken;
}

@Override
public Bot getSlackBot() {
    return this;
}

Now, create a method for receiving a direct message (DM) to the Slack Bot.

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

For catching bad words, we have to add a method onReceiveMessage and create a filter by message string pattern.

@Controller(events = EventType.MESSAGE, pattern = "fuck|shit|bitch")
public void onReceiveMessage(WebSocketSession session, Event event, Matcher matcher) {
    if(!matcher.group(0).isEmpty()) {
        BadWord badword = new BadWord(event.getUserId(),matcher.group(0));
        badwordRepository.save(badword);
        Integer countBadWords = badwordRepository.countByUser(event.getUserId());
        if(countBadWords >= 5) {
            reply(session, event, new Message("Enough! You have too many say bad words. \nThe admin will kick you away from this channel."));
        } else {
            reply(session, event, new Message("Becareful you have say bad words "+countBadWords+" times"));
        }
    }
}

The bad words declare the pattern if found one of them then save it to the database. After save, count by user ID then check if bad words exceed the maximum allowed 5 words then the response to the channel with a warning message.

Run and Test the Spring Boot MongoDB Slack Bot

To test and run the Slack Bot application on the local machine, make sure your MongoDB is running. Then open another terminal to run the Slack Bot by typing this command in the project directory.

./gradlew bootrun

Open the Slack app from your browser or desktop app then log on to it. Create a new channel from the left navigation menu of the Slack app.

Spring Boot + MongoDB Slack Bot Example - Slack Create Channel

Then fill the new Channel form like below.

Spring Boot + MongoDB Slack Bot Example - Create Channel Form

Click Create Channel button to finish. Now, your channel is ready. Type something contains bad words in the text field below the Slack App. If it catches then you will get the response like this.

Spring Boot + MongoDB Slack Bot Example - Slack Bad Word Catcher

That's it, a simple Slack Bot example using Spring Boot, MongoDB, and JBot. Actually, JBot getUser() method returns null so for saving user who types the bad word to DB using user ID. There's some Slack Bot library for Java out there that might be fit for your requirements, this is just an example of Slack Bot integration. For the full working Source Code, you can find in our GitHub.

spring-boot java chatbot mongodb

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Build a CRUD API with Java, MongoDB, and Spring Boot

This tutorial shows how to build a CRUD API with Java, MongoDB, and Spring Boot. How to build a CRUD API with Java and MongoDB. In this tutorial, you create a Java data model class and mapped it to a MongoDB domain document using Spring Data annotations. You use a simple embedded MongoDB database as the datastore. You use Spring Boot to quickly and easily expose your data model via a REST API. Finally, you secured the REST API using Okta and Okta’s Spring Boot Starter.

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK? OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE).

Java Spring Boot First App

Step by Step to your First Spring App

Spring Boot Tutorials - Spring Boot Full Course

Spring Boot Tutorials | Full Course - What is Spring? Spring Boot is an open source Java-based framework used to create a Micro Service. Spring Boot contains a comprehensive infrastructure support for developing a micro service and enables you to develop enterprise-ready applications that you can “just run”.

Top 10 Advanced Java and Spring Boot Courses for Full-Stack Java Developers

These are best online courses to learn Spring Boot, Advanced Java, Docker, React, Microservices, DEvops, and Angular to become full stack Java developer.