当前位置: 首页 > 图灵资讯 > 技术篇> Telegram Bot 轮询管理:实现自动与手动关闭策略

Telegram Bot 轮询管理:实现自动与手动关闭策略

来源:图灵教育
时间:2025-10-08 16:27:46

telegram bot 轮询管理:实现自动与手动关闭策略

本文旨在解决Telegram Bot创建的轮询(Poll)在达到指定时间后自动关闭,或通过特定命令手动关闭,特别是在Telegram API close_date限制(最长600秒)和onupdatereceived不跟踪机器人本身的信息。核心解决方案是利用stoppoll法,结合持久的存储和调度任务,实现灵活的轮询生命周期管理。Telegram Bot 生命周期管理挑战

Telegram Bot API 提供创建轮询(Poll)但是内置的功能 close_date 参数限制了轮询的自动关闭时间,最长只支持600秒(10分钟)。这对于需要长时间(如几天)运行的轮询来说远远不够。与此同时,开发人员经常面临如何通过机器人本身的逻辑或用户命令手动关闭轮询的问题,因为 onUpdateReceived 该方法通常不跟踪机器人发送的信息,使得很难获得机器人发送的轮询信息ID。

为了有效地管理Bot创建的轮询,我们需要一套更灵活的策略来实现几天后自动关闭或通过特定命令手动关闭。

核心解决:stopPoll API

Telegram Bot API 关闭轮询提供了一种特殊的方法:stopPoll。

stopPoll 方法详解:

stopPoll 该方法允许机器人关闭活跃轮询。它需要两个关键参数:

  • chat_id:聊天ID轮询所在地。
  • message_id:信息ID轮询消息。

一旦调用 stopPoll,指定的轮询将立即停止,用户将无法再次投票,投票结果将最终确定。

API 文档参考: https://www.php.cn/linkf6b50ff60e962a4d29e027770b7

实现策略1:自动关闭轮询(长期)

由于 close_date 我们不能直接通过限制 SendPoll 对象在几天后自动关闭。这一功能需要结合持久的存储和调度任务进行模拟。

千面视频动捕

千面视频动捕

千面视频动捕是AI视频动捕解决方案,专注于将视频中人体关节的二维信息转化为三维模型动作。

千面视频动捕27

查看详情 千面视频动捕

1. 存储轮询信息: 当机器人成功发送轮询时,execute(sendPoll) 方法会回到一个 Message 对象。这个 Message 对象包括轮询 chat_id 和 message_id。这些信息是后续关闭轮询的关键。

我们应存储以下信息:

  • chat_id:聊天ID轮询所在地。
  • message_id:ID轮询消息。
  • creation_time:轮询发送时间戳。
  • expected_close_time:预期的关闭时间戳(例如,creation_time + 2天)。
  • is_active:轮询是否仍然活跃。

这些信息可以存储在数据库中(例如PostgreSQL, MySQL)、NoSQL 数据库(如MongoDB, Redis)或者在简单的场景中存储在内存中 Map(但是请注意,内存Map在重启应用程序后会丢失数据)。

示例代码(发送轮询并存储信息):

import org.telegram.telegrambots.meta.api.methods.polls.SendPoll;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 假设这是一个存储轮询信息的类别
public class PollManager {

    // 存储活跃轮询的Mapp存储: key为chatId_messageId, pollinfo对象pollinfo
    private final Map<String, PollInfo> activePolls = new ConcurrentHashMap<>();

    private final Long chatIdPoll = 12345L; // 例子chat ID

    // 模拟Telegrambotexecute方法
    private Message execute(SendPoll sendPoll) throws TelegramApiException {
        System.out.println("Sending poll to chat: " + sendPoll.getChatId());
        // 在实际应用中,这里将调用Telegrambotsapitip.execute(sendPoll)
        // 为了演示,我们模拟返回一个Message对象
        Message message = new Message();
        message.setChatId(Long.valueOf(sendPoll.getChatId()));
        message.setMessageId(1000 + (int)(Math.random() * 100)); // 模拟message ID
        message.setDate((int)(System.currentTimeMillis() / 1000)); // 模拟发送时间
        return message;
    }

