springboot项目集成Telegram机器人

本文详细描述了如何在公司内部使用Telegram作为沟通工具时,通过创建TelegramBot并集成到自动化平台中,以便发送自动化报告通知的过程,包括创建Bot、添加Maven依赖、构建TelegramBotClient以及发送消息的方法。
摘要由CSDN通过智能技术生成

由于公司内部使用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");

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值