如何在PyTelegramBotAPI中终止长周期投票并获取结果
解决Telegram投票超时长自动关闭并获取结果的问题
Telegram官方send_poll接口的open_period参数上限为600秒,close_date虽支持设置未来时间,但受限于Bot框架实现或长期运行稳定性,无法直接满足长达一个月的投票需求。你需要通过自定义定时任务+主动调用关闭接口的方式实现需求,具体步骤如下:
核心思路
- 发送投票时记录投票的唯一ID和消息ID
- 借助定时任务工具,在指定时长(比如一个月)后触发关闭操作
- 关闭投票后主动获取并处理结果
代码实现(以python-telegram-bot v20+为例)
首先安装定时任务依赖:
pip install apscheduler
实现代码:
from apscheduler.schedulers.asyncio import AsyncIOScheduler import time # 初始化异步调度器(适配python-telegram-bot的异步环境) scheduler = AsyncIOScheduler(timezone="Asia/Shanghai") scheduler.start() async def send_long_term_poll(bot, channel_id): # 发送投票并保存关键信息 poll_msg = await bot.send_poll( chat_id=channel_id, question="投票内容", options=["是", "否"] ) poll_id = poll_msg.poll.id msg_id = poll_msg.message_id # 设置投票持续时长:一个月(单位:秒) duration = 30 * 24 * 3600 # 添加定时任务,到期自动关闭并获取结果 scheduler.add_job( handle_poll_close, trigger="date", run_date=time.time() + duration, args=[bot, channel_id, msg_id, poll_id] ) async def handle_poll_close(bot, channel_id, msg_id, poll_id): # 关闭投票 await bot.stop_poll(chat_id=channel_id, message_id=msg_id) # 获取最终投票结果 final_poll = await bot.get_poll(poll_id=poll_id) # 这里可以根据需求处理结果,比如存储到数据库或打印 for option in final_poll.options: print(f"选项「{option.text}」得票:{option.voter_count}")
注意事项
- 确保Bot服务长期在线,若服务重启,未执行的定时任务会丢失,可考虑用Redis等外部存储持久化任务信息
- 不同Bot框架的API调用细节有差异,比如pyrogram的
stop_poll参数格式不同,需对应调整 - 若投票时长极长,建议将定时任务托管到外部定时服务(如Linux的cron),避免本地进程崩溃导致任务失效
内容的提问来源于stack exchange,提问作者Shizer
相关产品推荐
相关产品推荐

