|
8 | 8 | import org.mangorage.mangobotapi.core.commands.IBasicCommand; |
9 | 9 |
|
10 | 10 | import java.io.IOException; |
| 11 | +import java.util.ArrayList; |
| 12 | +import java.util.List; |
11 | 13 |
|
12 | 14 | public class AICommand implements IBasicCommand { |
13 | | - @Override |
14 | 15 | public @NotNull CommandResult execute(Message message, Arguments arguments) { |
15 | 16 | var prompt = arguments.getFrom(0); |
16 | 17 | if (prompt.isBlank()) { |
| 18 | + return CommandResult.PASS; |
| 19 | + } |
| 20 | + |
17 | 21 |
|
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(); |
27 | 37 | } |
28 | 38 | } |
29 | 39 | } |
30 | | - } catch (IOException ignored) { |
31 | 40 | } |
| 41 | + } catch (IOException ignored) { |
32 | 42 | } |
| 43 | + |
33 | 44 | return CommandResult.PASS; |
34 | 45 | } |
35 | 46 |
|
| 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 | + |
36 | 67 | @Override |
37 | 68 | public String commandId() { |
38 | 69 | return "askAI"; |
|
0 commit comments