Files
telegram-helper-bot/helper_bot/main_with_metrics.py
Andrey c68db87901 Refactor project structure and enhance Docker support
- Removed unnecessary `__init__.py` and `Dockerfile` to streamline project organization.
- Updated `.dockerignore` and `.gitignore` to improve exclusion patterns for build artifacts and environment files.
- Enhanced `Makefile` with new commands for managing Docker containers and added help documentation.
- Introduced `pyproject.toml` for better project metadata management and dependency tracking.
- Updated `requirements.txt` to reflect changes in dependencies for metrics and monitoring.
- Refactored various handler files to improve code organization and maintainability.
2025-08-29 16:49:28 +03:00

118 lines
3.8 KiB
Python

"""
Example integration of metrics monitoring in the main bot file.
This shows how to integrate the metrics system without modifying existing handlers.
"""
import asyncio
import logging
from aiogram import Bot, Dispatcher
from aiogram.enums import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage
# Import metrics components
from .utils.metrics import metrics
from .utils.metrics_exporter import MetricsManager
from .middlewares.metrics_middleware import MetricsMiddleware, ErrorMetricsMiddleware
# Import your existing bot components
# from .handlers import ... # Your existing handlers
# from .database.db import BotDB # Your existing database class
class BotWithMetrics:
"""Bot class with integrated metrics monitoring."""
def __init__(self, token: str, metrics_port: int = 8000):
self.bot = Bot(token=token, parse_mode=ParseMode.HTML)
self.storage = MemoryStorage()
self.dp = Dispatcher(storage=self.storage)
# Initialize metrics manager
# You can pass your database instance here if needed
# self.metrics_manager = MetricsManager(port=metrics_port, db=your_db_instance)
self.metrics_manager = MetricsManager(port=metrics_port)
# Setup middlewares
self._setup_middlewares()
# Setup handlers (your existing handlers)
# self._setup_handlers()
self.logger = logging.getLogger(__name__)
def _setup_middlewares(self):
"""Setup metrics middlewares."""
# Add metrics middleware first to capture all events
self.dp.message.middleware(MetricsMiddleware())
self.dp.callback_query.middleware(MetricsMiddleware())
# Add error tracking middleware
self.dp.message.middleware(ErrorMetricsMiddleware())
self.dp.callback_query.middleware(ErrorMetricsMiddleware())
# Your existing middlewares can go here
# self.dp.message.middleware(YourExistingMiddleware())
def _setup_handlers(self):
"""Setup bot handlers."""
# Import and register your existing handlers here
# from .handlers.admin import admin_router
# from .handlers.private import private_router
# from .handlers.group import group_router
# from .handlers.callback import callback_router
#
# self.dp.include_router(admin_router)
# self.dp.include_router(private_router)
# self.dp.include_router(group_router)
# self.dp.include_router(callback_router)
pass
async def start(self):
"""Start the bot with metrics."""
try:
# Start metrics collection
await self.metrics_manager.start()
self.logger.info("Metrics system started")
# Start bot polling
await self.dp.start_polling(self.bot)
except Exception as e:
self.logger.error(f"Error starting bot: {e}")
raise
finally:
await self.stop()
async def stop(self):
"""Stop the bot and metrics."""
try:
# Stop metrics collection
await self.metrics_manager.stop()
self.logger.info("Metrics system stopped")
# Stop bot
await self.bot.session.close()
self.logger.info("Bot stopped")
except Exception as e:
self.logger.error(f"Error stopping bot: {e}")
# Example usage function
async def main():
"""Main function to run the bot with metrics."""
# Your bot token
TOKEN = "YOUR_BOT_TOKEN_HERE"
# Create and start bot
bot = BotWithMetrics(TOKEN)
try:
await bot.start()
except KeyboardInterrupt:
await bot.stop()
if __name__ == "__main__":
asyncio.run(main())