Skip to content

Commit c8a8645

Browse files
committed
use async http calls for Answer Overflow
1 parent de1e46e commit c8a8645

1 file changed

Lines changed: 17 additions & 12 deletions

File tree

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
package net.discordjug.javabot.systems.help;
22

3-
import java.io.IOException;
43
import java.net.URI;
54
import java.net.http.HttpClient;
65
import java.net.http.HttpRequest;
76
import java.net.http.HttpRequest.BodyPublishers;
8-
import java.net.http.HttpResponse;
97
import java.net.http.HttpResponse.BodyHandlers;
108

119
import lombok.extern.slf4j.Slf4j;
@@ -21,13 +19,18 @@ public AnswerOverflowService(BotConfig config) {
2119
apiKey = config.getSystems().getAnswerOverflowApiKey();
2220
}
2321

22+
/**
23+
* Marks a message as the answer of a forum post with Answer Overflow.
24+
* @param postId The Discord ID of the forum post
25+
* @param messageId The Discord ID of the message that should be marked as the answer.
26+
*/
2427
public void markAnswer(long postId, long messageId) {
2528
if (apiKey == null || apiKey.isBlank()) {
2629
return;
2730
}
2831

2932
try (HttpClient client = HttpClient.newHttpClient()) {
30-
HttpResponse<String> response = client.send(
33+
client.sendAsync(
3134
HttpRequest.newBuilder(URI.create("https://www.answeroverflow.com/api/v1/messages/" + postId))
3235
.header("x-api-key", apiKey)
3336
.header("Content-Type", "application/json")
@@ -37,14 +40,16 @@ public void markAnswer(long postId, long messageId) {
3740
}
3841
""".formatted(messageId)))
3942
.build(),
40-
BodyHandlers.ofString());
41-
if (response.statusCode() != 200) {
42-
log.warn("Answer Overflow responded with unexpected status code {}, post ID: {}, message ID: {}, body: {}", response.statusCode(), postId, messageId, response.body());
43-
}
44-
} catch (IOException e) {
45-
log.error("An exception occured trying to mark a post as an answer.", e);
46-
} catch (InterruptedException e) {
47-
Thread.currentThread().interrupt();
48-
};
43+
BodyHandlers.ofString())
44+
.thenAccept(response -> {
45+
if (response.statusCode() != 200) {
46+
log.warn("Answer Overflow responded with unexpected status code {}, post ID: {}, message ID: {}, body: {}", response.statusCode(), postId, messageId, response.body());
47+
}
48+
})
49+
.exceptionally(e -> {
50+
log.error("An exception occured trying to mark a post as an answer.", e);
51+
return null;
52+
});
53+
}
4954
}
5055
}

0 commit comments

Comments
 (0)