parent
98676fa048
commit
e4dd9db229
@ -0,0 +1,58 @@
|
|||||||
|
package com.example.guerrilla.service;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.slack.api.Slack;
|
||||||
|
import com.slack.api.methods.MethodsClient;
|
||||||
|
import com.slack.api.methods.SlackApiException;
|
||||||
|
import com.slack.api.methods.request.chat.ChatPostMessageRequest;
|
||||||
|
import com.slack.api.methods.response.chat.ChatPostMessageResponse;
|
||||||
|
import com.slack.api.model.Message;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class SlackService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(SlackService.class);
|
||||||
|
|
||||||
|
@Value("${app.slack.app-token}")
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
@Value("${app.slack.channel}")
|
||||||
|
private String channel;
|
||||||
|
|
||||||
|
public void sendMessage(String content) {
|
||||||
|
if (StringUtils.isEmpty(token) || StringUtils.isEmpty(channel)) {
|
||||||
|
logger.info("slack app token or channel not defined!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Slack slack = Slack.getInstance();
|
||||||
|
|
||||||
|
// Initialize an API Methods client with the given token
|
||||||
|
MethodsClient methods = slack.methods(token);
|
||||||
|
|
||||||
|
// Build a request object
|
||||||
|
ChatPostMessageRequest request = ChatPostMessageRequest.builder().channel(channel).text(content).build();
|
||||||
|
|
||||||
|
// Get a response as a Java object
|
||||||
|
try {
|
||||||
|
ChatPostMessageResponse response = methods.chatPostMessage(request);
|
||||||
|
logger.info("response: {}", response);
|
||||||
|
if (response.isOk()) {
|
||||||
|
Message postedMessage = response.getMessage();
|
||||||
|
logger.info("postedMessage: {}", postedMessage);
|
||||||
|
} else {
|
||||||
|
String errorCode = response.getError();
|
||||||
|
logger.info("errorCode: {}", errorCode);
|
||||||
|
}
|
||||||
|
} catch (IOException | SlackApiException e) {
|
||||||
|
logger.error("sendMessage error!", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in new issue