Telegram

简介

tio-utils 内置了 Telegram 工具类,用户可以通过它方便地发送消息到 Telegram 群组。

使用步骤

1. 创建 Telegram Bot

首先,您需要创建一个 Telegram Bot 并获取它的 API Token。以下是创建步骤:

  1. 在 Telegram 上与 @BotFather 进行对话。
  2. 输入 /newbot,然后按照提示创建一个新的 Bot。
  3. 创建完成后,您将收到一个 Bot API Token,请妥善记录并保管。
Done! Congratulations on your new bot. You will find it at t.me/your_bot_name.
Use this token to access the HTTP API:
<YourBotToken>
Keep your token secure and store it safely, it can be used by anyone to control your bot.

2. 获取群组的 Chat ID

  1. 将您的 Bot 添加到目标群组中。
  2. 通过访问 https://api.telegram.org/bot<YourBotToken>/getUpdates,获取最新的消息更新,找到群组的 Chat ID。
  3. 在返回的 JSON 数据中,找到 chat.id 对应的值并记录下来。
{
  "ok": true,
  "result": [
    {
      "update_id": 123456789,
      "message": {
        "message_id": 1,
        "from": {
          "id": 12345678,
          "is_bot": false,
          "first_name": "John",
          "username": "john_doe"
        },
        "chat": {
          "id": -987654321,
          "title": "MyGroup",
          "type": "group",
          "all_members_are_administrators": true
        },
        "date": 1624081865,
        "text": "Hello @your_bot_name",
        "entities": [
          {
            "offset": 0,
            "length": 19,
            "type": "mention"
          }
        ]
      }
    }
  ]
}

如果未获取到 chat.id,请按以下步骤解决:

  1. 在群组中发送一条消息并 @ 提到您的 Bot
    例如,发送 @YourBotUsername 测试消息

  2. 再次调用 getUpdates
    访问 https://api.telegram.org/bot<YourBotToken>/getUpdates,查看返回结果中是否包含您发送的消息。如果有,您应该能看到 chat 对象中的 chat.id 信息。

  3. 检查 Bot 的权限和隐私设置
    如果仍未获取到 chat.id,请尝试禁用 Bot 的隐私模式:

    • @BotFather 对话中发送 /mybots
    • 选择您的 Bot。
    • 选择 Bot Settings
    • 选择 Group Privacy
    • 将隐私模式设置为 Disabled,这样 Bot 就可以接收到群组中的所有消息。

3. 使用 Java 代码发送消息

以下是使用 Java 代码向 Telegram 群组发送消息的示例代码:

package com.litongjava.tio.utils.telegram;

import org.junit.Test;
import com.litongjava.tio.utils.http.ResponseVo;
import com.litongjava.tio.utils.json.JsonUtils;

public class TelegramTest {

  // Telegram Bot Token
  String BOT_TOKEN = "xxx";
  // Telegram Chat ID
  String CHAT_ID = "xxx";

  @Test
  public void testSend() {
    // 创建一个 Telegram bot 实例
    TelegramBot bot = new TelegramBot("mainBot", BOT_TOKEN);
    // 将 bot 添加到 Telegram 管理类中
    Telegram.addBot(bot);

    // 使用主 bot 发送消息
    ResponseVo responseVo = Telegram.use().sendMessage(CHAT_ID, "Hello, Telegram Group!");
    System.out.println(JsonUtils.toJson(responseVo));
  }

  @Test
  public void testFull() {
    // 创建一个 Telegram bot 实例
    TelegramBot bot = new TelegramBot("mainBot", BOT_TOKEN);
    // 将 bot 添加到 Telegram 管理类中
    Telegram.addBot(bot);

    // 可选:设置为主 bot(如果只使用一个 bot,可以省略这一步)
    Telegram.setMainBot("mainBot");

    // 使用主 bot 发送消息
    Telegram.use().sendMessage(CHAT_ID, "Hello, Telegram Group!");

    // 另外,您可以这样配置并发送消息:
    Telegram.config(botConfig -> botConfig.withToken("BOT_TOKEN"));
    Telegram.use().sendMessage(CHAT_ID, "Hello from another bot");
  }
}

集成到 Tio-Boot

配置类

import com.litongjava.jfinal.aop.annotation.AConfiguration;
import com.litongjava.jfinal.aop.annotation.AInitialization;
import com.litongjava.tio.boot.server.TioBootServer;
import com.litongjava.tio.utils.telegram.Telegram;
import com.litongjava.tio.utils.telegram.TelegramBot;

@AConfiguration
public class TelegramConfig {
  public static final String BOT_TOKEN = "xxx";
  public static final String CHAT_ID = "xxx";

  @AInitialization
  public void config() {
    // 创建一个 Telegram bot 实例
    TelegramBot bot = new TelegramBot(BOT_TOKEN);
    // 将 bot 添加到 Telegram 管理类中
    Telegram.addBot(bot);

    TioBootServer.me().addDestroyMethod(() -> {
      Telegram.clearBot();
    });
  }

}

Controller

import com.litongjava.tio.boot.http.TioRequestContext;
import com.litongjava.tio.http.common.HttpResponse;
import com.litongjava.tio.http.server.annotation.RequestPath;
import com.litongjava.tio.utils.http.ResponseVo;
import com.litongjava.tio.utils.telegram.Telegram;

@RequestPath("/api/v1/alarm")
public class AlarmController {
  public HttpResponse send(String text) {

    // 使用主 bot 发送消息
    ResponseVo responseVo = Telegram.use().sendMessage(TelegramConfig.CHAT_ID, text);
    String body = responseVo.getBody();
    int code = responseVo.getCode();

    HttpResponse response = TioRequestContext.getResponse();
    response.setStatus(code);
    response.setString(body);
    return response;
  }
}

返回的数据

调用成功后返回的数据

{
  "ok": true,
  "result": {
    "message_id": 7,
    "from": {
      "id": 7494961012,
      "is_bot": true,
      "first_name": "xx",
      "username": "xxx"
    },
    "chat": {
      "id": -4588913307,
      "title": "报警",
      "type": "group",
      "all_members_are_administrators": true
    },
    "date": 1724125945,
    "text": "text form api"
  }
}

总结

通过以上步骤,您可以轻松地在 Java 项目中集成 Telegram 机器人功能,实现向群组发送消息的功能。通过结合 Telegram 的强大 API,您可以进一步扩展机器人的功能,以满足更多业务需求。