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

pytelegrambotapi开发Telegram机器人多用户请求报400错误如何解决

核心问题原因

你代码中使用了global user全局变量存储单用户实例,多用户同时访问时,后触发请求的用户会覆盖全局user变量的值。先触发请求的用户再发消息时,代码读取到的是后一个用户的info_post_id、last_message等属性,这些ID属于另一个用户的聊天窗口,调用Telegram接口编辑消息时自然会返回「message to edit not found」的400错误。

解决方案

1. 替换全局单用户变量为用户字典存储

在全局位置定义字典存储所有用户实例,以用户chat_id作为键,避免用户数据串扰:

import telebot
# 新增全局用户存储字典
users = {}

# 原有USER类定义保持不变

@bot.message_handler(commands = ["start"])
def start_bot(message):
    chat_id = message.chat.id
    # 没有对应用户则新建,已有则直接读取
    if chat_id not in users:
        users[chat_id] = USER(chat_id)
    user = users[chat_id]
    # 以下原有逻辑保持不变
    if user.isFull():
        user.last_message = bot.send_message(message.chat.id, 
                                             f"Hello {user.fish}", 
                                             reply_markup=MAIN_MENU)
    else:
        bot.delete_message(message.chat.id, message.message_id)
        bot.send_message(message.chat.id, "*Some post", reply_markup=None)
        user.info_post_id = bot.send_message(message.chat.id, user.user_info_checking()).message_id
        user.last_message = bot.send_message(message.chat.id, 'Name:')

2. 修改文本消息处理逻辑,从字典读取对应用户

@bot.message_handler(content_types=['text'])
def get_name_and_age(message):
    chat_id = message.chat.id
    # 未启动过机器人的用户先引导触发start命令
    if chat_id not in users:
        bot.send_message(chat_id, "请先发送/start启动机器人")
        return
    user = users[chat_id]
    # 增加空值判断避免属性报错
    if user.last_message and user.last_message.text=='Name:':
        user.fish = message.text
        bot.delete_message(chat_id, message.message_id)
        bot.edit_message_text(chat_id=chat_id,
                                message_id=user.info_post_id,
                                text=user.user_info_checking(),
                                reply_markup=None)
        user.last_message = bot.edit_message_text(chat_id=chat_id,
                                                    message_id=user.last_message.message_id,
                                                    text="Age:",
                                                    reply_markup=None)

3. 增加接口异常捕获做降级处理

如果用户手动删除了机器人要编辑的消息,即使逻辑正确也会触发400错误,增加异常捕获避免程序崩溃:

try:
    bot.edit_message_text(chat_id=chat_id,
                          message_id=user.info_post_id,
                          text=user.user_info_checking(),
                          reply_markup=None)
except telebot.apihelper.ApiException as e:
    if "message to edit not found" in str(e):
        # 消息已被删除,直接发新消息并更新存储的ID
        user.info_post_id = bot.send_message(chat_id, user.user_info_checking()).message_id
    else:
        # 其他错误按需处理
        raise e

内容的提问来源于stack exchange,提问作者Avazbek Vaxobov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:45:07