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

Telegram Bot报错:TypeError: Message对象不能用于await表达式

问题原因分析
  1. 异步方法未用await执行:update.message.reply_text是异步方法,直接调用会返回Message对象而非完成执行,这就是报错TypeError: object Message can't be used in 'await' expression的核心原因。
  2. 协程启动方式错误:Updater内部已维护异步事件循环,手动用asyncio.run(start(...))启动协程会导致循环冲突,不符合框架运行规范。
修复后的完整代码
from telegram import Update, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    CallbackContext, Updater, MessageHandler, Filters,
    ConversationHandler, CallbackQueryHandler
)

# 定义对话状态标识(用于多轮交互跟踪)
SELECT_OPTION = 1

async def start(update: Update, context: CallbackContext):
    reply_keyboard = [["A", "B", "C"]]
    await update.message.reply_text(
        "Select any one",
        reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
    )
    return SELECT_OPTION  # 进入等待用户选择的状态

async def handle_invalid_input(update: Update, context: CallbackContext):
    cmd = update.message.text
    await update.message.reply_text(f"Sorry '{cmd}' is not a valid command")

# 处理用户选择A/B/C的逻辑
async def handle_option_selection(update: Update, context: CallbackContext):
    selected_option = update.message.text
    if selected_option in ["A", "B", "C"]:
        await update.message.reply_text(f"You selected {selected_option}!")
        # 内联键盘示例
        inline_keyboard = [[InlineKeyboardButton("Click Me", callback_data='button_clicked')]]
        await update.message.reply_text(
            "Here's an inline keyboard:",
            reply_markup=InlineKeyboardMarkup(inline_keyboard)
        )
        return ConversationHandler.END  # 结束当前对话
    else:
        await update.message.reply_text("Please select a valid option from the keyboard")
        return SELECT_OPTION  # 继续等待正确输入

# 处理内联按钮点击回调
async def handle_inline_button_click(update: Update, context: CallbackContext):
    query = update.callback_query
    await query.answer()
    await query.edit_message_text(text="You clicked the inline button!")

def main():
    updater = Updater(BOT_TOKEN, use_context=True)
    dispatcher = updater.dispatcher

    # 用ConversationHandler实现多轮对话(等待用户输入)
    conv_handler = ConversationHandler(
        entry_points=[MessageHandler(Filters.text & Filters.regex('^/start$'), start)],
        states={
            SELECT_OPTION: [MessageHandler(Filters.text, handle_option_selection)]
        },
        fallbacks=[MessageHandler(Filters.text, handle_invalid_input)]
    )

    dispatcher.add_handler(conv_handler)
    # 添加内联按钮回调处理器
    dispatcher.add_handler(CallbackQueryHandler(handle_inline_button_click))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
关键修改说明
  • 所有处理函数改为async def,异步方法调用前加await,确保异步操作正确执行。
  • 用ConversationHandler实现等待用户输入的多轮对话逻辑,通过状态标识跟踪对话阶段。
  • 移除asyncio.run,直接在异步函数内await其他协程,贴合框架的异步运行机制。
  • 新增内联键盘实现示例及对应的回调处理函数,覆盖你需要的功能场景。
新手入门提示
  • python-telegram-bot v12+版本的核心API均为异步设计,所有发送消息、更新状态的方法必须用await调用。
  • 多轮交互优先使用ConversationHandler,它会自动帮你管理用户对话上下文,无需手动跟踪。
  • 内联按钮的点击事件需用CallbackQueryHandler单独处理,不能与普通消息逻辑混在一起。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:10:13