首页 > Java > java教程 > 正文

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

聖光之護
发布: 2025-09-29 10:26:11
原创
902人浏览过

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/link/f6b50ff60e962a4d29e02759470b2d79

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

由于 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 {

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

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

    // 模拟TelegramBot的execute方法
    private Message execute(SendPoll sendPoll) throws TelegramApiException {
        System.out.println("Sending poll to chat: " + sendPoll.getChatId());
        // 实际应用中,这里会调用TelegramBotsApi.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; // 假设通过依赖注入获取
    // 模拟TelegramBot的execute方法
    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());
                }
            }
        });
    }
}
登录后复制

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

用户可能需要通过发送特定命令(如 /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 轮询管理:实现自动与手动关闭策略的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号