    public void sendAndRegisterPoll(SendPoll sendPoll, long daysToClose) {
        sendPoll.setChatId(String.valueOf(chatIdPoll));
        try {
            Message sentMessage = execute(sendPoll);
            if (sentMessage != null) {
                PollInfo pollInfo = new PollInfo(
                    sentMessage.getChatId(),
                    sentMessage.getMessageId(),
                    LocalDateTime.now(),
                    LocalDateTime.now().plusDays(daysToClose),
                    true
                );
                activePolls.put(pollInfo.getKey(), pollInfo);
                System.out.println("Poll sent and registered: " + pollInfo);
            }
        } catch (TelegramApiException e) {
            System.err.println("Failed to send poll: " + e.getMessage());
        }
    }

    // 内部类用于存储轮询信息
    static class PollInfo {
        Long chatId;
        Integer messageId;
        LocalDateTime creationTime;
        LocalDateTime expectedCloseTime;
        boolean isActive;

        public PollInfo(Long chatId, Integer messageId, LocalDateTime creationTime, LocalDateTime expectedCloseTime, boolean isActive) {
            this.chatId = chatId;
            this.messageId = messageId;
            this.creationTime = creationTime;
            this.expectedCloseTime = expectedCloseTime;
            this.isActive = isActive;
        }

        public String getKey() {
            return chatId + "_" + messageId;
        }

        @Override
        public String toString() {
            return "PollInfo{" +
                   "chatId=" + chatId +
                   ", messageId=" + messageId +
                   ", creationTime=" + creationTime +
                   ", expectedCloseTime=" + expectedCloseTime +
                   ", isActive=" + isActive +
                   '}';
        }
    }
}

2. 检查和关闭调度任务: 使用调度框架(如Spring) @Scheduled,Java的 Timer,或外部的 cron job)定期检查活动轮询列表。 每次调度执行时:

  • 遍历所有 is_active 为 true 的轮询。
  • 检查当前时间是否晚于当前时间 expected_close_time。
  • 若条件满足,调用 stopPoll 关闭轮询的方法。
  • 更新轮询状态为 is_active = false。

示例代码(调度任务):

import org.telegram.telegrambots.meta.api.methods.polls.StopPoll;
// ... (其他必要的导入,如 PollManager)

public class ScheduledPollCloser {

    private final PollManager pollManager; // 假设通过依赖注入获得假设
    // 模拟Telegrambotexecute方法
    private org.telegram.telegrambots.meta.api.objects.polls.Poll execute(StopPoll stopPoll) throws TelegramApiException {
        System.out.println("Stopping poll in chat: " + stopPoll.getChatId() + ", messageId: " + stopPoll.getMessageId());
        // 在实际应用中,TelegramBotsApi将在此调用。.execute(stopPoll)
        // 为了演示,我们模拟返回一个Poll对象
        return new org.telegram.telegrambots.meta.api.objects.polls.Poll();
    }

    public ScheduledPollCloser(PollManager pollManager) {
        this.pollManager = pollManager;
    }

    @Scheduled(fixedRate = 60000) // 每分钟检查一次
    public void checkAndCloseExpiredPolls() {
        LocalDateTime now = LocalDateTime.now();
        pollManager.activePolls.forEach((key, pollInfo) -> {
            if (pollInfo.isActive && now.isAfter(pollInfo.expectedCloseTime)) {
                try {
                    StopPoll stopPoll = new StopPoll(String.valueOf(pollInfo.chatId), pollInfo.messageId);
                    execute(stopPoll); // 执行关闭操作
                    pollInfo.isActive = false; // 更新状态
                    System.out.println("Poll automatically closed: " + pollInfo.getKey());
                } catch (TelegramApiException e) {
                    System.err.println("Failed to stop poll " + pollInfo.getKey() + ": " + e.getMessage());
                }
            }
        });
    }
}

实现策略2:手动关闭轮询(通过命令)

例如,用户可能需要发送特定的命令 /stoppoll 或 /closepoll)手动关闭一个或多个轮询。

1. 监控用户命令: 在机器人的 onUpdateReceived 在方法中,我们需要监控用户发送的命令。

import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.methods.polls.StopPoll;

public class MyTelegramBot extends TelegramLongPollingBot {

    private final PollManager pollManager; // 假设通过依赖注入获得假设

    public MyTelegramBot(PollManager pollManager) {
        this.pollManager = pollManager;
    }

