Skip to content

Commit dd7c1eb

Browse files
committed
Better handling of larger messages...
1 parent da145c7 commit dd7c1eb

1 file changed

Lines changed: 42 additions & 11 deletions

File tree

src/main/java/org/mangorage/mangobotgithub/AICommand.java

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,62 @@
88
import org.mangorage.mangobotapi.core.commands.IBasicCommand;
99

1010
import java.io.IOException;
11+
import java.util.ArrayList;
12+
import java.util.List;
1113

1214
public class AICommand implements IBasicCommand {
13-
@Override
1415
public @NotNull CommandResult execute(Message message, Arguments arguments) {
1516
var prompt = arguments.getFrom(0);
1617
if (prompt.isBlank()) {
18+
return CommandResult.PASS;
19+
}
20+
1721

18-
} else {
19-
try {
20-
var response = ChatGPTBot.askChatGPT(prompt);
21-
if (response != null) {
22-
var choices = response.getChoices();
23-
if (!choices.isEmpty()) {
24-
var msg = choices.getFirst().getMessage();
25-
if (msg != null) {
26-
message.reply(msg.getContent()).setSuppressEmbeds(true).mentionRepliedUser(false).queue();
22+
try {
23+
var response = ChatGPTBot.askChatGPT(prompt);
24+
if (response != null) {
25+
var choices = response.getChoices();
26+
if (!choices.isEmpty()) {
27+
var msg = choices.getFirst().getMessage();
28+
if (msg != null) {
29+
String content = msg.getContent();
30+
if (content.length() > 2000) {
31+
List<String> parts = splitMessage(content, 2000);
32+
for (String part : parts) {
33+
message.reply(part).setSuppressEmbeds(true).mentionRepliedUser(false).queue();
34+
}
35+
} else {
36+
message.reply(content).setSuppressEmbeds(true).mentionRepliedUser(false).queue();
2737
}
2838
}
2939
}
30-
} catch (IOException ignored) {
3140
}
41+
} catch (IOException ignored) {
3242
}
43+
3344
return CommandResult.PASS;
3445
}
3546

47+
/**
48+
* Splits a message into smaller parts without breaking words.
49+
*/
50+
private List<String> splitMessage(String message, int maxLength) {
51+
List<String> parts = new ArrayList<>();
52+
while (message.length() > maxLength) {
53+
int splitIndex = message.lastIndexOf("\n", maxLength);
54+
if (splitIndex == -1) {
55+
splitIndex = message.lastIndexOf(" ", maxLength);
56+
}
57+
if (splitIndex == -1) {
58+
splitIndex = maxLength;
59+
}
60+
parts.add(message.substring(0, splitIndex));
61+
message = message.substring(splitIndex).trim();
62+
}
63+
parts.add(message);
64+
return parts;
65+
}
66+
3667
@Override
3768
public String commandId() {
3869
return "askAI";

0 commit comments

Comments
 (0)