官方maven包项目
https://repo.maven.apache.org/maven2/org/telegram/
官方github仓库
https://github.com/rubenlagus
发送消息demo代码
@PostMapping("/test")public void test(@RequestParam("chatId") String chatId,@RequestParam("messageText") String messageText) throws Exception {String botToken = "7808144057:AAEkkjF**********"; // 替换为你的机器人tokenString apiUrl = "https://api.telegram.org/bot" + botToken + "/sendMessage";// 构建请求URLString url = UriComponentsBuilder.fromHttpUrl(apiUrl).build().toUriString();// 设置请求头,确保字符编码为UTF-8HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);// 构建请求体String requestBody = "{\"chat_id\":\"" + chatId + "\",\"text\":\"" + messageText + "\"}";// 创建HttpEntity对象HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);// 创建RestTemplate对象RestTemplate restTemplate = new RestTemplate();// 发送POST请求String response = restTemplate.postForObject(url, entity, String.class);}
获取chatId
1、引入依赖
<dependency><groupId>org.telegram</groupId><artifactId>telegrambots</artifactId><version>6.8.0</version></dependency>
2、添加代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;import javax.annotation.PostConstruct;@Slf4j
@Component
public class MyTelegramBot extends TelegramLongPollingBot {private static String BOT_NAME = "PeterWu_bot"; //TG Bot 机器人名称private static String BOT_TOKEN = "7808144057:AAEkkjF**********";//TG Bot 密钥@Overridepublic void onUpdateReceived(Update update) {if (update.hasMessage() && update.getMessage().hasText()) {String chatId = update.getMessage().getChatId().toString();log.info("onUpdateReceived chatId {}",chatId);}}@Overridepublic String getBotUsername() {return BOT_NAME;}@Overridepublic String getBotToken() {return BOT_TOKEN;}@PostConstructpublic void init() {log.info("MyTelegramBot init");try {TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);botsApi.registerBot(this);} catch (TelegramApiException e) {e.printStackTrace();}}
}