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_datalimit. 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(viaScopeRegistry) - Nested dependencies (
subdepends),Fromextractor,DependFilter, andDependExit
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-userkey="..."— custom rate-limit key- Custom
RateLimitAnswer— control the response when the limit is exceeded - Redis storage — share limits across bot restarts and multiple instances
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
💾 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:
- Dependency Injection — classes, scopes, overrides, sub-dependencies
- Rate Limiting — basic usage, algorithms, advanced configuration
- Callback Data — basic usage, custom answers, Redis storage
🤝 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.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| aiogram_tool-1.2.3.tar.gz | 132.3 kB | Without provenance | Details for aiogram_tool-1.2.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| aiogram_tool-1.2.3-py3-none-any.whl | Python 3 | none | any | Details for aiogram_tool-1.2.3-py3-none-any.whl |
Total release size: 161.4 kB
Release files / aiogram_tool-1.2.3.tar.gz
| Download URL | aiogram_tool-1.2.3.tar.gz |
|---|---|
| Size | 132.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
755e11de70dd4cf706e066b4e31b94af110abffaa0fd28f037919ffeb21072d1
|
|
BLAKE2b-256 checksum How to use checksums |
707209894b0f08a5b8794b938c681feaa1bb6f6708a844fb01d99be97172da71
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","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.3-py3-none-any.whl
| Download URL | aiogram_tool-1.2.3-py3-none-any.whl |
|---|---|
| Size | 29.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f9d6a4d4726c7ee5e46c74f09993d08e41095ab4b71dfb4bd2fe8ef264f53320
|
|
BLAKE2b-256 checksum How to use checksums |
bf1de047d078cd12ee6550d498522ed413eaa08652b51250e130600f21a3cd09
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","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.3
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.