egorhowlbar/slug icon
public
Published on 4/11/2025
Python Expert

Rules
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):

---

### **Build & Development Commands**  
#### Dependencies Management  
```python
# 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
```

#### Development Workflow  
```python
# 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
```

#### Testing Commands  
```python
# 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
```

---

### **Testing Guidelines**  
1. **Unit Tests**  
   - Use `pytest` and `pytest-asyncio` for asynchronous tests (as in  and ).  
   - Mock Telegram API interactions with `pytest-mock` or `aioresponses` to avoid hitting real endpoints.  
   - Example:  
     ```python
     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")
     ```

2. **Integration Tests**  
   - Test with a **test Telegram bot** (create one via [@BotFather](https://t.me/BotFather)).  
   - Validate interactions with VK API (if needed) using mocked responses.  

3. **Code Coverage**  
   - Aim for >90% coverage for critical paths (message handlers, API calls).  

4. **CI/CD Integration**  
   - Use GitHub Actions/CI to run tests and linting on pull requests (inspired by ).  

---

### **Code Style & Guidelines**  
#### **Core Principles**  
1. **PEP8 Compliance**  
   - Enforce with `black` and `flake8`.  
   - Limit line length to 100 characters.  

2. **Asynchronous Patterns**  
   - Use `async/await` for all handlers (aiogram3 requires this ).  
   - Avoid blocking calls in event loop threads.  

3. **Error Handling**  
   - Catch Telegram API errors using `try/except` for `aiogram.exceptions.TelegramAPIError`.  
   - Example:  
     ```python
     try:
         await bot.send_message(chat_id=chat_id, text=text)
     except TelegramAPIError as e:
         logging.error(f"API Error: {e}")
     ```

4. **Code Structure**  
   - Organize code into:  
     - `bot/`: Main bot logic (handlers, middlewares).  
     - `services/`: External services (e.g., VK API interactions).  
     - `tests/`: Test cases.  
   - Use **Dependency Injection** for services (e.g., VK client).  

5. **Type Hints**  
   - Annotate all functions and variables with `mypy`.  
   - Example:  
     ```python
     async def handle_message(update: types.Message, state: FSMContext) -> None:
         ...
     ```

6. **State Machines**  
   - For complex workflows, use aiogram3’s **Finite State Machine (FSM)** (as in ).  
   - Example:  
     ```python
     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)
     ```

---

### **Documentation Guidelines**  
1. **Docstrings**  
   - Use **Google-style** docstrings for functions and classes.  
   - Example:  
     ```python
     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.
         """
     ```

2. **README.md**  
   - Include:  
     - Setup instructions (e.g., `poetry install`).  
     - Environment variables (e.g., `TELEGRAM_TOKEN`, `VK_SERVICE_KEY`).  
     - Quickstart example:  
       ```bash
       poetry run python -m bot.main --token $TELEGRAM_TOKEN
       ```

3. **API Documentation**  
   - Use `sphinx` or `mkdocs` for documenting public APIs (if applicable).  

4. **Contributing Guidelines**  
   - Add a `CONTRIBUTING.md` file with:  
     - Code style rules.  
     - Testing requirements.  
     - Pull request process.  

---

### **References**  
- aiogram3 documentation for async patterns: , ,   
- FSM implementation examples:   
- Testing best practices: ,   

Let me know if you need further details!