@masterokh

Почему мой Telegram bot не реагирует на сообщения в принципе?

Я решил попробовать написать своего телеграмм бота, изучение данной тематики начал с уроков в интернете. И после написания пары простых классов, для обработки команды /start выяснил, что бот не реагирует вообще никак на мои команды. Я думал, что допустил ошибку, но полностью переписав и проверив код из разных видеоуроков (переписывал с разных источников):
1)https://www.youtube.com/watch?v=t9OTDHuF7_M&list=P...
2) https://habr.com/ru/articles/715384/
, понял что боты всё равно не реагируют на сообщения. Причем программы без проблем запускаются и работают.
64b477589436b183735805.png

Код программы:
package service;

import config.BotConfig;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
@Component
public class TelegramBot extends TelegramLongPollingBot {
private final BotConfig config;
public TelegramBot(BotConfig config){
this.config = config;
}
@Override
public void onUpdateReceived(Update update) {
if(update.hasMessage() && update.getMessage().hasText()){
long chatId = update.getMessage().getChatId();
switch (update.getMessage().getText()) {
case "/start":
StartCommandReceived(chatId, update.getMessage().getChat().getFirstName());
break;
default: sendMessage(chatId, "Sorry, command was not recognized");
}

}

}

@Override
public String getBotUsername() {
return config.getUsername();
}
@Override
public String getBotToken(){
return config.getToken();
}

private void StartCommandReceived(long chatId, String username){
String answer = "Hi," + username + "welcome to this bot";
sendMessage(chatId, answer);
}

private void sendMessage(long chatId, String answer){
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId);
sendMessage.setText(answer);
try {
execute(sendMessage);
}catch (TelegramApiException exception){

}
}
}

-------------------------------------------------------------------

package config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
import service.TelegramBot;

@Component
public class BotInitializer {
@Autowired
TelegramBot telegramBot;

@EventListener(ContextRefreshedEvent.class)
public void init() throws TelegramApiException{
TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
try{
telegramBotsApi.registerBot(telegramBot);
}catch (TelegramApiException exception){

}
}
}

-------------------------------------------------------------------

package config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@Data
@PropertySource("application.properties")
public class BotConfig {
@Value("${bot.name}")
String username;
@Value("${bot.token}")
String token;
}

-------------------------------------------------------------------

package com.example.springdemostudybot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringDemoStudyBotApplication {

public static void main(String[] args) {
SpringApplication.run(SpringDemoStudyBotApplication.class, args);
}

}

-------------------------------------------------------------------

а это в application.properties

bot.name = SpringDemoStudyBot
bot.token = токен здесь есть
  • Вопрос задан
  • 289 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
Bell Integrator Ульяновск
До 400 000 ₽
07 мая 2024, в 18:09
2000 руб./за проект
07 мая 2024, в 17:40
300 руб./за проект