Spring Boot Telegram机器人编译正常但/start命令无响应求助
Telegram机器人无响应问题排查
我开发了一个基于Spring Boot的Telegram机器人,编译过程没有报错,但发送/start命令后机器人完全没有回复。application.properties文件放置在resources目录下,已配置通过@BotFather注册机器人时获取的名称和token。以下是项目代码,请帮忙排查问题:
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>io.proj3ct</groupId> <artifactId>SpringNIRBot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringNIRBot</name> <description>Demo project for Spring Boot</description> <properties> <java.version>19</java.version> <telegram.version>5.6.0</telegram.version> </properties> <dependencies> <dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots</artifactId> <version>${telegram.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
BotInitializer.java
package io.proj3ct.SpringNIRBot.config; import io.proj3ct.SpringNIRBot.service.TelegramBot; 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; @Component public class BotInitializer { @Autowired TelegramBot bot; @EventListener({ContextRefreshedEvent.class}) public void init() throws TelegramApiException { TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class); try { telegramBotsApi.registerBot(bot); }catch (TelegramApiException e) { } } }
SpringNirBotApplication.java
package io.proj3ct.SpringNIRBot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) public class SpringNirBotApplication { public static void main(String[] args) { SpringApplication.run(SpringNirBotApplication.class, args); } }
BotConfig.java
package io.proj3ct.SpringNIRBot.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("classpath:application.properties") public class BotConfig { @Value("${bot.name}") String botName; @Value("${bot.token}") String token; }
TelegramBot.java
package io.proj3ct.SpringNIRBot.service; import io.proj3ct.SpringNIRBot.config.BotConfig; import lombok.Getter; import lombok.Setter; 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; @Setter @Getter @Component public class TelegramBot extends TelegramLongPollingBot { final BotConfig config; public TelegramBot(BotConfig config) { super(); this.config = config; } @Override public String getBotUsername() { return config.getBotName(); } @Override public String getBotToken () { return config.getToken(); } @Override public void onUpdateReceived(Update update) { if(update.hasMessage() && update.getMessage().hasText()) { String messageText = update.getMessage().getText(); long chartId = update.getMessage().getChatId(); switch (messageText) { case "/start": startCommandReceived(chartId, update.getMessage().getChat().getFirstName()); break; default: sendMessage(chartId, "Sorry, command was not recognized"); } } } private void startCommandReceived(long chartId, String name) { String answer = "Hi, " + name + ",nice to meet you!"; sendMessage(chartId, answer); } private void sendMessage (long chartId, String textToSend) { SendMessage message = new SendMessage(); message.setChatId(String.valueOf(chartId)); message.setText(textToSend); try { execute(message); }catch (TelegramApiException e) { throw new RuntimeException(e); } } }
可能的错误点及修复方案
1. 异常被静默丢弃,无法定位注册失败原因
BotInitializer的init方法中,捕获TelegramApiException后没有任何处理,导致机器人注册失败时没有任何日志提示,无法排查问题。
修复:
添加异常日志输出,至少打印堆栈信息:
try { telegramBotsApi.registerBot(bot); } catch (TelegramApiException e) { e.printStackTrace(); // 也可以引入SLF4J日志框架打印更规范的日志 // log.error("Failed to register Telegram bot", e); }
2. 机器人父类初始化错误
TelegramBot的构造方法调用了super()无参构造,但TelegramLongPollingBot的无参构造不会设置token,导致底层API无法正确认证。
修复:
修改构造方法,将token传入父类:
public TelegramBot(BotConfig config) { super(config.getToken()); // 传入token初始化父类 this.config = config; }
3. 检查application.properties配置正确性
确保配置文件中的键名与BotConfig的@Value注解完全匹配,且机器人名称不带@前缀:
bot.name=你的机器人用户名(如MyTestBot,不要@MyTestBot) bot.token=你的机器人token
4. 网络环境限制
如果在国内环境,Telegram API需要翻墙才能访问,机器人无法与Telegram服务器建立连接就会收不到消息。可以测试能否访问https://api.telegram.org,若无法访问需配置代理。
5. 变量名拼写错误(不影响功能但需修正)
代码中将chatId写成了chartId,虽然不影响当前功能,但容易导致后续维护出错,建议修正为:
long chatId = update.getMessage().getChatId();
内容的提问来源于stack exchange,提问作者Альбина Блашбанова
相关产品推荐
相关产品推荐

