
在 Telegram Bot 开发中,创建投票是一项常见功能。然而,当我们需要在特定时间后(例如几天后)自动关闭投票,或允许用户手动关闭投票时,会遇到一些挑战。Telegram Bot API 中 SendPoll 方法的 close_date 参数虽然可以设置投票关闭时间,但其最大值仅为 600 秒(10 分钟),这显然无法满足“几天后”关闭的需求。此外,机器人自身发送的消息通常不会直接触发 onUpdateReceived 方法,使得获取机器人所发投票的 messageId 变得不直观。本教程将深入探讨如何优雅地解决这些问题。
要关闭一个已经发送的 Telegram 投票,我们必须使用 Telegram Bot API 提供的 stopPoll 方法。此方法允许机器人通过指定投票的 chat_id 和 message_id 来停止该投票。
stopPoll 方法的签名如下(以 Java Telegram Bot API 为例):
public Message stopPoll(StopPoll stopPoll) throws TelegramApiException
其中,StopPoll 对象需要包含以下关键参数:
调用 stopPoll 后,该投票将立即停止,用户将无法再进行投票,并且投票结果将最终确定。
实现自动或手动关闭投票的关键在于,机器人必须能够持久化地存储其发送的每个投票的 chatId 和 messageId。当机器人成功发送一个投票后,Telegram API 会返回一个 Message 对象,其中包含了我们所需的所有信息。
以下是发送投票并存储其关键信息的示例代码:
import org.telegram.telegrambots.meta.api.methods.polls.SendPoll;
import org.telegram.telegrambots.meta.api.methods.polls.StopPoll;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
// 存储投票信息的内部类
class PollInfo {
    String chatId;
    Integer messageId;
    LocalDateTime closeTime; // 期望的关闭时间
    String pollIdentifier; // 用于手动关闭的唯一标识符,例如一个UUID或自定义名称
    public PollInfo(String chatId, Integer messageId, LocalDateTime closeTime, String pollIdentifier) {
        this.chatId = chatId;
        this.messageId = messageId;
        this.closeTime = closeTime;
        this.pollIdentifier = pollIdentifier;
    }
    // Getters
    public String getChatId() { return chatId; }
    public Integer getMessageId() { return messageId; }
    public LocalDateTime getCloseTime() { return closeTime; }
    public String getPollIdentifier() { return以上就是Telegram Bot 投票管理:实现自动与手动关闭策略的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号