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

Python Telegram Bot:如何向BaseHandler子类传入装饰后的回调函数?

问题解决:Telegram Bot装饰器回调函数无法正常传入Handler的问题

你的代码核心问题是装饰器的包装函数没有把参数传递给原回调函数,同时装饰器的定义可以优化,以下是具体修正方案:

问题分析

  1. 装饰器里的wrapper函数调用func()时,没有传递接收的*args, **kwargs,导致decorated_function拿不到update和context参数,无法执行逻辑
  2. 装饰器本身不需要定义为异步函数,它只需要返回一个异步的包装函数即可

修正后的代码

def sample_func(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 这里返回你的判断逻辑,示例返回True
    return True

def sample_decorator(func):
    async def wrapper(*args, **kwargs):
        # 调用判断函数时传入参数
        if sample_func(*args, **kwargs):
            # 把参数传递给原回调函数
            await func(*args, **kwargs)
    return wrapper

@sample_decorator
async def decorated_function(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Some text here.')

def bot_start():
    app = Application.builder().token(TOKEN).build()
    app.add_handler(CommandHandler('test', decorated_function))

    # ... 你的其他初始化逻辑

    app.run_polling(poll_interval=3)

额外说明

如果你的sample_func本身是异步函数,只需要调整判断逻辑为异步调用:

async def sample_func(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 异步判断逻辑
    return True

def sample_decorator(func):
    async def wrapper(*args, **kwargs):
        if await sample_func(*args, **kwargs):
            await func(*args, **kwargs)
    return wrapper

修正后,decorated_function被装饰后返回的wrapper是一个可调用的异步函数,完全符合Telegram Bot Handler对回调函数的要求,既能保留装饰器的逻辑,又能正常被Handler调用。

内容的提问来源于stack exchange,提问作者Damie-Umbra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 13:12:35