我正在用 Java 编写一个 Slack Bot,我想向用户发送消息以响应斜杠命令。
这可以通过使用 http 客户端库向斜杠命令请求附带的
response_url
参数发送 HTTP 请求来完成。
我无法使用 Slack 的 Java SDK 向
response_url
发送消息,因为 methods
客户端 Slack 的任何方法都不允许我设置 response_url
(chatPostEphemeral
, chatPostMessage
, . ..)
有没有办法使用 Java SDK for Slack 来响应斜杠命令?
您是否尝试过使用 WebClient 类发送带有所需负载的 POST 请求来向 response_url 发送请求?
类似的东西:
public class RespondToSlashCommand {
public static void main(String[] args) {
String responseUrl = "https://hooks.slack.com/commands/YourResponseUrlHere";
String message = "This is a response to a slash command.";
// Initialize the Slack API client
Slack slack = Slack.getInstance();
SlackHttpClient slackHttpClient = slack.getHttpClient();
// Prepare the JSON payload
String jsonPayload = String.format("{\"text\": \"%s\"}", message);
RequestBody requestBody = RequestBody.create(jsonPayload, MediaType.parse("application/json"));
try {
// Send a POST request to the response_url
Response response = slackHttpClient.postJsonBody(responseUrl, requestBody);
if (response.isSuccessful()) {
System.out.println("Response sent successfully!");
} else {
System.out.println("Failed to send response: " + response.message());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}