Skip to content

定时推送 ​

在本节中,我们将指导您如何为 Telegram 翻译机器人添加定时推送功能。具体包括创建一个 Telegram 群组,并配置机器人定时向该群组推送指定的文章。通过这种方式,您可以实现定期分享内容,提高群组的活跃度和用户参与度。

步骤概述 ​

  1. 创建一个 Telegram 群组
  2. 配置机器人加入群组
  3. 实现定时推送功能
  4. 测试与验证

步骤详解 ​

1. 创建一个 Telegram 群组 ​

首先,您需要在 Telegram 中创建一个新的群组,用于接收机器人定时推送的文章。

操作步骤:

  1. 打开 Telegram 应用。
  2. 点击左上角的“三条横线”菜单图标,选择“新建群组”。
  3. 从联系人列表中选择一个或多个成员(您可以在后续步骤中添加机器人)。
  4. 点击“下一步”,为群组命名,例如“每日文章推送”。
  5. 完成群组创建后,记下群组的名称和链接,以便后续配置。

2. 配置机器人加入群组 ​

为了让机器人能够向群组发送消息,您需要将机器人添加到群组中,并授予相应的权限。

操作步骤:

  1. 在 Telegram 中,进入您刚创建的群组。
  2. 点击群组名称,进入群组信息页面。
  3. 选择“添加成员”,搜索并选择您的机器人(例如:litongjava_bot)。
  4. 将机器人添加到群组后,确保它具有发送消息的权限。

获取群组的 Chat ID

为了让机器人能够向群组发送消息,您需要获取群组的 Chat ID。由于使用 MTProto 协议,获取 Chat ID 的方式稍有不同。

方法一:通过日志获取

  1. 启动您的 Telegram Translate Bot。
  2. 在群组中发送一条消息。
  3. 查看服务器日志,查找该消息事件中的 chatId。

方法二:使用专用命令

您可以为机器人添加一个命令,如 get_chat_id,用于获取当前聊天的 Chat ID。