    @Override
    public void onUpdateReceived(Update update) {
        if (update.hasMessage() && update.getMessage().hasText()) {
            String messageText = update.getMessage().getText();
            Long chatId = update.getMessage().getChatId();

            if (messageText.startsWith("/stoppoll")) {
                handleStopPollCommand(chatId, messageText);
            }
            // ... 其它命令处理
        }
    }

    private void handleStopPollCommand(Long chatId, String commandText) {
        // 解析命令,可能包括要关闭的轮询ID或其他标志
        // 简化示例:试着关闭聊天中最近的活跃轮询
        PollManager.PollInfo pollToStop = pollManager.activePolls.values().stream()
            .filter(p -> p.chatId.equals(chatId) && p.isActive)
            .sorted((p1, p2) -> p2.creationTime.compareTo(p1.creationTime)) // 最近的
            .findFirst()
            .orElse(null);

        if (pollToStop != null) {
            try {
                StopPoll stopPoll = new StopPoll(String.valueOf(pollToStop.chatId), pollToStop.messageId);
                execute(stopPoll); // 执行关闭操作
                pollToStop.isActive = false; // 更新状态
                System.out.println("Poll manually closed by command: " + pollToStop.getKey());
                // 可选:向用户发送确认信息
                // sendTextMessage(chatId, "轮询已经关闭。");
            } catch (TelegramApiException e) {
                System.err.println("Failed to stop poll " + pollToStop.getKey() + " via command: " + e.getMessage());
                // sendTextMessage(chatId, "关闭轮询失败:" + e.getMessage());
            }
        } else {
            System.out.println("No active poll found to stop in chat: " + chatId);
            // sendTextMessage(chatId, "目前聊天中没有活跃的轮询可以关闭。");
        }
    }

    @Override
    public String getBotUsername() {
        return "YourBotUsername";
    }

    @Override
    public String getBotToken() {
        return "YOUR_BOT_TOKEN";
    }
}

2. 识别并关闭目标轮询: 当收到 /stoppoll 命令时,机器人需要知道要关闭哪个轮询。这可能需要:

  • 上下文关联: 如果聊天中只有一个活跃的轮询,可以直接关闭。
  • 命令参数: 用户可以在命令中指定轮询ID(例如 /stoppoll <poll_id>),这就要求在存储轮询信息时分配一个易于识别的ID。
  • 回复消息: 如果用户回复要关闭的轮询信息,update.getMessage().getReplyToMessage() 可提供轮询信息 message_id。

根据具体需要,从存储的活跃轮询信息中找到匹配 chat_id 和 message_id,然后调用 stopPoll。

注意事项和最佳实践
  1. 信息ID的持久性至关重要: 无论是自动还是手动关闭,message_id 都是核心。发送轮询时必须获得并可靠存储。
  2. 错误处理: 调用 execute(stopPoll) 时应捕获 TelegramApiException,并进行适当的日志记录或用户反馈。
  3. 状态管理: 确保轮询状态(is_active)关闭后进行更新,避免重复关闭或对已关闭的轮询进行操作。
  4. 并发性: 如果机器人处理大量轮询或高并发请求,则确保轮询信息的存储和访问是线程安全的(例如使用) ConcurrentHashMap 或者数据库事务)。
  5. 用户反馈: 手动关闭轮询后,向用户发送确认信息,告知轮询已成功关闭。
  6. 可扩展性: 考虑到未来可能需要管理多种类型的轮询,或者在不同的聊天中管理多种活跃轮询。在设计存储结构时,应考虑这些扩展性。
  7. 内存与持久性: 对于生产环境,强烈建议使用数据库对轮询信息进行持久存储,以防止应用重启导致数据丢失。内存 Map 仅适用于简单的测试或短生命周期轮询。
总结

管理 Telegram Bot 需要跳出创建的轮询,特别是自定义的自动关闭周期和手动关闭功能 close_date 限制。核心在于利用 stopPoll API,并通过持久存储轮询进行持久存储 chat_id 和 message_id,通过监控用户命令和检索存储信息,结合调度任务实现自动关闭和手动关闭。遵循这些策略和最佳实践,我们可以建立一个强大而完美的功能 Telegram 轮询管理系统。

以上是Telegram Bot 轮询管理:实现自动和手动关闭策略的详细内容,请关注图灵教育的其他相关文章!

相关标签:

mysql java redis go mongodb oppo ai stream 数据丢失 持久化存储 并发请求 Java mysql spring 线程 map 并发 对象 redis mongodb postgresql nosql 数据库 https