You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pyTelegramBotApi(Telebot)多用户同时使用时数值混淆问题求解

问题根源

你遇到的多用户数值混淆问题核心是使用了全局变量存储验证数字,所有用户共享同一份全局状态,任意用户触发随机数生成逻辑都会覆盖全局的n1、n2值,自然会同步影响其他正在进行验证的用户。

修复方案

用chat_id作为唯一标识存储每个用户的专属验证数据,同时利用pyTelegramBotApi的register_next_step_handler支持传递自定义参数的特性,将对应验证数值直接传给后续回调函数,完全隔离不同用户的状态。

修复后完整代码
import random
import telebot

bot = telebot.TeleBot("替换为你的BOT_TOKEN")

# 存储每个用户的验证数据,key为chat_id
user_verify_data = {}

# 生成随机验证数字,直接返回结果不再修改全局变量
def generate_random():
    n1 = random.randint(1, 100)
    n2 = random.randint(1, 100)
    return n1, n2

# Bot Start Command
@bot.message_handler(commands=['start'])
def start_command(message):
    chat_id = message.chat.id
    # 生成当前用户专属的验证数字
    n1, n2 = generate_random()
    # 存入用户专属数据
    user_verify_data[chat_id] = {"n1": n1, "n2": n2}
    prove_yourself(chat_id, n1, n2)

def prove_yourself(chat_id, n1, n2):
    result = bot.send_message(chat_id, f"ℹ️ Prove That You Are A Human!\n\n{n1} + {n2} = ?")
    # 把当前用户的n1、n2作为参数传给验证回调
    bot.register_next_step_handler(result, verifyUser, n1, n2)

def verifyUser(message, n1, n2):
    chat_id = message.chat.id
    try:
        input_ans = int(message.text)
    except ValueError:
        bot.send_message(chat_id, '❌ 请输入有效的数字答案 ❌')
        prove_yourself(chat_id, n1, n2)
        return
        
    if input_ans != n1 + n2:
        bot.send_message(chat_id, '❌ Wrong Answer ❌')
        # 答错重新生成当前用户的新验证数字
        new_n1, new_n2 = generate_random()
        user_verify_data[chat_id] = {"n1": new_n1, "n2": new_n2}
        prove_yourself(chat_id, new_n1, new_n2)
    else:
        # 验证成功后清理用户数据避免占用空间
        if chat_id in user_verify_data:
            del user_verify_data[chat_id]
        print("next step")

bot.polling()
核心改动说明
  • 移除了全局n1、n2变量,新增user_verify_data字典按chat_id存储每个用户的独立验证状态,不同用户的数据完全隔离
  • 随机数生成函数改为直接返回结果,不再修改全局变量,避免互相干扰
  • 调用register_next_step_handler时将当前用户的验证数字作为参数传入回调函数,验证时直接使用传入的参数,不需要读取共享变量
  • 新增输入合法性校验,避免用户输入非数字内容导致程序报错
  • 验证成功后自动清理对应用户的存储数据,减少不必要的内存占用

内容的提问来源于stack exchange,提问作者Drop Guruji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:48:04