[Java] Post to Slack from Play Framework 2.8 (Java)

3 minute read

Overview

How to use Slack API with Play Framework 2.8.
We will implement a simple posting function.

Use Slack’s official Java client, which makes it easy to use Slack’s Web API.

It is an article that aims to practice the contents of the official article with Play Framework.
https://slack.dev/java-slack-sdk/guides/ja/web-api-basics

Preparation

Creating a project

Omit.
Prepare an empty project using the Play Framework Java template.

Dependency description

The Slack official provides a client to easily handle Slack’s Web API in Java.
We will install this in the project we created earlier.

↓ Official page about setup
https://slack.dev/java-slack-sdk/guides/ja/web-api-client-setup

The official page introduces how to install to the project using Maven, but the Play Framework uses Maven2, and you can install it with a simple description.

Open build.sbt in the top directory of the project file and add the following dependencies.

build.sbt


libraryDependencies += "com.slack.api" % "slack-api-client" % "1.0.8"

The contents of the dependency are the group ID, artifact ID, and version from the left, so change them as necessary.

That’s all for the preparation for the Play Framework project.
The client will be downloaded and installed automatically when you compile for the first time.
After that, you can use the client with the import statement in the java file.

Get token

This time it is the setting on the Slack side.
Tokens are issued by Slack’s workspace, so to speak, “a permit that you can post to Slack if you have it.”
With this string, you can post to Slack.

I will omit the details,

–Creating a new application
–Required token information
–Adding an application to your workspace

You can issue tokens by doing.

There are two types of tokens, bots and users, but it doesn’t matter if you just try posting.
The scope requires chat: write.

Please refer to the official page below.

https://slack.com/intl/ja-jp/help/articles/115005265703-%E3%83%AF%E3%83%BC%E3%82%AF%E3%82%B9%E3%83%9A%E3%83%BC%E3%82%B9%E3%81%A7%E5%88%A9%E7%94%A8%E3%81%99%E3%82%8B%E3%83%9C%E3%83%83%E3%83%88%E3%81%AE%E4%BD%9C%E6%88%90
https://slack.com/intl/ja-jp/help/articles/215770388-API-%E3%83%88%E3%83%BC%E3%82%AF%E3%83%B3%E3%81%AE%E7%94%9F%E6%88%90%E3%81%A8%E5%86%8D%E7%94%9F%E6%88%90

Channel settings

Add the application to the channel you want to post.
It can be set from the Slack application.

Implementation

This time, for the sake of simplicity, it is described in the index method of HomeController.java that is executed at startup.
When creating an actual application, write it in a model or something.

HomeController.java


package controllers;
import com.slack.api.model.Message;
import play.mvc.*;
import com.slack.api.Slack;
import java.io.IOException;
import com.slack.api.methods.response.chat.ChatPostMessageResponse;
import com.slack.api.methods.MethodsClient;
import com.slack.api.methods.request.chat.ChatPostMessageRequest;
import com.slack.api.methods.SlackApiException;

public class HomeController extends Controller {

  public Result index() {
    Slack slack = Slack.getInstance();
    String token = "Token string";
    MethodsClient methods = slack.methods(token);
    ChatPostMessageRequest request = ChatPostMessageRequest.builder().channel("#general").text(":wave: Hi from a bot written in Java!").build();

    try {
      ChatPostMessageResponse response = slack.methods(token).chatPostMessage(request);
      if (response.isOk()) {
        Message postedMessage = response.getMessage();
        System.out.println("success");
      } else {
        String errorCode = response.getError();
        System.out.println("Failure 1"+errorCode);
      }
    } catch (SlackApiException requestFailure) {
      System.out.println("Failure 2");
    } catch (IOException connectivityIssue) {
      System.out.println("Failure 3");
    }
    return ok(views.html.index.render());
  }

}

It is okay if the acquired token is included in the character string part of the token.
The official page uses a method to get the token stored in the environment variable.
Entering directly is out of the question of versatility and security, so don’t ** absolutely ** in a real application.

As a flow,

–Initialize your Slack instance
–Token storage
–Set token in instance for request generation
–Request generation
-Receive a response (send a request) (with exception handling)

I feel like.

Since the request is generated according to the Slack Web API, it should be easy to understand how to generate the request.

If you do not write exception handling, you will be warned at runtime, so please write it referring to the official page.

Hopefully at runtime you will see ```success ` on the console and it will be posted to the specified channel.
If it fails, please check the error by referring to the official document.
In my case, I was getting an error saying that the token was not set properly and that the posting channel was specified incorrectly.

Summary

–The Slack API client can now be used with the Play Framework.
–Posted a message from Play Framework to Slack.