/
vorotov.a.vikt
/
MathEquGen
Обзор
Документация
Войти
/
vorotov.a.vikt
/
MathEquGen
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop
src/main/java/com/example/chat/telegram/MathEquGenBot.java
173 строки
7 KB
vorotovalexey
небольшие доработки
08 фев 2026, 20:20
08 фев 2026, 20:20
f967048
Код
Авторство
О чём код?
package com.example.chat.telegram; import com.example.chat.logic.aiservice.EquationGenerator; import com.example.chat.logic.component.Transceiver; import com.example.chat.logic.service.MathEquationsExtractor; import com.example.chat.telegram.service.ChatWizard; import com.example.chat.telegram.service.Creators; import com.example.chat.telegram.service.Extractors; import lombok.SneakyThrows; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.GetFile; import org.telegram.telegrambots.meta.api.methods.send.SendDocument; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendPhoto; import org.telegram.telegrambots.meta.api.objects.File; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import javax.swing.text.html.Option; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.Serializable; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; public class MathEquGenBot extends TelegramLongPollingBot { private static final Logger log = LoggerFactory.getLogger(MathEquGenBot.class); private static final String ERROR_MESSAGE = "Произошла ошибка! Просьба повторить сообщение"; private final String botToken; private final ChatWizard chatWizard; private final Extractors extractors; private final MathEquationsExtractor mathEquationsExtractor; private final Creators creators; private final EquationGenerator equationGenerator; public MathEquGenBot(String botToken, ChatWizard chatWizard, Extractors extractors, MathEquationsExtractor mathEquationsExtractor, Creators creators, EquationGenerator equationGenerator) { super(botToken); this.botToken = botToken; this.chatWizard = chatWizard; this.extractors = extractors; this.mathEquationsExtractor = mathEquationsExtractor; this.creators = creators; this.equationGenerator = equationGenerator; } @Override @SneakyThrows public void onUpdateReceived(Update update) { var chatId = extractors.extractChatId(update); var messageId = extractors.extractMessageId(update); log.info("chatId={}", chatId); Optional.ofNullable(update.getMessage()).map(Message::getText) .ifPresent(mt -> log.info("Сообщение для бота:{}", mt)); Optional.ofNullable(update.getMessage()).map(Message::getCaption) .ifPresent(c -> log.info("Сообщение для бота с файлом:{}", c)); var eqWiz = chatWizard.getEquationWizard(chatId); try { eqWiz.getInvocationParameters().put("chatId", chatId); extractors.extractFileId(update).map(this::downloadPhoto) .ifPresent(path -> eqWiz.setExamples(mathEquationsExtractor.extractEquations(path))); extractors.extractMessageTextOrCaption(update) .map(mt -> eqWiz.getEquationAgent().executeCommand(mt, eqWiz.getInvocationParameters())) .or( () -> Optional.of(ERROR_MESSAGE)) .ifPresent(sm -> { try { var sendMessage = new SendMessage(); sendMessage.setChatId(chatId); sendMessage.setText(sm); execute(sendMessage); } catch (Exception e) { throw new RuntimeException(e); } }); eqWiz.getTransceiver().getTransobjects().forEach(t -> { if (t instanceof Transceiver.Image image) { try { // var sendPhoto = creators.createSendDocument(chatId, image); var sendPhoto = creators.createSendPhoto(chatId, image); // sendPhoto.setReplyToMessageId(messageId); executeInternal(sendPhoto); } catch (Exception e) { throw new RuntimeException(e); } } else if (t instanceof Transceiver.File file) { try { var sendDocument = creators.createSendDocument(chatId, file); executeInternal(sendDocument); } catch (Exception e) { throw new RuntimeException(e); } } }); eqWiz.getTransceiver().clear(); } catch (Exception e) { log.error("Произошла ошибка", e); var sendMessage = new SendMessage(); sendMessage.setChatId(chatId); sendMessage.setText(ERROR_MESSAGE); execute(sendMessage); } } @Override public <T extends Serializable, Method extends BotApiMethod<T>> T execute(Method method) throws TelegramApiException { if (method instanceof SendMessage m) { log.info("Ответ в чат: {}", m.getText()); } return super.execute(method); } public Message executeInternal(SendDocument sendDocument) throws TelegramApiException { log.info("Ответ в чат: {}", sendDocument.getCaption()); return super.execute(sendDocument); } public Message executeInternal(SendPhoto sendPhoto) throws TelegramApiException { log.info("Ответ в чат: {}", sendPhoto.getCaption()); return super.execute(sendPhoto); } @Override public String getBotUsername() { return "MathEquGenBot"; } private Path downloadPhoto(String fileId) { try { // Получаем объект File от Telegram File file = execute(new GetFile(fileId)); var filePath = file.getFilePath(); Path filePathPath = Paths.get(filePath); // Формируем URL для скачивания String downloadUrl = "https://api.telegram.org/file/bot" + botToken + "/" + filePath; // Скачиваем файл URL url = new URL(downloadUrl); BufferedInputStream in = new BufferedInputStream(url.openStream()); var savePath = Files.createTempFile("equations-", filePathPath.getFileName().toString()); FileOutputStream out = new FileOutputStream(savePath.toString()); byte[] data = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { out.write(data, 0, count); } out.close(); in.close(); return savePath; } catch (Exception e) { throw new RuntimeException("Не удалось сказать картинку ", e); } } }