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

PyTelegramBotAPI点击按钮后立即返回错误,无法输入章节号

PyTelegramBotAPI漫画查询机器人章节搜索功能修复

问题说明

使用PyTelegramBotAPI编写漫画查询机器人时,点击“Search”按钮(对应call.data == 'search_chapter'),机器人发送提示文本“Введите номер главы манги, которую вы ищете:”后,会立刻执行handle_search_chapter_input函数并返回错误“Некорректный номер главы. Пожалуйста, введите число.”,用户根本无法输入章节号。原因是代码直接将机器人发送的提示消息对象传给了处理函数,而非等待用户输入的章节号消息。

错误根源

原代码中,调用bot.send_message后立即把返回的消息对象(机器人自身发送的提示消息)传入handle_search_chapter_input,此时msg.text是提示文本或为空,并非用户输入的章节号,导致数据库查询无结果,触发错误提示。

修复方案

需要通过注册临时消息处理器实现“等待用户输入”的逻辑:

  • 用户点击按钮后,发送提示消息,同时为该聊天ID注册临时消息处理器,专门监听用户接下来的输入。
  • 处理完用户输入的章节号后,移除临时处理器,避免干扰后续消息处理。

修改后的代码示例

按钮点击处理逻辑

elif call.data == 'search_chapter':
    chat_id = call.message.chat.id
    bot.send_message(chat_id, "Введите номер главы манги, которую вы ищете:")
    
    # 注册临时消息处理器,仅监听当前聊天ID的消息
    @bot.message_handler(func=lambda message: message.chat.id == chat_id)
    def temp_chapter_input_handler(message):
        handle_search_chapter_input(chat_id, message)
        # 处理完成后移除临时处理器
        bot.remove_message_handler(temp_chapter_input_handler)

章节查询处理函数

def handle_search_chapter_input(chat_id, msg):
    try:
        # 获取已选择的漫画名称
        manga_name = chapter_selection[chat_id]['manga_name']
        chapter_number_input = msg.text.strip()
        
        # 先验证输入是否为数字
        if not chapter_number_input.isdigit():
            bot.send_message(chat_id=chat_id, text="Некорректный номер главы. Пожалуйста, введите число.")
            return
        
        # 转换为整数类型(适配数据库中章节号的整数存储)
        chapter_number = int(chapter_number_input)
        
        # 查询数据库
        conn = sqlite3.connect('manga_bot.db')
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM chapters WHERE manga_name=? AND chapter_number=?",
                       (manga_name, chapter_number))
        chapter_data = cursor.fetchone()
        conn.close()
        
        # 处理查询结果
        if chapter_data is not None:
            chapter_title = chapter_data[3]
            chapter_url = chapter_data[4]
            chapter_num = chapter_data[2]
            result_message = f"Глава {chapter_num}: {chapter_title}\n\nСсылка на главу: {chapter_url}"
            bot.send_message(chat_id=chat_id, text=result_message)
        else:
            bot.send_message(chat_id=chat_id, text="Такой главы не существует. Пожалуйста, проверьте номер.")
    
    # 处理未选择漫画的情况
    except KeyError:
        bot.send_message(chat_id=chat_id, text="Ошибка: Сначала выберите мангу для поиска глав.")
    # 捕获其他未知错误
    except Exception as e:
        bot.send_message(chat_id=chat_id, text=f"Произошла ошибка: {str(e)}")

关键优化点

  • 临时处理器通过func=lambda message: message.chat.id == chat_id限定处理范围,不会影响其他用户的消息。
  • 增加输入验证,提前过滤非数字输入,避免无效数据库查询。
  • 完善异常处理,覆盖未选择漫画、数据库错误等场景,提升用户体验。

内容的提问来源于stack exchange,提问作者kocchi wo miro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:22:51