要将 Telegram Bot 与 Spring Boot 集成,你首先需要确保你的 Maven 项目已经正确配置,并且包含必要的依赖项。你已经正确地设置了 Spring Boot 和 Telegram Bots API 的依赖项。接下来,我将展示如何编写一个基本的 Telegram Bot 配置类,并创建一个简单的 Bot 类来处理消息。
首先,确保你的 application.yml
文件配置正确。你已经有了一个基本的配置,但通常 Telegram Bot 不需要配置 host
和 port
,除非你打算自己实现一个 Webhook 服务器来接收 Telegram 的更新。对于大多数用例,使用长轮询(Long Polling)或 Webhook 就足够了。这里,我们将使用长轮询,因此你可以简化 application.yml
文件:
yaml复制代码
bot: | |
botname: xxxBot | |
token: asdadsasd:xxxx-GdaY4 |
接下来,是你的 BotConfig
类,它使用 @ConfigurationProperties
注解来绑定 application.yml
中的属性:
java复制代码
@Data | |
@Configuration | |
@ConfigurationProperties(prefix = "bot") | |
public class BotConfig { | |
private String botname; | |
private String token; | |
// 如果有需要,可以在这里添加更多的配置属性 | |
} |
然后,你需要创建一个继承自 TelegramLongPollingBot
的类来实际处理 Telegram 的消息。这个类将包含你的主要逻辑,比如如何响应不同类型的消息。
java复制代码
import org.telegram.telegrambots.ApiContextInitializer; | |
import org.telegram.telegrambots.bots.TelegramLongPollingBot; | |
import org.telegram.telegrambots.meta.TelegramBotsApi; | |
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; | |
import org.telegram.telegrambots.meta.api.objects.Update; | |
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Component; | |
@Component | |
public class MyTelegramBot extends TelegramLongPollingBot { | |
@Autowired | |
private BotConfig botConfig; | |
public void onUpdateReceived(Update update) { | |
if (update.hasMessage() && update.getMessage().hasText()) { | |
String messageText = update.getMessage().getText(); | |
// 这里添加你的逻辑来处理消息 | |
SendMessage message = new SendMessage() | |
.setChatId(update.getMessage().getChatId()) | |
.setText("Received: " + messageText); | |
try { | |
execute(message); | |
} catch (TelegramApiException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
@PostConstruct | |
public void startBot() { | |
ApiContextInitializer.init(); | |
TelegramBotsApi botsApi = new TelegramBotsApi(); | |
try { | |
botsApi.registerBot(this); | |
} catch (TelegramApiException e) { | |
e.printStackTrace(); | |
} | |
} | |
@PreDestroy | |
public void stopBot() { | |
TelegramBotsApi botsApi = new TelegramBotsApi(); | |
botsApi.deregisterBot(this); | |
} | |
} |
注意几个关键点:
@Component
注解使 Spring 能够管理这个 Bot 实例。onUpdateReceived
方法是处理接收到的更新的地方。@PostConstruct
和@PreDestroy
注解用于在 Spring 容器启动和停止时注册和注销 Bot。
最后,确保你的 Spring Boot 应用程序能够加载并启动这个 Bot。如果你使用的是 Spring Boot 的自动配置,并且 MyTelegramBot
已经被 Spring 管理,那么它将在启动时自动注册。
这样,你就完成了将 Telegram Bot 与 Spring Boot 的基本集成。现在,你可以扩展 MyTelegramBot
类来处理更复杂的消息类型和功能。