Untitled
Понял вас. Вы правы, интерфейс TelegramBot из библиотеки telegrambots действительно не содержит метода execute. Вместо этого метод execute находится в классе TelegramLongPollingBot, который является подклассом TelegramBot. Давайте исправим ваш код, чтобы использовать TelegramLongPollingBot и добавим необходимые изменения для корректной отправки сообщений. Исправленный метод processCommand java package ru.dmt100.hhmonitorbotapplication.controller; import org.springframework.stereotype.Controller; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class CommandController { private final Map<String, CommandHandler> handlers = new HashMap<>(); public CommandController(List<CommandHandler> handlers) { handlers.forEach(handler -> this.handlers.put(handler.getCommandName(), handler)); } public void processCommand(Message message, TelegramLongPollingBot bot) { String commandName = extractCommandName(message); CommandHandler handler = this.handlers.get(commandName); if (handler != null) { handler.handle(message, bot); } else { SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(message.getChatId()); sendMessage.setText("Unknown command: " + commandName); try { bot.execute(sendMessage); } catch (TelegramApiException e) { e.printStackTrace(); } } } private String extractCommandName(Message message) { String text = message.getText(); if (text != null && text.startsWith("/")) { return text.split(" ")[0].substring(1); } return ""; } } Обновленный BotConfig Убедитесь, что ваш BotConfig использует TelegramLongPollingBot и передает его в CommandController. java package ru.dmt100.hhmonitorbotapplication.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.objects.Update; @Configuration @EnableScheduling public class BotConfig { @Value("${bot.token}") private String token; @Value("${bot.name}") private String name; @Bean public TelegramLongPollingBot telegramBot(CommandController commandController) { return new TelegramLongPollingBot(token) { @Override public String getBotUsername() { return name; } @Override public void onUpdateReceived(Update update) { if (update.hasMessage() && update.getMessage().hasText()) { commandController.processCommand(update.getMessage(), this); } } }; } } Пример полного кода CommandController java package ru.dmt100.hhmonitorbotapplication.controller; import org.springframework.stereotype.Controller; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class CommandController { private final Map<String, CommandHandler> handlers = new HashMap<>(); public CommandController(List<CommandHandler> handlers) { handlers.forEach(handler -> this.handlers.put(handler.getCommandName(), handler)); } public void processCommand(Message message, TelegramLongPollingBot bot) { String commandName = extractCommandName(message); CommandHandler handler = this.handlers.get(commandName); if (handler != null) { handler.handle(message, bot); } else { SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(message.getChatId()); sendMessage.setText("Unknown command: " + commandName); try { bot.execute(sendMessage); } catch (TelegramApiException e) { e.printStackTrace(); } } } private String extractCommandName(Message message) { String text = message.getText(); if (text != null && text.startsWith("/")) { return text.split(" ")[0].substring(1); } return ""; } } BotConfig java package ru.dmt100.hhmonitorbotapplication.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.objects.Update; @Configuration @EnableScheduling public class BotConfig { @Value("${bot.token}") private String token; @Value("${bot.name}") private String name; @Bean public TelegramLongPollingBot telegramBot(CommandController commandController) { return new TelegramLongPollingBot(token) { @Override public String getBotUsername() { return name; } @Override public void onUpdateReceived(Update update) { if (update.hasMessage() && update.getMessage().hasText()) { commandController.processCommand(update.getMessage(), this); } } }; } } Заключение Эти изменения должны решить проблему с отправкой сообщений и сделать ваш бот более устойчивым к ошибкам. Убедитесь, что все зависимости и конфигурации настроены правильно, и протестируйте бота, чтобы убедиться, что он работает как ожидается. Если у вас возникнут дополнительные вопросы или ошибки, пожалуйста, дайте знать!
Leave a Comment