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.
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:
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.
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.
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.
As our previous Spring Boot tutorial, we will generate a Spring Boot application online by going to Spring Initalizr on the browser.
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.
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
.
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
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> {
}
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.
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.
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.
Then fill the new Channel form like below.
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.
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