springboot项目集成Telegram机器人
·
由于公司内部使用telegram作为沟通工具,而目前的自动化平台不支持Telegram通知,因此需要集成Telegram机器人发送一些自动化报告通知,在此记录一下过程
1.创建Telegram Bot
首先需要在telegram中创建一个bot,在左上角搜索框中搜索“BotFather”,注意选择带有官方认证的那个账号,以防被骗

之后点击进入对话,发送/newbot创建新的机器人,并根据提示设置机器人的name和username,设置完成后会返回机器人的token

2.集成Bot
2.1.添加maven依赖
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>6.8.0</version>
</dependency>
2.2.创建TelegramBotClient
@Slf4j
public class TelegramBotClient extends TelegramLongPollingBot {
private String token;
private String userName;
private static TelegramBotClient instance;
private TelegramBotClient(DefaultBotOptions botOptions, String token, String userName){
super(botOptions);
this.token = token;
this.userName = userName;
}
public static TelegramBotClient getInstance(DefaultBotOptions botOptions, String token, String userName){
if (instance == null){
instance = new TelegramBotClient(botOptions, token, userName);
}
return instance;
}
/**
* 接收消息
* @param update
*/
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage()){
Message message = update.getMessage();
String text = message.getText();
Chat chat = message.getChat();
String chatType = chat.getType();
LogUtil.info("接收到{}消息:{}", chatType, text);
if ("private".equals(chatType)){
//私聊
Long userId = chat.getId();
if ("chatId".equals(text)){
sendMsg(String.valueOf(userId), String.valueOf(userId));
}
}else if ("group".equals(chatType) || "supergroup".equals(chatType)){
//群聊
Long chatId = chat.getId();
if (("@" + userName + " chatId").equals(text)){
sendMsg(String.valueOf(chatId), String.valueOf(chatId));
}
}
}
}
/**
* 发送消息
* @param text
* @param chatId
*/
public void sendMsg(String text, String chatId){
SendMessage response = new SendMessage();
response.setChatId(chatId);
response.setText(text);
try {
execute(response);
}catch (Exception ex){}
}
@Override
public String getBotUsername() {
return this.userName;
}
@Override
public String getBotToken() {
return this.token;
}
}
在这个client中,我们设置了获取chatId的规则,私聊时给bot发送chatId即会回复当前聊天的chatId,群聊时发送@bot chatId即会回复当前群聊的chatId

2.3.初始化并注册client
@Component
public class TelegramSender {
public static TelegramBotClient telegramBotClient;
private static final String TOKEN = "YOUR_TOKEN";
private static final String USERNAME = "YOUR_USERNAME";
//使用@PostConstruct注解,会在项目启动的时候执行该方法
@PostConstruct
public void init(){
try {
DefaultBotOptions defaultBotOptions = new DefaultBotOptions();
TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
telegramBotClient = TelegramBotClient.getInstance(defaultBotOptions, TOKEN, USERNAME);
botsApi.registerBot(telegramBotClient);
}catch (Exception ex){
LoggerUtil.error("TelegramBot初始化失败", ex);
}
}
}
注意每个bot同时只能注册一次,否则会报错该bot已经注册
2.4.发送消息
发送消息时需要获取聊天的chatId,上面我们已经设置好如何获取chatId,在需要发送消息的地方调用下面的方法即可发送
telegramBotClient.sendMsg("YOUR_MSG", "CHAT_ID");
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)