基于springboot在【pom】中添加
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>5.3.0</version>
</dependency>
初始化自己的机器人类并注册
@Component
public class SystemInit implements ApplicationRunner {
@Autowired
private MyTelegramBot myTelegramBot;
@Override
@SneakyThrows
public void run(ApplicationArguments args) throws Exception {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
telegramBotsApi.registerBot(myTelegramBot);
}
}
其次实现该类
public class MyTelegramBot extends TelegramLongPollingBot {
SendMessage message = new SendMessage();
@Override
public String getBotUsername() {
return username;
}
@Override
public String getBotToken() {
return token;
}
@SneakyThrows
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
Long chatId = msg.getChatId();
String content = msg.getText();
message.setChatId(chatId.toString());
message.setText(content);
sendMessage(message);
}
}
//发送消息
private void sendMessage(SendMessage message) {
try {
execute(message); // Call method to send the message
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
其中username和token换上自己申请的,服务运行在可翻q的服务器上,给机器人发消息就会收到回复,前提是你的telegram能收到翻q信息。