java
  private Mono<Message> processAndSendMessage(Chat chat, Message message) {
    String text = message.getContent();

    if (text.equals("/get_chat_id")) {
      Id id = chat.getId();
      Mono<Message> monoMessage = chat.sendMessage("Chat ID: " + id.asLong());
      return monoMessage;
    }

添加上述代码后,重新启动机器人,并在群组中发送 get_chat_id,机器人将回复群组的 Chat ID。 不用@机器人,机器人 会自动获取群中的所有消息

3. 实现定时推送功能 ​

为了实现定时向群组推送文章,我们将使用 Java 的 ScheduledExecutorService 来安排定时任务。同时,您需要编写代码来读取或指定要推送的文章内容,并通过 MTProto 客户端发送消息。 使用 Java 内置的 ScheduledExecutorService,无需额外依赖。

3.1 编写定时推送配置类 ​

java
package nexus.io.gpt.translator.config;

import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import nexus.io.annotation.AConfiguration;
import nexus.io.annotation.Initialization;
import nexus.io.gpt.translator.services.ScheduledPushService;
import nexus.io.jfinal.aop.Aop;

import lombok.extern.slf4j.Slf4j;

@AConfiguration
@Slf4j
public class SchedulerConfig {

  private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

  @Initialization
  public void startScheduledTask() {
    ScheduledPushService scheduledPushService = Aop.get(ScheduledPushService.class);
    // 设定任务在每天的固定时间执行,例如每天上午9点
    long initialDelay = computeInitialDelay(9, 00); // 9:00 AM
    long period = TimeUnit.DAYS.toSeconds(1);

    scheduler.scheduleAtFixedRate(scheduledPushService::pushArticleToGroup, initialDelay, period, TimeUnit.SECONDS);
    log.info("定时推送任务已启动,每天上午9点执行。");
  }

  /**
   * 计算从当前时间到目标时间的初始延迟(秒)
   */
  private long computeInitialDelay(int targetHour, int targetMinute) {
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime nextRun = now.withHour(targetHour).withMinute(targetMinute).withSecond(0).withNano(0);
    if (now.compareTo(nextRun) > 0) {
      nextRun = nextRun.plusDays(1);
    }
    return java.time.Duration.between(now, nextRun).getSeconds();
  }
}

3.2 编写定时推送业务类 ​

创建一个新的 Java 类 ScheduledPushService,负责管理定时任务并向群组推送文章。

java
package nexus.io.gpt.translator.services;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import nexus.io.gpt.translator.client.TelegramClient;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
import telegram4j.core.object.Message;
import telegram4j.core.object.chat.Chat;
import telegram4j.core.spec.SendMessageSpec;
import telegram4j.core.util.Id;

@Slf4j
public class ScheduledPushService {

  // 群组的 Chat ID,请在前面步骤中获取
  private final Long groupChatId = 4679160257L;

  /**
   * 推送文章到群组
   */
  public void pushArticleToGroup() {
    String article = getDailyArticle();
    try {
      sendMessageToGroup(article).subscribe();
      log.info("成功向群组推送文章。");
    } catch (Exception e) {
      log.error("推送文章到群组时发生异常", e);
    }
  }

  /**
   * 获取当天要推送的文章
   *
   * @return 文章内容
   */
  public String getDailyArticle() {
    // 示例:根据日期生成文章标题
    LocalDate today = LocalDate.now();
    String formattedDate = today.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    String article = String.format("📅 **每日一文** - %s\n\n这里是今天的文章内容。请大家阅读并讨论!", formattedDate);
    return article;
  }

  /**
   * 通过 MTProto 客户端发送消息到指定群组
   */
  private Mono<Message> sendMessageToGroup(String message) {
    Id chatId = Id.ofChat(groupChatId);
    Mono<Chat> monoChat = TelegramClient.client.getChatById(chatId);
    Mono<Message> monoMessage = monoChat.flatMap(chat -> chat.sendMessage(SendMessageSpec.of(message)));
    return monoMessage;
  }
}

代码解析:

  1. ScheduledExecutorService:用于管理定时任务。这里我们创建了一个单线程的调度器。

  2. startScheduledTask() 方法:配置定时任务,使其每天上午 9 点执行 pushArticleToGroup 方法。

  3. computeInitialDelay() 方法:计算当前时间到下一个目标时间(如 9:00 AM)的延迟,以确保任务在正确的时间开始。

  4. pushArticleToGroup() 方法:调用 获取当天的文章,并通过 sendMessageToGroup 方法发送到群组。

  5. sendMessageToGroup() 方法:使用 MTProto 客户端向指定群组发送消息。

  6. getDailyArticle() 方法:当前示例中,文章内容是动态生成的,包含当天的日期。您可以根据实际需求,修改此方法以从数据库或其他来源获取真实的文章内容。

4. 测试与验证 ​

完成上述配置后,您需要测试定时推送功能,确保机器人能够按预期向群组推送文章。

4.1 启动机器人 ​

在 TelegramTranslateBot 获取 client 并添加到 TelegramClient.client 中

java
package nexus.io.gpt.translator.config;

import java.nio.file.Path;
import java.time.Duration;
import java.util.function.Function;

import nexus.io.annotation.AConfiguration;
import nexus.io.annotation.Initialization;
import nexus.io.gpt.translator.client.TelegramClient;
import nexus.io.gpt.translator.predicate.UserPredicate;
import nexus.io.gpt.translator.tgfunc.TranslateFunction;
import nexus.io.tio.boot.server.TioBootServer;
import nexus.io.tio.utils.environment.EnvUtils;

import lombok.extern.slf4j.Slf4j;
import reactor.util.retry.Retry;
import telegram4j.core.MTProtoBootstrap;
import telegram4j.core.MTProtoTelegramClient;
import telegram4j.core.event.domain.message.SendMessageEvent;
import telegram4j.mtproto.RpcException;
import telegram4j.mtproto.store.FileStoreLayout;
import telegram4j.mtproto.store.StoreLayoutImpl;

@Slf4j
@AConfiguration
public class TelegramTranslateBot {

  @Initialization
  public void config() {
    // 从环境变量获取 Telegram API 配置信息
    int apiId = EnvUtils.getInt("telegram.api.id");
    String apiHash = EnvUtils.getStr("telegram.api.hash");
    String botAuthToken = EnvUtils.getStr("telegram.bot.auth.token");

    String botId = botAuthToken.split(":")[0];
    // 创建并连接 MTProto Telegram 客户端
    MTProtoBootstrap bootstrap = MTProtoTelegramClient.create(apiId, apiHash, botAuthToken);

    StoreLayoutImpl storeLayoutImpl = new StoreLayoutImpl(Function.identity());
    FileStoreLayout storeLayout = new FileStoreLayout(storeLayoutImpl, Path.of("t4j-bot_" + botId + ".bin"));
    bootstrap.setStoreLayout(storeLayout);

    MTProtoTelegramClient client = bootstrap.connect().block();
    if (client == null) {
      log.error("Failed to connect to Telegram MTProto client.");
      return;
    }

    // 获取自己的id
    long selfId = client.getSelfId().asLong();
    log.info("self id:{}", selfId);

    // 配置事件监听器:接收 SendMessageEvent,过滤用户消息,并应用翻译功能
    client.on(SendMessageEvent.class)
        //
        .filter(new UserPredicate(selfId)::test).flatMap(new TranslateFunction()::apply)
        //
        .delayElements(Duration.ofSeconds(1)) // 每秒最多发送一条消息
        //
        .doOnError(e -> log.error("处理消息时发生错误", e))
        //
        .retryWhen(Retry.backoff(5, Duration.ofSeconds(1)).filter(e -> e instanceof RpcException))
        //
        .subscribe();

    TelegramClient.client = client;

    // 防止主线程阻塞,监控客户端断开连接
    //    TioThreadUtils.submit(() -> {
    //      client.onDisconnect().block();
    //      log.info("Telegram client disconnected.");
    //    });

    // 在服务器关闭时,断开 Telegram 客户端连接
    HookCan.me().addDestroyMethod(client::disconnect);

    log.info("Telegram MTProto client configured and connected.");
  }
}
java
package nexus.io.gpt.translator.client;

import telegram4j.core.MTProtoTelegramClient;

public class TelegramClient {

  public static MTProtoTelegramClient client = null;

}

4.2 手动触发推送任务(可选) ​

为了验证推送功能,我们编辑一个 Controller 测试推送代码

java
package nexus.io.gpt.translator.controller;

import nexus.io.annotation.RequestPath;
import nexus.io.gpt.translator.services.ScheduledPushService;
import nexus.io.jfinal.aop.Aop;
import nexus.io.model.body.RespBodyVo;

@RequestPath("/test")
public class TestController {

  public RespBodyVo push() {
    Aop.get(ScheduledPushService.class).pushArticleToGroup();
    return RespBodyVo.ok();
  }
}

保存修改并重新启动机器人,观察群组中是否收到推送的文章消息。

将机器人添加到群里后自动获取 ChatId ​

将机器人添加到群里后 机器人会收到一个 SendMessageEvent,event message action is MessageActionChatAddUser,具体内容如下

log
SendMessageEvent{
	message=Message{data=Variant2{t2=MessageService#2b085862{flags=100000000, id=1698, fromId=PeerUser#59511722{userId=6276672963}, peerId=PeerChat#36c6019a{chatId=4679160257}, replyTo=null, date=1733599167, action=MessageActionChatAddUser#15cefd00{users=[7847170133]}, ttlPeriod=null}}},

	chat=GroupChat{minData=BaseChat#41cbf256{flags=1000000000000000000, id=4679160257, title='telegram_dev_test', photo=ChatPhotoEmpty#37c1011c{}, participantsCount=2, date=1733599148, version=2, migratedTo=null, adminRights=null, defaultBannedRights=ChatBannedRights#9f120418{flags=0, untilDate=2147483647}}, fullData=null},

	author=User{minData=BaseUser#abb5f120{flags=10010000000000000001101011, flags2=10000, id=6276672963, accessHash=-6745242867060598026, firstName='', lastName='null', username='', phone='null', photo=BaseUserProfilePhoto#82d1f706{flags=0, photoId=5129962608709971087, strippedThumb=null, dcId=1}, status=UserStatusRecently#e26f42f1{}, botInfoVersion=null, restrictionReason=null, botInlinePlaceholder='null', langCode='zh-hans', emojiStatus=null, usernames=null, storiesMaxId=null}, fullData=null}
}

如果机器人收到用户发送的消息,event message 没有 action 对象

SendMessageEvent{
	message=Message{data=Variant2{t1=BaseMessage#38116ee0{flags=100000000, id=1702, fromId=PeerUser#59511722{userId=6276672963}, peerId=PeerChat#36c6019a{chatId=4679160257}, fwdFrom=null, viaBotId=null, replyTo=null, date=1733622976, message='get_chat_id', media=null, replyMarkup=null, entities=null, views=null, forwards=null, replies=null, editDate=null, postAuthor='null', groupedId=null, reactions=null, restrictionReason=null, ttlPeriod=null}}},

	chat=GroupChat{minData=BaseChat#41cbf256{flags=1000000000000000000, id=4679160257, title='telegram_dev_test', photo=ChatPhotoEmpty#37c1011c{}, participantsCount=2, date=1733599148, version=2, migratedTo=null, adminRights=null, defaultBannedRights=ChatBannedRights#9f120418{flags=0, untilDate=2147483647}}, fullData=null},

	author=User{minData=BaseUser#abb5f120{flags=10010000000000000001101011, flags2=10000, id=6276672963, accessHash=-6745242867060598026, firstName='', lastName='null', username='', phone='null', photo=BaseUserProfilePhoto#82d1f706{flags=0, photoId=5129962608709971087, strippedThumb=null, dcId=1}, status=UserStatusRecently#e26f42f1{}, botInfoVersion=null, restrictionReason=null, botInlinePlaceholder='null', langCode='zh-hans', emojiStatus=null, usernames=null, storiesMaxId=null}, fullData=null}
}

推送消息到超级群 ​

问题描述 ​

我自己创建的群,我可以推送消息,但是别人创建的群却不行 1.我创建的群是 groupChat 2.别人创建是 SupergroupChat

SupergroupChat 获取到的消息如下,该如何解决

SendMessageEvent{

	message=Message{data=Variant2{t1=BaseMessage#38116ee0{flags=100000010, id=55, fromId=PeerUser#59511722{userId=user_id}, peerId=PeerChannel#a2a5371e{channelId=chat_id}, fwdFrom=null, viaBotId=null, replyTo=null, date=1733626097, message='Chat ID: chat_id', media=null, replyMarkup=null, entities=null, views=null, forwards=null, replies=null, editDate=null, postAuthor='null', groupedId=null, reactions=null, restrictionReason=null, ttlPeriod=null}}},

	chat=SupergroupChat{minData=Channel#83259464{flags=1000110000100000000, flags2=0, id=chat_id, accessHash=-2695782318103141212, title='审核群', username='null', photo=ChatPhotoEmpty#37c1011c{}, date=1733625678, restrictionReason=null, adminRights=ChatAdminRights#5fb224d5{flags=1101010111001}, bannedRights=null, defaultBannedRights=ChatBannedRights#9f120418{flags=0, untilDate=2147483647}, participantsCount=null, usernames=null}, fullData=null},

	author=User{minData=BaseUser#abb5f120{flags=10000000001100010000001011, flags2=10010, id=user_id, accessHash=-4262855346709871929, firstName='my-translator', lastName='null', username='litongjava_bot', phone='null', photo=null, status=null, botInfoVersion=1, restrictionReason=null, botInlinePlaceholder='null', langCode='null', emojiStatus=null, usernames=null, storiesMaxId=null}, fullData=null}

}

问题分析 ​

在 Telegram 中,普通群组(GroupChat) 和 超级群组(SupergroupChat) 在 MTProto 协议中有不同的处理方式。具体来说,超级群组 被视为 频道(Channel),因此需要使用不同的方法来获取和使用其 Chat ID。

以下是详细的解决方案,帮助您在超级群组中实现定时推送功能。

  1. 群组类型不同:

    • 普通群组(GroupChat) 使用 PeerChat,其 Chat ID 是一个较大的数值(例如:4679160257)。
    • 超级群组(SupergroupChat) 使用 PeerChannel,其 Channel ID 是一个较小的数值(例如:2431959548)。
  2. ID 构建方式不同:

    • 对于 普通群组,需要使用 Id.ofChat(groupChatId)。
    • 对于 超级群组,需要使用 Id.ofChannel(channelId)。

因此,当您向超级群组发送消息时,必须使用 Channel ID 并通过 Id.ofChannel 方法构建 Id 对象,而不是使用 Id.ofChat。

修改后的代码 ​

java
package nexus.io.gpt.translator.services;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import nexus.io.gpt.translator.client.TelegramClient;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
import telegram4j.core.object.Message;
import telegram4j.core.spec.SendMessageSpec;
import telegram4j.core.util.Id;

@Slf4j
public class ScheduledPushService {

  // 普通群组的 Chat ID
  private final Long groupChatId = 8888888L;

  // 超级群组的 Channel ID
  private final Long supergroupChannelId = 999999999L;

  /**
   * 推送文章到群组和超级群组
   */
  public void pushArticleToGroup() {
    SendMessageSpec messageSpec = SendMessageSpec.of(getDailyArticle());

    try {
      // 推送到超级群组
      sendMessageToGroup(supergroupChannelId, true, messageSpec).doOnSuccess(msg -> log.info("成功向超级群组推送文章。")).doOnError(e -> log.error("向超级群组推送文章时发生异常", e)).subscribe();

      // 推送到普通群组
      sendMessageToGroup(groupChatId, false, messageSpec).doOnSuccess(msg -> log.info("成功向普通群组推送文章。")).doOnError(e -> log.error("向普通群组推送文章时发生异常", e)).subscribe();

      log.info("推送任务已完成。");
    } catch (Exception e) {
      log.error("推送文章到群组时发生异常", e);
    }
  }

  /**
   * 获取当天要推送的文章
   *
   * @return 文章内容
   */
  public String getDailyArticle() {
    LocalDate today = LocalDate.now();
    String formattedDate = today.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    String article = String.format("📅 **每日一文** - %s\n\n这里是今天的文章内容。请大家阅读并讨论!", formattedDate);
    return article;
  }

  /**
   * 通过 MTProto 客户端发送消息到指定群组或超级群组
   *
   * @param id        群组 ID 或频道 ID
   * @param isChannel 是否为频道(超级群组)
   * @param messageSpec 消息规范
   * @return Mono<Message>
   */
  private Mono<Message> sendMessageToGroup(Long id, boolean isChannel, SendMessageSpec messageSpec) {
    Id chatId;
    if (isChannel) {
      chatId = Id.ofChannel(id);
    } else {
      chatId = Id.ofChat(id);
    }

    return TelegramClient.client.getChatById(chatId).flatMap(chat -> {
      log.info("尝试发送消息到 {}: {}", isChannel ? "超级群组" : "普通群组", id);
      return chat.sendMessage(messageSpec).doOnNext(msg -> log.info("消息发送成功: {}", msg)).doOnError(e -> log.error("消息发送失败: ", e));
    });
  }
}

运行日志 ​

2024-12-07 19:22:41.678 [tio-group-3] INFO  c.l.g.t.s.ScheduledPushService.lambda$4:71 - 尝试发送消息到 超级群组: {超级群Id}
2024-12-07 19:22:41.691 [tio-group-3] INFO  c.l.g.t.s.ScheduledPushService.pushArticleToGroup:36 - 推送任务已完成。
2024-12-07 19:22:41.835 [ForkJoinPool.commonPool-worker-1] INFO  c.l.g.t.s.ScheduledPushService.lambda$5:72 - 消息发送成功: Message{data=Variant2{t1=BaseMessage#38116ee0{flags=100000010, id=69, fromId=PeerUser#59511722{userId=7847170133}, peerId=PeerChannel#a2a5371e{channelId={超级群Id}}, fwdFrom=null, viaBotId=null, replyTo=null, date=1733635379, message='📅 **每日一文** - 2024年12月07日

这里是今天的文章内容。请大家阅读并讨论!', media=null, replyMarkup=null, entities=null, views=null, forwards=null, replies=null, editDate=null, postAuthor='null', groupedId=null, reactions=null, restrictionReason=null, ttlPeriod=null}}}
2024-12-07 19:22:41.836 [ForkJoinPool.commonPool-worker-1] INFO  c.l.g.t.s.ScheduledPushService.lambda$0:31 - 成功向超级群组推送文章。
2024-12-07 19:22:41.836 [t4j-events-2] INFO  c.l.g.t.p.UserPredicate.test:21 - e:SendMessageEvent{message=Message{data=Variant2{t1=BaseMessage#38116ee0{flags=100000010, id=69, fromId=PeerUser#59511722{userId=7847170133}, peerId=PeerChannel#a2a5371e{channelId={超级群Id}}, fwdFrom=null, viaBotId=null, replyTo=null, date=1733635379, message='📅 **每日一文** - 2024年12月07日

这里是今天的文章内容。请大家阅读并讨论!', media=null, replyMarkup=null, entities=null, views=null, forwards=null, replies=null, editDate=null, postAuthor='null', groupedId=null, reactions=null, restrictionReason=null, ttlPeriod=null}}}, chat=SupergroupChat{minData=Channel#83259464{flags=1000110000100000000, flags2=0, id={超级群Id}, accessHash=-2695782318103141212, title='最强互推机器人审核群', username='null', photo=ChatPhotoEmpty#37c1011c{}, date=1733625678, restrictionReason=null, adminRights=ChatAdminRights#5fb224d5{flags=1101010111001}, bannedRights=null, defaultBannedRights=ChatBannedRights#9f120418{flags=0, untilDate=2147483647}, participantsCount=null, usernames=null}, fullData=null}, author=User{minData=BaseUser#abb5f120{flags=10000000001100010000001011, flags2=10010, id=7847170133, accessHash=-4262855346709871929, firstName='my-translator', lastName='null', username='litongjava_bot', phone='null', photo=null, status=null, botInfoVersion=1, restrictionReason=null, botInlinePlaceholder='null', langCode='null', emojiStatus=null, usernames=null, storiesMaxId=null}, fullData=null}}
2024-12-07 19:22:41.836 [t4j-events-2] INFO  c.l.g.t.p.UserPredicate.test:37 - 获取到机人自己的消息
2024-12-07 19:22:41.853 [ForkJoinPool.commonPool-worker-1] INFO  c.l.g.t.s.ScheduledPushService.lambda$4:71 - 尝试发送消息到 普通群组: {普通群Id}
2024-12-07 19:22:42.000 [ForkJoinPool.commonPool-worker-1] INFO  c.l.g.t.s.ScheduledPushService.lambda$5:72 - 消息发送成功: Message{data=Variant2{t1=BaseMessage#38116ee0{flags=100000010, id=1752, fromId=PeerUser#59511722{userId=7847170133}, peerId=PeerChat#36c6019a{chatId={普通群Id}}, fwdFrom=null, viaBotId=null, replyTo=null, date=1733635379, message='📅 **每日一文** - 2024年12月07日

这里是今天的文章内容。请大家阅读并讨论!', media=null, replyMarkup=null, entities=null, views=null, forwards=null, replies=null, editDate=null, postAuthor='null', groupedId=null, reactions=null, restrictionReason=null, ttlPeriod=null}}}
2024-12-07 19:22:42.004 [ForkJoinPool.commonPool-worker-1] INFO  c.l.g.t.s.ScheduledPushService.lambda$2:34 - 成功向普通群组推送文章。
2024-12-07 19:22:42.005 [t4j-events-2] INFO  c.l.g.t.p.UserPredicate.test:21 - e:SendMessageEvent{message=Message{data=Variant2{t1=BaseMessage#38116ee0{flags=100000010, id=1752, fromId=PeerUser#59511722{userId=7847170133}, peerId=PeerChat#36c6019a{chatId={普通群Id}}, fwdFrom=null, viaBotId=null, replyTo=null, date=1733635379, message='📅 **每日一文** - 2024年12月07日

这里是今天的文章内容。请大家阅读并讨论!', media=null, replyMarkup=null, entities=null, views=null, forwards=null, replies=null, editDate=null, postAuthor='null', groupedId=null, reactions=null, restrictionReason=null, ttlPeriod=null}}}, chat=null, author=null}
2024-12-07 19:22:42.006 [t4j-events-2] INFO  c.l.g.t.p.UserPredicate.test:28 - 消息发送者信息缺失,可能是机器人自身发送的消息。

注意事项 ​

在首次启动应用程序后,请按照以下步骤操作:

  1. 使用个人账号向机器人发送消息:

    • 操作:使用您的个人 Telegram 账号向机器人发送一条消息,等待机器人的回复。
    • 原因:这是为了建立与机器人的初始连接,并确保机器人能够识别您的账号。这一步骤确保机器人具备与您的账号进行双向通信的权限。
  2. 在超级群组中向机器人发送消息:

    • 操作:在目标超级群组中发送一条消息给机器人,等待机器人的回复。
    • 原因:机器人需要确认其在超级群组中的存在并获得必要的权限。通过在群组中发送消息,您确保机器人能够接收到群组的上下文信息,并正确处理来自群组的请求。
  3. 等待机器人回复后再进行推送:

    • 操作:只有在机器人成功回复上述两步操作后,才开始执行定时推送任务。
    • 原因:确保机器人已经正确连接并获得了所需的访问权限。这一步骤防止在机器人未完全准备好的情况下尝试发送消息,从而避免潜在的错误或消息发送失败。

常见问题 ​


问题一:机器人无法向群组发送消息 ​

可能原因及解决方法:

  1. 权限不足:

    • 确保机器人在群组中具有发送消息的权限。
    • 检查群组设置,确认机器人未被限制发送消息。
  2. 错误的 Chat ID:

    • 确认群组的 Chat ID 是否正确。
    • 使用前述方法重新获取 Chat ID,并更新配置。
  3. 网络连接问题:

    • 确保服务器能够正常访问 Telegram API。
    • 检查防火墙设置,确保相关端口未被阻止。
  4. 机器人未连接到 MTProto 客户端:

    • 查看日志,确认机器人已成功连接到 Telegram MTProto 客户端。
    • 如果未连接,检查 API ID 和 Hash 是否正确配置。

总结 ​

在本节中,我们详细介绍了如何为基于 MTProto 协议开发的 Telegram 翻译机器人添加定时推送功能。通过创建 Telegram 群组、配置机器人权限、实现定时任务调度以及编写推送逻辑,您可以实现自动向群组推送文章的功能。定时推送不仅能够提高群组的活跃度,还能为用户提供定期的有价值内容,增强用户体验。

关键步骤回顾: ​

  1. 创建 Telegram 群组:用于接收定时推送的文章。
  2. 配置机器人加入群组:确保机器人具有发送消息的权限,并获取群组的 Chat ID。
  3. 实现定时推送功能:
    • 使用 SchedulerConfig 管理定时任务。
    • 编写 ScheduledPushService 类,负责定时获取文章并发送到群组。
  4. 测试与验证:确保定时推送功能正常工作,并根据需要调整配置和代码。

通过上述步骤,您的 Telegram 翻译机器人将不仅具备翻译功能,还能主动向群组推送内容,提升机器人的实用性和用户满意度。希望本节内容对您有所帮助,助您顺利扩展机器人的功能。

参考资料 ​