Here’s a structured coding rule set for developing Telegram bots with Python 3.12+ and aiogram3 (based on your knowledge base and best practices):
# Use Poetry for dependency management (recommended in and ):
poetry init # Initialize project
poetry add aiogram[fast] # Install aiogram3 with optional dependencies
poetry add pytest pytest-asyncio pytest-mock --group dev # Add testing tools
# Run the bot in development mode:
poetry run python -m bot.main --env development # Example entry point
# Linting and formatting:
poetry run black . # Code formatting (PEP8)
poetry run flake8 . # Static type checking
poetry run mypy bot/ # Type hints validation
# Run unit and integration tests:
poetry run pytest tests/ --cov=bot # With coverage reporting
# Run tests in debug mode:
poetry run pytest --pdb # Drop into debugger on failure
Unit Tests
pytest
and pytest-asyncio
for asynchronous tests (as in and ).pytest-mock
or aioresponses
to avoid hitting real endpoints.from aiogram import Bot
from aioresponses import aioresponses
async def test_send_message(mocker):
with aioresponses() as m:
m.post("https://api.telegram.org/bot/sendMessage", status=200)
await bot.send_message(chat_id=123, text="Test")
Integration Tests
Code Coverage
CI/CD Integration
PEP8 Compliance
black
and flake8
.Asynchronous Patterns
async/await
for all handlers (aiogram3 requires this ).Error Handling
try/except
for aiogram.exceptions.TelegramAPIError
.try:
await bot.send_message(chat_id=chat_id, text=text)
except TelegramAPIError as e:
logging.error(f"API Error: {e}")
Code Structure
bot/
: Main bot logic (handlers, middlewares).services/
: External services (e.g., VK API interactions).tests/
: Test cases.Type Hints
mypy
.async def handle_message(update: types.Message, state: FSMContext) -> None:
...
State Machines
class UserState(StatesGroup):
waiting_for_input = State()
@dp.message_handler(commands=["start"])
async def start_handler(message: types.Message, state: FSMContext):
await state.set_state(UserState.waiting_for_input)
Docstrings
async def send_vk_post(chat_id: int, post: dict) -> None:
"""Send a VK post to a Telegram channel.
Args:
chat_id (int): Target Telegram chat ID.
post (dict): VK post data (text, media, etc.).
Raises:
ValueError: If post data is invalid.
"""
README.md
poetry install
).TELEGRAM_TOKEN
, VK_SERVICE_KEY
).poetry run python -m bot.main --token $TELEGRAM_TOKEN
API Documentation
sphinx
or mkdocs
for documenting public APIs (if applicable).Contributing Guidelines
CONTRIBUTING.md
file with:
Let me know if you need further details!