java集成telegram机器人

java集成telegram机器人

最近项目需要集成telegram机器人,来实现消息推送功能,以此记录下。

1.创建telegram账号

没有账号的可以去某宝上买一个,千万不要用自己的手机号+86去注册,你懂得。

2. 打开@BotFather对话创建机器人获取token

在搜索框里的输入@BotFather后进入对话框会看到如下界面

然后发送/start开始对话

发送/newbot创建机器人

发送机器人的name和 username,其中username有要求,需要以xxx_bot命名

以下就拿到机器人对应的token,后面我们将通过token给机器人发送消息,token不需要泄露出去了。

3.获取chatId会话ID

telegram中每个用户、群组、频道都是一个会话,会话ID就是chatId,通过会话ID和token就可以给机器人发送消息了。

通过搜索@getidsbot用户然后发送/start获取会话id

当然目前获取的为当前用户的会话ID,如果需要将消息通知到群里面,操作也是一样的,我们只需要将机器人和@getidsbot都拉进群里进行,这样拿到群的会话id。

4.发送请求

telegram官方有对应的api点击查看,将下方token、chatId、message替换即可。

javascript 复制代码
https://api.telegram.org/bot${token}/sendMessage?chat_id=[chatId]&text=${message}

或者直接通过浏览器访问,用于测试

json 复制代码
{
  "ok": true,
  "result": {
    "message_id": 9,
    "from": {
      "id": 7662234082,
      "is_bot": true,
      "first_name": "test01",
      "username": "pitiless223_bot"
    },
    "chat": {
      "id": -4614960807,
      "title": "z & test01",
      "type": "group",
      "all_members_are_administrators": true,
      "accepted_gift_types": {
        "unlimited_gifts": false,
        "limited_gifts": false,
        "unique_gifts": false,
        "premium_subscription": false
      }
    },
    "date": 1746695605,
    "text": "hello"
  }
}

5.java代码实现

github上直接有集成好了的插件java-telegram-bot-api

配置maven依赖

xml 复制代码
<dependency>
  <groupId>com.github.pengrad</groupId>
  <artifactId>java-telegram-bot-api</artifactId>
  <version>8.3.0</version>
</dependency>

以下是我封装好的serve

java 复制代码
package com.ruoyi.system.service.impl;

import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.request.SendPhoto;
import com.pengrad.telegrambot.response.SendResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TelegramBotServiceImpl implements UpdatesListener {

    /**
     * token
     */
    @Value("${custom.telegram_bot.token}")
    private String telegramBotToken;

    /**
     * bot
     */
    private TelegramBot bot;

    @Override
    public int process(List<Update> updates) {
        updates.forEach(update -> {
            log.info("机器人收到消息 -> {}", update);
        });
        return UpdatesListener.CONFIRMED_UPDATES_ALL;
    }

    @PostConstruct
    public void run() {
        // Create your bot passing the token received from @BotFather
        this.bot = new TelegramBot(this.telegramBotToken);
        // Register for updates
        this.bot.setUpdatesListener(this);
    }

    /**
     * 发送消息
     *
     * @param type   消息类型
     * @param chatId 会话ID
     * @param text   消息内容
     */
    public void sendMessage(Byte type, long chatId, String text) {
        SendResponse response;
        if (type == 1) {
            // 图片
            response = bot.execute(new SendPhoto(chatId, text));
        } else {
            // 文本
            response = bot.execute(new SendMessage(chatId, text));
        }
        log.info("发送消息 -> {}", response);
    }

    public void close() {
        this.bot.removeGetUpdatesListener();
    }

}

使用时直接调用即可

java 复制代码
TelegramBotServiceImpl.sendMessage(Byte.valueOf("2"), 6576654010L, "请求测试")
相关推荐
浮尘笔记2 小时前
Java Snowy框架CI/CD云效自动化部署流程
java·运维·服务器·阿里云·ci/cd·自动化
一直不明飞行9 小时前
Java的equals(),hashCode()应该在什么时候重写
java·开发语言·jvm
REDcker9 小时前
有限状态机与状态模式详解 FSM建模Java状态模式与C++表驱动模板实践
java·c++·状态模式
2301_803934619 小时前
Go语言如何做网络爬虫_Go语言爬虫开发教程【指南】
jvm·数据库·python
WL_Aurora9 小时前
Python爬虫实战(六):新发地蔬菜价格数据采集.
爬虫·python
盲敲代码的阿豪9 小时前
Python 入门基础教程(爬虫前置版)
开发语言·爬虫·python
你的保护色9 小时前
【无标题】
java·服务器·网络
basketball61610 小时前
C++ 构造函数完全指南:从入门到进阶
java·开发语言·c++
weixin1997010801610 小时前
[特殊字符] 智能数据采集:数字化转型的“数据石油勘探队”(附Python实战源码)
开发语言·python
淘矿人10 小时前
Claude辅助DevOps实践
java·大数据·运维·人工智能·算法·bug·devops