Telegram Bot开发:如何逐条发送赛事并等待用户回复后处理下一条
问题根因
你写的for循环没有等待用户回复的逻辑,会立刻执行完所有迭代:一次性发送全部10条赛事,同时给同一条触发消息注册了10个register_next_step_handler回调,所以用户仅发送1条回复就会触发所有10次make_prediction执行,和你预期的逐条交互逻辑不符。
修复方案
核心逻辑是存储每个用户的预测进度,每次处理完用户的单场预测后再发送下一场赛事,注册下一次的回复回调,不要用循环一次性处理所有赛事。
以下是基于pyTelegramBotAPI的可运行代码示例:
import re # 全局字典存储用户的预测进度和结果,生产环境可替换为Redis/数据库 user_prediction_status = {} # /prediction 命令触发入口 @bot.message_handler(commands=['prediction']) def init_prediction_process(message): chat_id = message.chat.id # 初始化用户状态 user_prediction_status[chat_id] = { "current_fixture_idx": 0, "saved_predictions": [] } # 发送第一条赛事 first_fixture = prediction.schedule[0]["fixture_name"] bot.send_message(chat_id, first_fixture) # 注册下一次用户回复的处理回调 bot.register_next_step_handler(message, process_single_prediction) # 处理单场赛事的用户预测输入 def process_single_prediction(message): chat_id = message.chat.id # 校验用户是否处于预测流程中 if chat_id not in user_prediction_status: bot.send_message(chat_id, "请先发送 /prediction 开启预测流程") return user_status = user_prediction_status[chat_id] user_input_score = message.text.strip() # 可选:添加比分格式校验,不符合则提示重新输入,不推进进度 # if not re.match(r'^\d+-\d+$', user_input_score): # bot.send_message(chat_id, "比分格式错误,请输入类似 2-1 的格式重新提交") # bot.register_next_step_handler(message, process_single_prediction) # return # 保存当前场次的预测结果 current_fixture = prediction.schedule[user_status["current_fixture_idx"]] user_status["saved_predictions"].append({ "fixture_name": current_fixture["fixture_name"], "predicted_score": user_input_score }) # 推进进度到下一场 user_status["current_fixture_idx"] += 1 if user_status["current_fixture_idx"] < len(prediction.schedule): # 还有未预测的赛事,发送下一场并注册回调 next_fixture = prediction.schedule[user_status["current_fixture_idx"]]["fixture_name"] bot.send_message(chat_id, next_fixture) bot.register_next_step_handler(message, process_single_prediction) else: # 所有赛事预测完成 bot.send_message(chat_id, "Predictions saved!") # 可选:清除用户状态,或者将结果持久化到数据库 del user_prediction_status[chat_id]
额外优化建议
- 可以添加
/cancel命令处理逻辑,用户中途想退出预测时清除对应状态 - 生产环境建议将用户状态存储到Redis等持久化组件中,避免服务重启导致用户进度丢失
- 完善输入校验逻辑,避免用户输入非法内容打断流程
内容的提问来源于stack exchange,提问作者pdanchenko
相关产品推荐
相关产品推荐

