基于telegram-bot-ruby实现多用户独立会话的Telegram机器人咨询
问题分析与解决方案
你的代码问题出在嵌套bot.listen和共享实例变量:
- 嵌套的
listen会抢占全局消息处理逻辑,导致后续消息被内层listen捕获,其他用户的消息无法正常处理 @name、@age是全局实例变量,多个用户同时操作时会互相覆盖,导致会话状态混乱
不需要异步实现,核心是为每个用户维护独立的会话状态,用状态机模式即可解决。以下是修改后的代码:
Telegram::Bot::Client.run(token) do |bot| # 存储每个用户的会话状态,key为chat_id,value为当前状态 sessions = {} bot.listen do |message| chat_id = message.chat.id current_state = sessions[chat_id] || :idle text = message.text case current_state when :idle case text when '/start' sessions[chat_id] = :waiting_for_name bot.api.send_message(chat_id: chat_id, text: "Hello, enter name:") when '/stop' bot.api.send_message(chat_id: chat_id, text: "Bye") else bot.api.send_message(chat_id: chat_id, text: "Enter /start ") end when :waiting_for_name # 接收用户输入的名字 name = text sessions[chat_id] = :waiting_for_age bot.api.send_message(chat_id: chat_id, text: "Nice to meet you #{name}, now input age") when :waiting_for_age # 接收用户输入的年龄 age = text sessions[chat_id] = :idle # 重置状态 bot.api.send_message(chat_id: chat_id, text: "Got it! Your name is #{name}, age is #{age}") end end end
关键说明
- 会话状态隔离:用
sessions哈希为每个chat_id保存独立状态(:idle、:waiting_for_name、:waiting_for_age),不同用户的状态完全独立 - 单循环处理:所有消息都在同一个
bot.listen循环内处理,根据当前状态分支逻辑,避免嵌套监听的混乱 - 状态流转清晰:每个步骤完成后更新状态,确保用户的交互流程按预期推进
如果需要更复杂的条件树,可以扩展状态值,或者把状态逻辑拆分成单独的方法/类,保持代码可读性。
内容的提问来源于stack exchange,提问作者ip0208
相关产品推荐
相关产品推荐

