Skip to main content

aiogram-buffered-router

Debounced message batching for aiogram 3. Consecutive messages from the same chat are collected into one batch and passed to a single handler.

Install

uv add aiogram-buffered-router

Usage

from aiogram import Bot, Dispatcher, F
from aiogram.types import Message
from aiogram_buffered_router import BufferedRouter

router = BufferedRouter(name="chat", interval=1.0)


@router.buffered(F.text)
async def handle_batch(messages: list[Message], data: dict[str, object]) -> None:
    bot = data["bot"]
    texts = [message.text for message in messages if message.text]
    print(bot, texts)


dispatcher = Dispatcher()
dispatcher.include_router(router)

On shutdown flush the pending batches:

await router.aclose()

Options

  • interval — debounce window in seconds, restarted on nothing; the batch is dispatched interval seconds after the first message.
  • max_size — dispatch immediately once the batch reaches this size, 0 disables the limit.
  • keychat_key (bot + chat) or thread_key (bot + chat + topic, default), or any callable returning a hashable.
  • on_error — called with (error, messages, data) when a batch handler raises.
  • expose_contexts — pass the per-message contexts to the handler under CONTEXTS_KEY.

Handler exceptions are logged by the aiogram_buffered_router.buffer logger and never break polling.

Context

Debouncing means the handler runs after the update that scheduled it has already been answered, in a task that outlives it. Context is carried across that gap rather than left to asyncio's implicit inheritance, which would pin every batch in a chat to whichever update happened to open the first one.

Each message is snapshotted with contextvars.copy_context() as it is buffered, the batch runs in the snapshot of the message that opened it, and the batch loop itself starts from an empty context so nothing leaks between batches. Anything built on context variables — trace context, request-scoped log binding — reaches the handler as a result, with no dependency on the library's side.

on_error runs in that same context, so a failure can be mapped back onto the update that caused it. It is the only route out: the batch runs detached from the dispatcher, so aiogram's error handling can never see it.

router = BufferedRouter(name="chat", interval=1.0, on_error=report)

A batch is many updates collapsing into one unit of work, and only the first of them can be the parent. Set expose_contexts=True to receive all of them and relate the rest yourself:

router = BufferedRouter(name="chat", interval=1.0, expose_contexts=True)


@router.buffered(F.text)
async def handle_batch(messages: list[Message], data: dict[str, object]) -> None:
    contexts = data.get(CONTEXTS_KEY, ())
    ...

Joining a batch that is already open

Sometimes only the first message of a batch is recognisable. A command takes an argument and the rest of the thought arrives as ordinary messages:

/system answer briefly
and in Russian

The second message matches no command filter, so it never reaches the buffer. Ask the buffer whether it is already collecting for that message's key and register a second entry into the same buffer:

buffer = router.attach(handle_system, key=thread_key)


async def collect(message: Message, **data: object) -> None:
    await buffer.add(message, data)


router.message.register(collect, Command("system"))
router.message.register(collect, buffer.is_buffering)

is_buffering uses the buffer's own key, and is true only while a batch actually holds messages — a dispatched batch lingers in memory for one idle window, and that does not count. Use attach rather than buffered here: buffered returns the handler, attach returns the buffer.

Keep in mind that the window is fixed from the first message of a batch and is not restarted by later ones, so a continuation only joins if it arrives inside interval.

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiogram_buffered_router-0.3.0.tar.gz (9.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiogram_buffered_router-0.3.0-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file aiogram_buffered_router-0.3.0.tar.gz.

File metadata

  • Download URL: aiogram_buffered_router-0.3.0.tar.gz
  • Upload date:
  • Size: 9.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for aiogram_buffered_router-0.3.0.tar.gz
Algorithm Hash digest
SHA256 61ec7c8e21a7821a96c3e9f726173b96796a96c1b484811bf4c1955891568fd3
MD5 c17d578ecbf3e38384e4d6675560623f
BLAKE2b-256 f382b942188d4db2d1c0c7b4947270d8141e077b3096ec3c348223620b0b8967

See more details on using hashes here.

File details

Details for the file aiogram_buffered_router-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: aiogram_buffered_router-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 8.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for aiogram_buffered_router-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8ec8843d255bc01e49d61e3fe7f0fe007f9a17503534a098c15188a1adddaa48
MD5 e361cf7b223303bc801782746f9a8b21
BLAKE2b-256 b066d69026afe092337025752d0295efd1a25d54e78f58e8a833ffbc4bf6cf13

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page