Bootstrap

springboot 对接Telegram发送消息

官方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**********"; // 替换为你的机器人token
        String apiUrl = "https://api.telegram.org/bot" + botToken + "/sendMessage";
        // 构建请求URL
        String url = UriComponentsBuilder.fromHttpUrl(apiUrl)
                .build()
                .toUriString();
        // 设置请求头,确保字符编码为UTF-8
        HttpHeaders 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 密钥

    @Override
    public void onUpdateReceived(Update update) {
        if (update.hasMessage() && update.getMessage().hasText()) {
            String chatId = update.getMessage().getChatId().toString();
            log.info("onUpdateReceived chatId {}",chatId);
        }
    }

    @Override
    public String getBotUsername() {
        return BOT_NAME;
    }

    @Override
    public String getBotToken() {
        return BOT_TOKEN;
    }

    @PostConstruct
    public void init() {
        log.info("MyTelegramBot init");
        try {
            TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
            botsApi.registerBot(this);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

3、机器人中随便发送一个消息,查看chat_id

;