- Выберите загрузчик игры
- OptiFine
Не знаю,просто нейросеть через команду,ss:
new AICommand()
Пожалуйста, авторизуйтесь для просмотра ссылки.
Пожалуйста, авторизуйтесь для просмотра ссылки.
потом идем в CommandManager и добавляем строку:new AICommand()
package DickRecode.commands.impl;
import DickRecode.commands.Command;
import DickRecode.commands.CommandInfo;
import DickRecode.utils.client.ClientUtil;
import net.minecraft.util.text.TextFormatting;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@CommandInfo(name = "ai", description = "Задать вопрос нейросети")
public class AICommand extends Command {
private static final String API_URL = "Пожалуйста, авторизуйтесь для просмотра ссылки.";
private static final int MAX_REQUESTS_PER_PLAYER = 100;
private static final Map<String, Integer> playerRequests = new HashMap<>();
private static String lastResetDate = "";
private static final Map<String, List<Message>> playerHistory = new HashMap<>();
private static final int MAX_HISTORY = 6;
@Override
public void run(String[] args) throws Exception {
String playerName = mc.player.getName().getString();
checkDailyReset();
playerHistory.putIfAbsent(playerName, new ArrayList<>());
if (args.length == 1) {
ClientUtil.sendMesage(TextFormatting.RED + "Использование: .ai <вопрос>");
ClientUtil.sendMesage(TextFormatting.GRAY + "Команды: .ai clear - очистить историю, .ai limit - проверить лимит");
return;
}
if (args[1].equalsIgnoreCase("clear")) {
playerHistory.get(playerName).clear();
ClientUtil.sendMesage(TextFormatting.GREEN + "[AI] История диалога очищена!");
return;
}
if (args[1].equalsIgnoreCase("limit")) {
int used = playerRequests.getOrDefault(playerName, 0);
ClientUtil.sendMesage(TextFormatting.GRAY + "Использовано запросов: " + used + "/" + MAX_REQUESTS_PER_PLAYER);
return;
}
int requestsUsed = playerRequests.getOrDefault(playerName, 0);
if (requestsUsed >= MAX_REQUESTS_PER_PLAYER) {
ClientUtil.sendMesage(TextFormatting.RED + "Ты исчерпал лимит запросов на сегодня (" + MAX_REQUESTS_PER_PLAYER + ")");
return;
}
StringBuilder question = new StringBuilder();
for (int i = 1; i < args.length; i++) {
question.append(args).append(" ");
}
final String finalQuestion = question.toString().trim();
if (finalQuestion.isEmpty()) {
ClientUtil.sendMesage(TextFormatting.RED + "Что хочешь спросить?");
return;
}
ClientUtil.sendMesage(TextFormatting.GRAY + "AI: " + TextFormatting.YELLOW + "Думаю...");
playerRequests.put(playerName, requestsUsed + 1);
playerHistory.get(playerName).add(new Message("user", finalQuestion));
CompletableFuture.supplyAsync(() -> askAI(finalQuestion, playerName))
.thenAccept(answer -> {
ClientUtil.sendMesage(TextFormatting.AQUA + "[AI] " + TextFormatting.WHITE + answer);
playerHistory.get(playerName).add(new Message("assistant", answer));
List<Message> history = playerHistory.get(playerName);
while (history.size() > MAX_HISTORY) {
history.remove(0);
}
})
.exceptionally(ex -> {
ClientUtil.sendMesage(TextFormatting.RED + "[AI] Ошибка: " + ex.getMessage());
return null;
});
}
private void checkDailyReset() {
java.time.LocalDate today = java.time.LocalDate.now();
String todayStr = today.toString();
if (!todayStr.equals(lastResetDate)) {
playerRequests.clear();
lastResetDate = todayStr;
}
}
private String askAI(String question, String playerName) {
try {
HttpURLConnection conn = (HttpURLConnection) URI.create(API_URL).toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setConnectTimeout(30000);
conn.setReadTimeout(60000);
List<Message> history = playerHistory.get(playerName);
int startIndex = Math.max(0, history.size() - MAX_HISTORY);
StringBuilder messagesJson = new StringBuilder();
messagesJson.append("[");
// лютый промпт,можете поменять
messagesJson.append("{\"role\":\"system\",\"content\":\"Ты полезный AI. Отвечай кратко.\"}");
for (int i = startIndex; i < history.size(); i++) {
Message msg = history.get(i);
messagesJson.append(",{\"role\":\"").append(msg.role).append("\",\"content\":\"").append(escapeJson(msg.content)).append("\"}");
}
messagesJson.append("]");
String jsonInputString = String.format(
"{\"model\":\"openai\",\"messages\":%s,\"max_tokens\":300}",
messagesJson.toString()
);
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
}
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
return "Ошибка: " + responseCode;
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
String answer = extractAnswer(response.toString());
if (answer.isEmpty()) return "Не удалось получить ответ";
if (answer.length() > 400) answer = answer.substring(0, 397) + "...";
return answer;
}
} catch (Exception e) {
return "Ошибка: " + e.getMessage();
}
}
private String extractAnswer(String json) {
try {
String marker = "\"content\":\"";
int idx = json.indexOf(marker);
if (idx != -1) {
int start = idx + marker.length();
StringBuilder sb = new StringBuilder();
for (int i = start; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '"') break;
if (c == '\\' && i + 1 < json.length()) {
sb.append(json.charAt(i + 1));
i++;
} else {
sb.append(c);
}
}
return sb.toString();
}
} catch (Exception ignored) {}
return "";
}
private String escapeJson(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
}
private static class Message {
String role;
String content;
Message(String role, String content) {
this.role = role;
this.content = content;
}
}
@Override
public void error() {
ClientUtil.sendMesage(TextFormatting.RED + "Ошибка в команде .ai");
}
}