Untitled

 avatar
unknown
java
12 days ago
5.8 kB
1
Indexable
Вы правы, класс TelegramBot из библиотеки telegrambots не имеет метода sendMessage. Вместо этого вы должны использовать метод execute для отправки сообщений. Давайте исправим метод processCommand и добавим необходимые изменения для корректной отправки сообщений.

Исправленный метод processCommand
java
@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, TelegramBot 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 "";
    }
}
Дополнительные изменения
Обработка исключений при отправке сообщений: В методе processCommand добавлен блок try-catch для обработки TelegramApiException, который может возникнуть при выполнении метода execute.

Использование SendMessage: Создание объекта SendMessage и установка необходимых параметров (chatId и text).

Пример полного кода
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.api.objects.Update;
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.

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