Post to Slack from Play Framework 2.8 (Java)

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.

Recommended Posts

Post to Slack from Play Framework 2.8 (Java)
Play Framework2.5 (Java) Tips
Changes from Java 8 to Java 11
Sum from Java_1 to 100
From Java to Ruby !!
Migration from Cobol to JAVA
New features from Java7 to Java8
Connect from Java to PostgreSQL
Introduced Dozer to Play Framework
From Ineffective Java to Effective Java
How to use Java HttpClient (Post)
Play Framework 2.6 (Java) development environment creation
Java to be involved from today
From Java to VB.NET-Writing Contrast Memo-
Java, interface to start from beginner
The road from JavaScript to Java
[Java] Conversion from array to List
java framework
Easy to make Slack Bot in Java
How to install Play Framework 2.6 for Mac
How to use BootStrap with Play Framework
Convert from java UTC time to JST time
Play Framework 2.6 (Java) environment construction in Eclipse
From installing Eclipse to executing Java (PHP)
Java: How to send values from Servlet to Servlet
[Java] Flow from source code to execution
Introduction to monitoring from Java Touching Prometheus
Precautions when migrating from VB6.0 to JAVA
Memo for migration from java to kotlin
Type conversion from java BigDecimal type to String type
[Java] From two Lists to one array list
Upsert from Java SDK to Azure Cosmos DB
Run R from Java I want to run rJava
POST images from Android to PHP using Retrofit
Connect to Aurora (MySQL) from a Java application
Migrate from Java to Server Side Kotlin + Spring-boot
How to use Java framework with AWS Lambda! ??
How to get Class from Element in Java
Play Framework study
Java framework comparison
[Java] Introduction to Java
[Java] How to switch from open jdk to oracle jdk
I want to play with Firestore from Rails
I want to write quickly from java to sqlite
Introduction to java
Minecraft BE server development from PHP to Java
Select * from Java SDK to Azure Cosmos DB
[Java] Collection framework
Launch Docker from Java to convert Office documents to PDF
Convert Java enum enums and JSON to and from Jackson
[Swift] How to play songs from your music library
[Java] I want to calculate the difference from the date
How to jump from Eclipse Java to a SQL file
How to write Scala from the perspective of Java
How to deploy Java to AWS Lambda with Serverless Framework
[Java] How to play rock-paper-scissors (equivalent to paiza rank A)
[Java] How to extract the file name from the path
6 features I missed after returning to Java from Scala
Java development for beginners to start from 1-Vol.1-eclipse setup
How to change from Oracle Java 8 to Adopt Open JDK 9
[Java] How to erase a specific character from a character string