Skip to main content

aiogram_tool

A collection of powerful tools and utilities for aiogram 3.x — dependency injection, rate limiting, and long callback data support.

✨ Features

  • Dependency Injection — inject dependencies into handlers with Depends(), similar to FastAPI. Supports classes, functions, scopes (SINGLETON, REQUEST, TRANSIENT), nested dependencies, and more.
  • Rate Limiter — limit how often handlers can be called. Three built-in algorithms: Fixed Window, Sliding Window, and Token Bucket. Works per-user or globally.
  • Long Callback Data — bypass Telegram's 64-byte callback_data limit. Pack large payloads into inline keyboard buttons transparently.
  • Pluggable Storage — Memory, Redis, and File storage backends for persisting rate-limit and callback data state.

📦 Installation

Requires Python 3.11+ and aiogram 3.x.

pip

pip install aiogram_tool

Poetry

poetry add aiogram_tool

uv

uv add aiogram_tool

🚀 Quick Start

Register tools on your dispatcher with aiogram_tool_setup:

from aiogram import Bot, Dispatcher
from aiogram_tool.tools.setup import aiogram_tool_setup
from aiogram_tool.tools.depend import DependTool
from aiogram_tool.tools.limit import RateLimitTool

bot = Bot("YOUR_TOKEN_HERE")
dp = Dispatcher()

aiogram_tool_setup(dp, [DependTool(), RateLimitTool()])

await dp.start_polling(bot)

🧰 Tools

Dependency Injection

Inject dependencies into handlers via default argument values — no middleware boilerplate required.

from aiogram_tool.tools.setup import aiogram_tool_setup
from aiogram_tool.tools.depend import Depends, DependTool, ScopeRegistry, Scope

scope_registry = ScopeRegistry()


class CounterService:
    def __init__(self) -> None:
        self.count = 0

    async def __call__(self, context) -> dict:
        self.count += 1
        return {"current_count": self.count}


counter = CounterService()
scope_registry.register(counter, Scope.REQUEST)

# Pass the registry to the tool during setup
aiogram_tool_setup(dp, [DependTool(scope_registry=scope_registry)])


@dp.message(CommandStart())
async def start_handler(message: Message, stats: dict = Depends(counter)):
    await message.answer(f"Pressed: {stats['current_count']} times")

Highlights:

  • Works with functions, class-functors, and __init__ methods
  • Scopes: SINGLETON, REQUEST, TRANSIENT (via ScopeRegistry)
  • Nested dependencies (subdepends), From extractor, DependFilter, and DependExit

📖 Full documentation: EN | RU

Rate Limiter

Limit handler calls with three built-in algorithms:

from datetime import timedelta
from aiogram_tool.tools.limit import RateLimitTool, RateLimitFilter
from aiogram_tool.tools.limit.rate_limit import SlidingWindowRateLimit


@dp.message(
    Command("ping"),
    # 3 requests per 10 seconds per user
    RateLimitFilter(
        rate_limit=SlidingWindowRateLimit(
            requests=3,
            time=timedelta(seconds=10),
        )
    ),
)
async def ping_handler(message: Message):
    await message.answer("Pong!")

Available algorithms:

Algorithm Description
FixedWindowRateLimit N requests per fixed time window
SlidingWindowRateLimit More accurate; prevents bursts at window edges
TokenBucketRateLimit Bucket of tokens that refills over time

Extras:

  • all_users=True — apply the limit globally instead of per-user
  • key="..." — custom rate-limit key
  • Custom RateLimitAnswer — control the response when the limit is exceeded
  • Redis storage — share limits across bot restarts and multiple instances

📖 Full documentation: EN | RU

Long Callback Data

Telegram limits callback_data to 64 bytes. LongCallbackData automatically stores oversized payloads and restores them when the callback arrives — with the same familiar aiogram API.

from aiogram import Bot, Dispatcher, F
from aiogram.filters import CommandStart
from aiogram.types import (
    CallbackQuery,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    Message,
)
from aiogram_tool.tools.callback_data import LongCallbackData

bot = Bot("YOUR_TOKEN_HERE")
dp = Dispatcher()


class MyData(LongCallbackData, prefix="mydata"):
    mode: str
    payload: str


@dp.message(CommandStart())
async def start_handler(message: Message):
    # Short data is packed as usual; long data is stored transparently
    short_cb = await MyData(mode="short", payload="Hello!").pack_long()
    long_cb = await MyData(mode="long", payload="A" * 200).pack_long()

    await message.answer(
        "Choose an action:",
        reply_markup=InlineKeyboardMarkup(
            inline_keyboard=[
                [InlineKeyboardButton(text="Short data", callback_data=short_cb)],
                [InlineKeyboardButton(text="Long data", callback_data=long_cb)],
            ]
        ),
    )


# Filter exactly like standard aiogram CallbackData
@dp.callback_query(MyData.filter(F.mode == "long"))
async def handler(query: CallbackQuery, callback_data: MyData):
    # Original data is fully available despite the 64-byte limit
    await query.answer(text=f"Received: {callback_data.payload}")

By default data is kept in in-memory storage. Use Redis to persist it across restarts:

from redis.asyncio import Redis as AsyncRedis
from aiogram_tool.storage import AsyncRedisLockStorage


class PersistentData(LongCallbackData, prefix="redis"):
    _storage = AsyncRedisLockStorage(redis=AsyncRedis(), expire=3600)
    user_id: int
    big_context: str

📖 Full documentation: EN | RU

💾 Storage Backends

Storage Persistence Lock support
MemoryStorage / MemoryLockStorage In-memory ✅
AsyncRedisStorage / AsyncRedisLockStorage Redis (survives restarts) ✅
FileStorage / FileLockStorage Local files ✅

📁 Examples

Ready-to-run examples are available in the examples/ directory:

🤝 Contributing

Contributions are welcome! Please read CONTRIBUTING.md for guidelines.

📄 License

This project is licensed under the terms of the LICENSE.md.

Metadata

Release files for aiogram-tool 1.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aiogram-tool 1.2.2
File Size Uploaded Provenance Actions
aiogram_tool-1.2.2.tar.gz 126.1 kB Without provenance Details for aiogram_tool-1.2.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aiogram-tool 1.2.2
File Interpreter ABI Platform Actions
aiogram_tool-1.2.2-py3-none-any.whl Python 3 none any Details for aiogram_tool-1.2.2-py3-none-any.whl

Total release size: 155.2 kB

Release files / aiogram_tool-1.2.2.tar.gz

Download URL aiogram_tool-1.2.2.tar.gz
Size 126.1 kB
Tags Source
SHA-256 checksum
How to use checksums
8c558644b9c42cb38f47940411503c19bc012550ebe57aca9c52a42e9daf3d0b
BLAKE2b-256 checksum
How to use checksums
06f71062af82efcfc2516c23fb4b8e5eb2533640a66d99cc65fa14be4795e914
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.7 {"installer":{"name":"uv","version":"0.12.7","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}

Release files / aiogram_tool-1.2.2-py3-none-any.whl

Download URL aiogram_tool-1.2.2-py3-none-any.whl
Size 29.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
98744b6de573eea1a74c3d83d9a864580c341be2eda6ed20919e1ae4954671a4
BLAKE2b-256 checksum
How to use checksums
b58095f6d46d153a9dc592a3bc43967a5b2bfff06dd9186a89eb276f6f63841d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.7 {"installer":{"name":"uv","version":"0.12.7","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}

Security for aiogram-tool 1.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page