Python telebot如何实现用户无操作时的自动消息推送与流程跳过
代码存在的核心问题
- 你当前的实现完全无法跑通需求,存在两个本质错误:
- 在回调处理流程中直接调用
time.sleep()会阻塞整个bot的事件循环,sleep期间所有用户的消息、按钮点击都无法被响应;且call.data是单次回调请求的临时变量,回调函数执行结束后就会被销毁,sleep结束后根本不存在“判断call.data是否为None”的可能,你写的条件判断逻辑从一开始就不成立。 - 缺少用户维度的状态追踪机制,根本没法记录每个用户的最后交互时间、已推送的提醒轮次、是否触发了跳过第5条推送的条件。
- 在回调处理流程中直接调用
可落地的实现方案
1. 搭建轻量状态存储
新手阶段不需要上复杂数据库,用内存字典即可实现核心逻辑,按用户chat_id存储独立状态:
# 全局状态存储:key为用户chat_id,value为对应用户的状态字典 user_session_state = {} # 单用户状态结构示例: # { # "last_interaction_ts": 1690000000, # 最后一次产生交互的时间戳 # "reminder_step": 0, # 已推送的提醒轮次:0=未发提醒,1=已发第4条提醒,99=提醒流程结束 # "skip_5th_reminder": False # 是否跳过第5条推送(用户点击第4条消息的按钮时设为True) # }
2. 全局交互状态更新钩子
给所有消息、按钮点击的请求加统一的中间件,只要用户触发任何交互,就自动更新他的最后交互时间,同时重置提醒流程:
@bot.middleware_handler(update_types=['message', 'callback_query']) def sync_user_interaction(bot_instance, update): # 提取当前用户的chat_id if update.message: chat_id = update.message.chat.id else: chat_id = update.callback_query.message.chat.id # 初始化或更新用户状态 user_session_state.setdefault(chat_id, {}) user_session_state[chat_id]["last_interaction_ts"] = time.time() user_session_state[chat_id]["reminder_step"] = 0 # 如果用户点击了第4条消息的按钮,标记需要跳过第5条推送 if update.callback_query and update.callback_query.data == "check_exercise": user_session_state[chat_id]["skip_5th_reminder"] = True
3. 独立后台定时调度线程
绝对不能用time.sleep阻塞主进程,单独开启一个守护线程做定时扫描,低频率检查所有用户的状态,判断是否到了发提醒的节点:
import threading import time IDLE_THRESHOLD = 12 * 3600 # 连续12小时无交互的触发阈值 def reminder_scheduler(): while True: current_ts = time.time() for chat_id, state in user_session_state.items(): # 计算用户距上次交互的闲置时长 idle_time = current_ts - state.get("last_interaction_ts", 0) # 只处理满足闲置时长条件的用户 if idle_time >= IDLE_THRESHOLD: current_step = state.get("reminder_step", 0) # 第一阶段闲置:满12小时,发送第4条提醒 if current_step == 0: bot.send_message( chat_id, mg.fourth_message, reply_markup=kb.check_exercise() ) user_session_state[chat_id]["reminder_step"] = 1 # 第二阶段闲置:累计满24小时,判断是否发送第5条提醒 elif current_step == 1: # 如果之前点击过第4条的按钮,直接结束提醒流程,跳过第5条 if state.get("skip_5th_reminder", False): user_session_state[chat_id]["reminder_step"] = 99 continue # 未触发跳过条件的,发送第5条提醒 bot.send_message( chat_id, mg.fives_message, reply_markup=kb.check_exercise() ) user_session_state[chat_id]["reminder_step"] = 99 # 每10分钟扫描一次,降低资源消耗 time.sleep(600) # 启动调度线程,设为守护线程,主进程退出时自动销毁 threading.Thread(target=reminder_scheduler, daemon=True).start()
4. 原有按钮回调逻辑保留
你之前写的按钮处理逻辑不需要大幅改动,会被全局中间件自动同步状态:
@bot.callback_query_handler(func=lambda call: call.data == 'GetLesson1') def handle_lesson_access(call): bot.send_message(call.message.chat.id, mg.third_message, reply_markup=kb.check_exercise()) push_data.append(call.data) @bot.callback_query_handler(func=lambda call: call.data == 'Exercise') def handle_exercise(call): bot.send_message(call.message.chat.id, mg.sixth_message, reply_markup=kb.check_exercise())
提示:内存存储的状态会在bot重启后丢失,如果做长期生产部署,可将状态存储替换为SQLite等轻量数据库,核心逻辑不需要改动。
内容的提问来源于stack exchange,提问作者Cristina
相关产品推荐
相关产品推荐

