Skip to content

Commit 4f7968c

Browse files
committed
Clean up
1 parent 50a8c3c commit 4f7968c

File tree

9 files changed

+100
-123
lines changed

9 files changed

+100
-123
lines changed

example/lj-discord-bot/src/main/java/com/javadiscord/bot/Main.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,21 +26,21 @@ public static JShellService jShellService() {
2626
return new JShellService();
2727
}
2828

29-
private static DockerClient dockerClient =
29+
private static final DockerClient DOCKER_CLIENT =
3030
DockerClientBuilder.getInstance("tcp://localhost:2375").build();
3131

3232
@Component
3333
public static DockerClient dockerClient() {
34-
return dockerClient;
34+
return DOCKER_CLIENT;
3535
}
3636

3737
@Component
3838
public static DockerCommandRunner dockerCommandRunner() {
39-
return new DockerCommandRunner(dockerClient);
39+
return new DockerCommandRunner(DOCKER_CLIENT);
4040
}
4141

4242
@Component
4343
public static DockerSessions dockerSessions() {
44-
return new DockerSessions(dockerClient);
44+
return new DockerSessions(DOCKER_CLIENT);
4545
}
4646
}

example/lj-discord-bot/src/main/java/com/javadiscord/bot/commands/slash/JShellCommand.java

