
Telegram Bot API 提供了创建轮询(Poll)的功能,但其内置的 close_date 参数限制了轮询的自动关闭时间,最长仅支持600秒(10分钟)。这对于需要长时间(例如几天)运行的轮询来说远远不够。同时,开发者常常面临如何通过机器人自身逻辑或用户命令来手动关闭轮询的问题,因为 onUpdateReceived 方法通常不追踪机器人发送的消息,使得获取机器人发送的轮询消息ID变得困难。
为了有效管理Bot创建的轮询,实现其在几天后自动关闭或通过特定命令手动关闭,我们需要一套更为灵活的策略。
Telegram Bot API 提供了一个专门用于关闭轮询的方法:stopPoll。
stopPoll 方法详解:
stopPoll 方法允许机器人关闭一个活跃的轮询。它需要两个关键参数:
一旦调用 stopPoll,指定的轮询将立即停止,用户将无法再投票,并且投票结果将最终确定。
API 文档参考: https://www.php.cn/link/f6b50ff60e962a4d29e02759470b2d79
由于 close_date 的限制,我们无法直接通过 SendPoll 对象实现数天后的自动关闭。我们需要结合持久化存储和调度任务来模拟这一功能。
1. 存储轮询信息: 当机器人成功发送一个轮询时,execute(sendPoll) 方法会返回一个 Message 对象。这个 Message 对象包含了轮询的 chat_id 和 message_id。这些信息是后续关闭轮询的关键。
我们应该将以下信息存储起来:
这些信息可以存储在数据库(如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)定期检查活跃轮询列表。 在每次调度执行时:
示例代码(调度任务):
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 命令时,机器人需要知道要关闭哪个轮询。这可能需要:
根据具体需求,从存储的活跃轮询信息中找到匹配的 chat_id 和 message_id,然后调用 stopPoll。
管理 Telegram Bot 创建的轮询,特别是实现自定义的自动关闭周期和手动关闭功能,需要跳出 close_date 的限制。核心在于利用 stopPoll API,并通过持久化存储轮询的 chat_id 和 message_id,结合调度任务实现自动关闭,以及通过监听用户命令和检索存储信息实现手动关闭。遵循这些策略和最佳实践,可以构建一个健壮且功能完善的 Telegram 轮询管理系统。
以上就是Telegram Bot 轮询管理:实现自动与手动关闭策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号