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

aiogram中Dispatcher的update事件处理器失效,需兼容其他处理器

解决Telegram Bot拦截所有更新同时保留其他处理器的问题

你遇到的问题主要有两个原因:一是@dp.update()处理器的优先级低于更具体的处理器(比如@dp.message()),如果事件被其他处理器先处理并终止传播,它就不会触发;二是可能缺少了Application的初始化与启动逻辑,导致Dispatcher根本没在运行。

以下是修正后的代码,实现拦截所有事件且不影响其他处理器:

from telegram import Update
from telegram.ext import (
    ApplicationBuilder,
    UpdateHandler,
    MessageHandler,
    filters,
    ContextTypes
)

# 拦截所有更新的处理器
async def all_updates_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(update)
    # 不要调用context.stop_propagation(),确保后续处理器能正常执行

def main():
    # 替换成你的Bot Token
    BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
    
    # 初始化Application
    application = ApplicationBuilder().token(BOT_TOKEN).build()
    dp = application.dispatch

    # 给全局更新处理器设置更高优先级(数字越小优先级越高,默认是0)
    dp.add_handler(UpdateHandler(all_updates_handler), priority=-1)

    # 保留你的其他消息处理器
    async def message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
        await update.message.reply_text("已收到文本消息")

    # 添加普通消息处理器(默认优先级0,会在全局处理器之后执行)
    dp.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, message_handler))

    # 启动Bot
    application.run_polling()

if __name__ == "__main__":
    main()

关键说明

  • 优先级设置:通过priority=-1让全局更新处理器比默认优先级(0)的其他处理器先执行,确保所有事件都会被它捕获。
  • 事件传播:全局处理器中不要调用context.stop_propagation(),这样后续的MessageHandler等处理器仍能正常处理对应事件。
  • 完整流程:必须初始化Application并调用run_polling()(或run_webhook()),否则Dispatcher不会开始接收更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:10:08