To add new variables (i.e., dependencies or additional parameters) to your handler in Aiogram 3, you can utilize dependency injection. Aiogram 3 provides a flexible way to inject dependencies into your handlers using the built-in DI (Dependency Injection) system. Here's a step-by-step guide on how to achieve this:
1. Understand the Current Handler
Your current handler looks like this:
@chat_router.message(
F.text.contains(' '),
Command(
*commands,
ignore_case=True,
),
)
@flags.chat_action(initial_sleep=1, action='typing', interval=3)
async def chat_handler(
message: Message,
sd: fai.AiService,
glif_service: glif.AiService,
YandeGPT: neuro.YandexGPT,
) -> None:
# Handler logic
pass
Here, sd, glif_service, and YandeGPT are dependencies being injected into the handler.
2. Define the New Dependency
Suppose you want to add a new service called NewService. First, ensure that this service is properly defined and can be injected. For example:
class NewService:
def __init__(self):
# Initialize your service
pass
async def perform_action(self):
# Define some action
pass
3. Register the Dependency in the DI Container
Aiogram 3 uses a dependency injection container named Bot. To register your new service, you can use the bind method or factory functions.
Using bind:
from aiogram import Bot
from aiogram.fsm.storage.memory import MemoryStorage
bot = Bot(token='YOUR_BOT_TOKEN')
storage = MemoryStorage()
# Create an instance of NewService
new_service = NewService()
# Bind the service to the DI container
bot.get('di').bind(NewService, new_service)
Using a Factory Function:
If your service needs to be instantiated per request or has asynchronous initialization:
async def new_service_factory() -> NewService:
service = NewService()
# Perform any async initialization if needed
return service
bot.get('di').bind_factory(NewService, new_service_factory)
4. Add the New Dependency to the Handler
Now that NewService is registered in the DI container, you can add it as a parameter to your handler:
@chat_router.message(
F.text.contains(' '),
Command(
*commands,
ignore_case=True,
),
)
@flags.chat_action(initial_sleep=1, action='typing', interval=3)
async def chat_handler(
message: Message,
sd: fai.AiService,
glif_service: glif.AiService,
YandeGPT: neuro.YandexGPT,
new_service: NewService, # New dependency added here
) -> None:
# Now you can use new_service within your handler
await new_service.perform_action()
# Rest of your handler logic
pass
5. Complete Example
Here's how the complete setup might look:
from aiogram import Bot, Dispatcher, F
from aiogram.types import Message
from aiogram.filters import Command
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.di import Container
# Define your services
class NewService:
def __init__(self):
# Initialization logic
pass
async def perform_action(self):
# Action logic
pass
# Initialize Bot and Dispatcher
bot = Bot(token='YOUR_BOT_TOKEN')
storage = MemoryStorage()
dispatcher = Dispatcher(storage=storage)
# Create and bind services
sd_service = fai.AiService()
glif_service = glif.AiService()
yandex_gpt = neuro.YandexGPT()
new_service = NewService()
container = dispatcher.container
container.bind(fai.AiService, sd_service)
container.bind(glif.AiService, glif_service)
container.bind(neuro.YandexGPT, yandex_gpt)
container.bind(NewService, new_service)
# Define router
chat_router = Router()
@chat_router.message(
F.text.contains(' '),
Command(
*commands,
ignore_case=True,
),
)
@flags.chat_action(initial_sleep=1, action='typing', interval=3)
async def chat_handler(
message: Message,
sd: fai.AiService,
glif_service: glif.AiService,
YandeGPT: neuro.YandexGPT,
new_service: NewService, # Added new dependency
) -> None:
await new_service.perform_action()
# Your handler logic here
dispatcher.include_router(chat_router)
# Start polling or set up your executor
import asyncio
async def main():
await dispatcher.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
6. Notes and Best Practices
-
Asynchronous Initialization: If your new service requires asynchronous initialization (e.g., database connections), use a factory function with bind_factory as shown above.
-
Singleton vs. Per-Handler Instances: Decide whether your service should be a singleton (shared across handlers) or a new instance per handler invocation. The binding method (bind vs. bind_factory) will affect this.
-
Error Handling: Ensure that your dependencies are properly instantiated and handle any potential exceptions during their creation.
-
Type Annotations: Use accurate type annotations for better editor support and to leverage static type checking.
7. Additional Resources
- Aiogram 3 Documentation: Aiogram DI
- Dependency Injection in Aiogram: Helps manage dependencies effectively, making your code more modular and testable.
- Community Examples: Exploring community examples and repositories can provide further insights and patterns for dependency management.
By following these steps, you can seamlessly add new variables or dependencies to your handlers in Aiogram 3, enhancing the modularity and scalability of your Telegram bot.