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 import Bot, Dispatcher
from aiogram.filters import CommandStart
from aiogram.types import Message
from aiogram_tool.tools.setup import aiogram_tool_setup
from aiogram_tool.tools.depend import Depends, DependTool, ScopeRegistry, Scope

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

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
  • Call dependencies manually from middleware via data["resolver"] and resolver.resolve()

📖 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.6

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.6
File Size Uploaded Provenance Actions
aiogram_tool-1.2.6.tar.gz 171.4 kB Without provenance Details for aiogram_tool-1.2.6.tar.gz

Built distribution (wheel)

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

Total release size: 200.7 kB

Release files / aiogram_tool-1.2.6.tar.gz

Download URL aiogram_tool-1.2.6.tar.gz
Size 171.4 kB
Tags Source
SHA-256 checksum
How to use checksums
6e6f0e90786955186698b0a1e912ffa5d75c92cce8f203a8ef8501b5c2da6559
BLAKE2b-256 checksum
How to use checksums
04477e1909c311e4ae1d2035a4f6ade61bbfa3b348510fc1a1a7e07e01eaf790
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","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.6-py3-none-any.whl

Download URL aiogram_tool-1.2.6-py3-none-any.whl
Size 29.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8e64ee992805ed42ab79ce050df1662aa90b7312e5bba43cd3048899721b53bc
BLAKE2b-256 checksum
How to use checksums
ff0bdd7709a9a54cda17c6e1073fc35a6532a86c9b328ab5e2b661dad95e9171
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","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.6

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