Skip to main content

A package for improving and automating the work with Routers in asynchronous Telegram frameworks (e.g., Aiogram). It allows for dynamically finding, importing, and binding routers, as well as managing their dependencies (Middleware) during runtime.

Project description

KTGUtils: Dynamic Router & Middleware Manager for Aiogram

KTGUtils is a lightweight utility package designed to significantly enhance router management and development efficiency within Aiogram (v3+)-based Telegram bots. It provides an elegant solution for automatically discovering, loading, and refreshing your bot's routing logic.

🌟 Key Features

  • Dynamic Router Discovery: Automatically scans a specified package (folder) to find all Router instances defined in separate modules.
  • Hot Reloading Support: Unlike standard Python imports, this manager can explicitly reload router modules at runtime. This is invaluable for development, allowing you to quickly test changes to handlers or filters without restarting the entire bot.
  • Automated Middleware Binding: Simplifies the complex process of attaching your custom Middleware classes to the dispatcher's handlers.

📦 Installation

Since your package is likely called ktgutils on PyPI:

pip install ktgutils

🚀 Usage

1. Router Management

Define your routers as usual in separate files (e.g., handlers/user_commands.py, handlers/admin.py).

# main.py

from aiogram import Dispatcher
from ktgutils import RouterManager

# Initialize Dispatcher
dp = Dispatcher()

# Initialize Router Manager
router_manager = RouterManager(dp=dp)

# Bind all routers found inside the 'handlers' package
router_manager.bind_routers("handlers")

# --- Development Use Case (Hot Reloading) ---
# If you make changes to a handler file (e.g., handlers/user_commands.py)
# while the bot is running, simply call this again to refresh the logic:
# router_manager.bind_routers("handlers") 
# (Note: bind_routers automatically clears and reloads/rebinds)

# To manually clear all bound routers:
# router_manager.unbind_routers()

2. Automated Middleware Application

Applying the same Middleware to both message handlers and callback queries can be repetitive. Use the @RouterManager.apply_middleware decorator to handle this automatically when the Middleware class is instantiated.

# middleware/user_check.py

from ktgutils import RouterManager
from aiogram.types import Message, CallbackQuery

# Note: The decorator MUST be applied via the RouterManager instance/class
@RouterManager.apply_middleware
class UserCheckMiddleware:
    def __init__(self, user_role: str):
        # This original __init__ is called first
        self.role = user_role

    async def __call__(self, handler, event: Message | CallbackQuery, data: dict):
        # Your actual middleware logic
        # For example:
        # if data.get('user_role') != self.role:
        #     return # Block the handler

        return await handler(event, data)

# --- In your main bot setup ---

# Instantiate the Middleware class. The decorator handles binding to the dispatcher.
user_middleware = UserCheckMiddleware(user_role="admin")

⚙️ How It Works

The core functionality is provided by the get_routers method, which uses Python's built-in pkgutil.walk_packages to recursively scan the specified directory. It then uses importlib.reload(module) to bypass the standard Python module cache (sys.modules) and load the latest version of the module from the disk, ensuring that all defined router objects are up-to-date before being bound to the Dispatcher.

Project details


Download files

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

Source Distribution

ktgutils-0.1.1.tar.gz (3.8 kB view details)

Uploaded Source

Built Distribution

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

ktgutils-0.1.1-py3-none-any.whl (3.9 kB view details)

Uploaded Python 3

File details

Details for the file ktgutils-0.1.1.tar.gz.

File metadata

  • Download URL: ktgutils-0.1.1.tar.gz
  • Upload date:
  • Size: 3.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for ktgutils-0.1.1.tar.gz
Algorithm Hash digest
SHA256 8ada183760838d16a8bcc9df9b52135f4d90e666efd3c639f469dc8a92c2b0bb
MD5 0fb50a3eaf2bcf1599ccd47e05c9c9e3
BLAKE2b-256 73e2933b5a40323569477fa2450db4c34d94d348302d0bab4e297e60070ac3fa

See more details on using hashes here.

File details

Details for the file ktgutils-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: ktgutils-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 3.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for ktgutils-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f566fe1196e18eb1bf5cec3c9f752e79cb1bc4b41091b821ae2849166ab57656
MD5 16fe2b5849bf98d820dddb1764bf7b91
BLAKE2b-256 16aaff1a1b6925ea15fe0ee2d41d61accab87e6ef39b6682e4371db9cafd8749

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 Pingdom Monitoring Sentry Error logging StatusPage Status page