Lines changed: 78 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -33,91 +33,102 @@ public void handle(SlashCommandEvent event) {
3333

3434
private void handleJShell(SlashCommandEvent event) {
3535
User user = event.user();
36-
3736
long start = System.currentTimeMillis();
3837

3938
event.option("code").ifPresent(msg -> {
4039
JShellResponse response = jShellService.sendRequest(msg.valueAsString());
4140
if (response == null) {
42-
String reply = "Failed to execute the provided code, was it bad?";
43-
Embed embed =
44-
new Embed.Builder()
45-
.author(new EmbedAuthor(user.asMention(), user.avatar(), null, null))
46-
.description(reply)
47-
.color(Color.ORANGE)
48-
.build();
49-
event.reply(embed);
41+
handleNullResponse(event, user);
5042
return;
5143
}
5244

5345
if (response.error() != null && !response.error().isEmpty()) {
54-
String reply =
55-
"""
56-
An error occurred while executing command:
57-
58-
```java
59-
%s
60-
```
61-
62-
%s
63-
"""
64-
.formatted(msg.valueAsString(), response.error());
65-
Embed embed =
66-
new Embed.Builder()
67-
.author(new EmbedAuthor(user.asMention(), user.avatar(), null, null))
68-
.description(reply)
69-
.color(Color.RED)
70-
.build();
71-
event.reply(embed);
46+
handleErrorResponse(event, user, msg.valueAsString(), response);
7247
return;
7348
}
7449

75-
StringBuilder sb = new StringBuilder();
76-
sb.append("## Snippets\n");
77-
for (JShellSnippet snippet : response.events()) {
78-
sb.append("`");
79-
sb.append(snippet.statement());
80-
sb.append("`\n\n");
81-
sb.append("**Status**: ");
82-
sb.append(snippet.status());
83-
sb.append("\n");
84-
85-
if (snippet.value() != null && !snippet.value().isEmpty()) {
86-
sb.append("**Output**\n");
87-
sb.append("```java\n");
88-
sb.append(snippet.value());
89-
sb.append("```\n");
90-
}
91-
}
50+
handleSuccessResponse(event, user, response, start);
51+
});
52+
}
9253

93-
if (!response.outputStream().isEmpty()) {
94-
sb.append("## Console Output\n");
95-
sb.append("```java\n");
96-
sb.append(response.outputStream());
97-
sb.append("```\n");
98-
}
54+
private void handleNullResponse(SlashCommandEvent event, User user) {
55+
String reply = "Failed to execute the provided code, was it bad?";
56+
Embed embed =
57+
new Embed.Builder()
58+
.author(new EmbedAuthor(user.asMention(), user.avatar(), null, null))
59+
.description(reply)
60+
.color(Color.ORANGE)
61+
.build();
62+
event.reply(embed);
63+
}
64+
65+
private void handleErrorResponse(
66+
SlashCommandEvent event,
67+
User user,
68+
String code,
69+
JShellResponse response
70+
) {
71+
String reply =
72+
String.format(
73+
"""
74+
An error occurred while executing command:
75+
76+
```java
77+
%s
78+
```
79+
80+
%s
81+
""", code, response.error()
82+
);
83+
Embed embed =
84+
new Embed.Builder()
85+
.author(new EmbedAuthor(user.asMention(), user.avatar(), null, null))
86+
.description(reply)
87+
.color(Color.RED)
88+
.build();
89+
event.reply(embed);
90+
}
9991

100-
if (response.errorStream() != null && !response.errorStream().isEmpty()) {
101-
sb.append("## Error Output\n");
102-
sb.append("```java\n");
103-
sb.append(response.errorStream());
104-
sb.append("```\n");
92+
private void handleSuccessResponse(
93+
SlashCommandEvent event,
94+
User user,
95+
JShellResponse response,
96+
long start
97+
) {
98+
StringBuilder sb = new StringBuilder();
99+
sb.append("## Snippets\n");
100+
for (JShellSnippet snippet : response.events()) {
101+
sb.append("`").append(snippet.statement()).append("`\n\n");
102+
sb.append("**Status**: ").append(snippet.status()).append("\n");
103+
104+
if (snippet.value() != null && !snippet.value().isEmpty()) {
105+
sb.append("**Output**\n");
106+
sb.append("```java\n").append(snippet.value()).append("```\n");
105107
}
108+
}
106109

107-
Embed.Builder embed =
108-
new Embed.Builder()
109-
.author(new EmbedAuthor(user.asMention(), null, null, null));
110+
appendOutputStreams(sb, response);
110111

111-
if (sb.length() > 4000) {
112-
embed.description(sb.substring(0, 4000));
113-
} else {
114-
embed.description(sb.toString());
115-
}
112+
Embed.Builder embed =
113+
new Embed.Builder()
114+
.author(new EmbedAuthor(user.asMention(), null, null, null))
115+
.description(sb.length() > 4000 ? sb.substring(0, 4000) : sb.toString())
116+
.color(Color.GREEN)
117+
.footer("Time taken: " + (System.currentTimeMillis() - start) + "ms");
116118

117-
embed.color(Color.GREEN);
118-
embed.footer("Time taken: " + (System.currentTimeMillis() - start) + "ms");
119-
event.reply(embed.build()).onError(System.err::println);
120-
});
119+
event.reply(embed.build());
120+
}
121+
122+
private void appendOutputStreams(StringBuilder sb, JShellResponse response) {
123+
if (!response.outputStream().isEmpty()) {
124+
sb.append("## Console Output\n");
125+
sb.append("```java\n").append(response.outputStream()).append("```\n");
126+
}
127+
128+
if (response.errorStream() != null && !response.errorStream().isEmpty()) {
129+
sb.append("## Error Output\n");
130+
sb.append("```java\n").append(response.errorStream()).append("```\n");
131+
}
121132
}
122133

123134
}

example/lj-discord-bot/src/main/java/com/javadiscord/bot/listeners/SpamListener.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,8 @@
77
import com.javadiscord.jdi.core.api.builders.CreateMessageBuilder;
88
import com.javadiscord.jdi.core.models.message.Message;
99

