欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > springboot 对接Telegram发送消息

springboot 对接Telegram发送消息

2024/10/23 23:20:04 来源:https://blog.csdn.net/luckywuxn/article/details/143025757  浏览:    关键词: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**********"; // 替换为你的机器人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();}}
}

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com