10-
import org.apache.logging.log4j.LogManager;
11-
import org.apache.logging.log4j.Logger;
12-
1310
@EventListener
1411
public class SpamListener {
15-
private static final Logger LOGGER = LogManager.getLogger(SlashCommandListener.class);
1612

1713
@MessageCreate
1814
public void onMessage(Message message, Guild guild) {
@@ -33,7 +29,7 @@ public void onMessage(Message message, Guild guild) {
3329
"""
3430
.formatted(message.content())
3531
)
36-
).onError(System.err::println)
32+
)
3733
);
3834
}
3935
}

example/lj-discord-bot/src/main/java/com/javadiscord/bot/listeners/SuggestionListener.java

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,6 @@ public void onMessage(Message message, Guild guild) {
1919
return;
2020
}
2121

22-
// guild.channel().createReaction(message.channelId(), message.id(), "thumbup");
23-
// guild.channel().createReaction(message.channelId(), message.id(),
24-
// "thumbsdown");
25-
2622
String title =
2723
message.content().length() > 60
2824
? message.content().substring(0, 60)
@@ -34,8 +30,7 @@ public void onMessage(Message message, Guild guild) {
3430
message.id(),
3531
title
3632
)
37-
).onError(System.err::println)
38-
.onSuccess(System.out::println);
33+
);
3934
}
4035

4136
}

example/lj-discord-bot/src/main/java/com/javadiscord/bot/utils/Tenor.java

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import org.apache.logging.log4j.Logger;
1313

1414
public class Tenor {
15-
private static final Logger logger = LogManager.getLogger(Tenor.class);
15+
private static final Logger LOGGER = LogManager.getLogger(Tenor.class);
1616
private static final String API_KEY = System.getenv("TENOR_API_KEY");
1717
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
1818
private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
@@ -38,10 +38,12 @@ public static JsonNode search(String searchTerm, int limit) {
3838
if (response.statusCode() == 200) {
3939
return OBJECT_MAPPER.readTree(response.body());
4040
} else {
41-
System.err.println("HTTP Code: " + response.statusCode() + " from " + url);
41+
LOGGER.trace("HTTP Code: {} from {}", response.statusCode(), url);
4242
}
43+
4344
} catch (IOException | InterruptedException e) {
44-
logger.error("Error making a request to Tenor", e);
45+
LOGGER.error("Error making a request to Tenor", e);
46+
Thread.currentThread().interrupt();
4547
}
4648

4749
return null;

example/lj-discord-bot/src/main/java/com/javadiscord/bot/utils/chatgpt/ChatGPT.java

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,37 +14,17 @@
1414
import org.apache.logging.log4j.Logger;
1515

1616
public class ChatGPT {
17-
private static final Logger logger = LogManager.getLogger(ChatGPT.class);
17+
private static final Logger LOGGER = LogManager.getLogger(ChatGPT.class);
1818
private static final String API_KEY = System.getenv("CHATGPT_API_KEY");
1919
private static final Duration TIMEOUT = Duration.ofMinutes(3);
2020
private static final String AI_MODEL = "gpt-3.5-turbo";
21-
private final OpenAiService openAiService;
22-
2321
private static final int MAX_TOKENS = 2000;
24-
25-
/**
26-
* This parameter reduces the likelihood of the AI repeating itself. A higher
27-
* frequency penalty makes the model less likely to repeat the same lines
28-
* verbatim. It helps in generating more diverse and varied responses.
29-
*/
3022
private static final double FREQUENCY_PENALTY = 0.5;
31-
32-
/**
33-
* This parameter controls the randomness of the AI's responses. A higher
34-
* temperature results in more varied, unpredictable, and creative responses.
35-
* Conversely, a lower temperature makes the model's responses more
36-
* deterministic and conservative.
37-
*/
3823
private static final double TEMPERATURE = 0.8;
39-
40-
/**
41-
* n: This parameter specifies the number of responses to generate for each
42-
* prompt. If n is more than 1, the AI will generate multiple different
43-
* responses to the same prompt, each one being a separate iteration based on
44-
* the input.
45-
*/
4624
private static final int MAX_NUMBER_OF_RESPONSES = 1;
4725

26+
private final OpenAiService openAiService;
27+
4828
public ChatGPT() {
4929
openAiService = new OpenAiService(API_KEY, TIMEOUT);
5030

@@ -92,9 +72,9 @@ public Optional<String[]> ask(String question) {
9272
.getMessage()
9373
.getContent();
9474

95-
return Optional.ofNullable(ChatGPTResponseParser.parse(response));
75+
return Optional.of(ChatGPTResponseParser.parse(response));
9676
} catch (OpenAiHttpException openAiHttpException) {
97-
logger.warn(
77+
LOGGER.warn(
9878
String.format(
9979
"There was an error using the OpenAI API: %s Code: %s Type: %s Status"
10080
+ " Code: %s",
@@ -105,7 +85,7 @@ public Optional<String[]> ask(String question) {
10585
)
10686
);
10787
} catch (RuntimeException e) {
108-
logger.warn(
88+
LOGGER.warn(
10989
"There was an error using the OpenAI API: {}", e.getMessage()
11090
);
11191
}

example/lj-discord-bot/src/main/java/com/javadiscord/bot/utils/chatgpt/ChatGPTResponseParser.java

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@
77
import org.apache.logging.log4j.Logger;
88

99
public class ChatGPTResponseParser {
10-
private static final Logger logger = LogManager.getLogger(ChatGPTResponseParser.class);
10+
private static final Logger LOGGER = LogManager.getLogger(ChatGPTResponseParser.class);
1111
private static final int RESPONSE_LENGTH_LIMIT = 2000;
1212

1313
private ChatGPTResponseParser() {}
1414

1515
public static String[] parse(String response) {
1616
String[] partedResponse = new String[] {response};
1717
if (response.length() > RESPONSE_LENGTH_LIMIT) {
18-
logger.debug("Response to parse:\n{}", response);
18+
LOGGER.debug("Response to parse:\n{}", response);
1919
partedResponse = partitionAiResponse(response);
2020
}
2121
return partedResponse;
@@ -29,9 +29,6 @@ private static String[] partitionAiResponse(String response) {
2929
List<String> chunks = new ArrayList<>();
3030
chunks.add(split);
3131

32-
// Check each chunk for correct length. If over the length, split in two and
33-
// check
34-
// again.
3532
while (!chunks.stream().allMatch(s -> s.length() < RESPONSE_LENGTH_LIMIT)) {
3633
for (int j = 0; j < chunks.size(); j++) {
3734
String chunk = chunks.get(j);
@@ -43,22 +40,17 @@ private static String[] partitionAiResponse(String response) {
4340
}
4441
}
4542

46-
// Given the splitting on ```, the odd numbered entries need to have code marks
47-
// restored.
4843
if (i % 2 != 0) {
49-
// We assume that everything after the ``` on the same line is the language
50-
// declaration. Could be empty.
5144
String lang = split.substring(0, split.indexOf(System.lineSeparator()));
5245
chunks =
5346
chunks.stream()
5447
.map(s -> ("```" + lang).concat(s).concat("```"))
55-
// Handle case of doubling language declaration
5648
.map(s -> s.replaceFirst("```" + lang + lang, "```" + lang))
5749
.toList();
5850
}
5951

6052
responseChunks.addAll(filterEmptyStrings(chunks));
61-
} // end of for loop.
53+
}
6254

6355
return responseChunks.toArray(new String[0]);
6456
}

example/lj-discord-bot/src/main/java/com/javadiscord/bot/utils/jshell/JShellService.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ record Request(String code) {}
4444
LOGGER.error("Failed to parse data received from JShell API", e);
4545
} catch (IOException | InterruptedException e) {
4646
LOGGER.error("Failed to send request to JShell API", e);
47+
Thread.currentThread().interrupt();
4748
}
4849
return null;
4950
}

models/src/test/unit/com/javadiscord/jdi/internal/channel/ThreadGuildModelMemberTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ void testDecodingThreadMember() {
3232
ThreadMember threadMember = OBJECT_MAPPER.readValue(input, ThreadMember.class);
3333
assertEquals(1, threadMember.threadId());
3434
assertEquals(10, threadMember.userId());
35-
assertEquals(OffsetDateTime.parse("2024-04-25T21:37:44Z"), threadMember.joinTime());
35+
assertEquals(OffsetDateTime.parse("2024-04-25T21:37:44Z").toString(), threadMember.joinTime());
3636
assertEquals(0, threadMember.flags());
3737
} catch (JsonProcessingException e) {
3838
fail(e.getMessage());

0 commit comments

Comments
 (0)