Spaces:
1
Sleeping

1 / AGENTS.md
dycd's picture
Add bot files
5203d08
|
Raw History Blame Contribute Delete
6.87 kB

AGENTS.md - Agent Guidelines for This Repository

Project Overview

This is a simple Telegram bot built with aiogram 3.x. The bot runs using Python asyncio and responds to the /start command.

Build & Run Commands

Installation

pip install -r requirements.txt

Running the Bot

python main.py

Testing

This project does not currently have a test suite. When adding tests:

  • Use pytest as the test framework
  • Run all tests: pytest
  • Run a single test: pytest path/to/test_file.py::test_function_name
  • Run tests matching a pattern: pytest -k "test_name_pattern"

Linting & Type Checking

This project uses the following tools:

  • ruff: Fast Python linter (install via pip install ruff)
    • Run linting: ruff check .
    • Auto-fix issues: ruff check . --fix
  • mypy: Static type checker for Python
    • Run type checking: mypy .

Code Style Guidelines

General Principles

  • Follow PEP 8 style guide
  • Keep functions small and focused (ideally < 50 lines)
  • Use meaningful variable and function names
  • Add type hints to all function signatures

Imports

  • Standard library imports first
  • Third-party imports second
  • Local imports last
  • Group imports within each category alphabetically
  • Use explicit relative imports for local modules

Example:

import asyncio
from pathlib import Path

from aiogram import Bot, Dispatcher, types
from aiogram.filters import Command

from . import handlers, utils

Formatting

  • Maximum line length: 100 characters
  • Use 4 spaces for indentation (no tabs)
  • Use trailing commas in multi-line collections
  • Use f-strings for string formatting

Naming Conventions

  • snake_case for functions, variables, and methods
  • PascalCase for classes and types
  • SCREAMING_SNAKE_CASE for constants
  • Prefix private functions/variables with underscore: _private_function()

Type Hints

Always include type hints in function signatures:

def process_message(message: types.Message) -> str:
    ...

async def handle_callback(callback: types.CallbackQuery) -> None:
    ...

Error Handling

  • Use specific exception types, not bare except:
  • Log errors before re-raising or handling
  • Return meaningful error messages to users
  • Never expose sensitive information in error messages

Example:

try:
    await some_async_operation()
except SpecificError as e:
    logger.error(f"Operation failed: {e}")
    await message.answer("An error occurred. Please try again.")

Async/Await

  • Always use async def for asynchronous functions
  • Use asyncio.run() to execute async main functions
  • Avoid blocking calls in async context
  • Use await for all async operations

Bot Configuration

  • Store sensitive values (tokens, API keys) in environment variables
  • Never hardcode credentials in source code
  • Use os.environ.get() or python-dotenv for configuration

File Structure (Recommended for Growth)

.
├── main.py              # Entry point
├── config.py            # Configuration/environment variables
├── handlers/           # Message/command handlers
│   ├── __init__.py
│   ├── commands.py
│   └── messages.py
├── keyboards/           # Inline/reply keyboards
├── middlewares/         # Custom middlewares
├── utils/               # Helper functions
├── tests/               # Test files
└── requirements.txt

Security Notes

  • Never commit secrets, tokens, or API keys to version control
  • Use .env files for local development (add to .gitignore)
  • The current main.py contains a hardcoded token - this should be moved to environment variables before production use

Dependencies

  • aiogram==3.4.1 (Telegram bot framework)

aiogram-Specific Guidelines

Dispatcher and Router Pattern

Use Dispatcher for global handlers and Router for modular handler organization:

from aiogram import Dispatcher, Router

dp = Dispatcher()
router = Router()

@router.message(Command("help"))
async def cmd_help(message: types.Message):
    await message.answer("Help text")

dp.include_router(router)

Bot and Token Management

  • Always create Bot instance with token
  • Use context managers or proper cleanup for Bot instances
  • Pass Bot to handlers via dependency injection when needed

Message Handlers

  • Use appropriate filters to avoid redundant checks
  • Always acknowledge callbacks with callback.answer() or callback.message.answer()
  • Use state for conversation flows with FSM

Keyboard Construction

  • Use InlineKeyboardBuilder or ReplyKeyboardBuilder for keyboards
  • Keep keyboard callback data structured and parseable
  • Example:
from aiogram.utils.keyboard import InlineKeyboardBuilder

builder = InlineKeyboardBuilder()
builder.button(text="Click me", callback_data="action:click")
await message.answer("Choose:", reply_markup=builder.as_markup())

Filters and Middlewares

  • Leverage built-in filters from aiogram.filters
  • Create custom filters for reusable logic
  • Use middlewares for cross-cutting concerns (logging, rate limiting)

Types Reference

  • types.Message - regular messages
  • types.CallbackQuery - inline button callbacks
  • types.ChatMemberUpdated - chat member changes
  • types.PreCheckoutQuery - payment pre-checkout
  • types.ShippingQuery - shipping queries

Working with This Repository

Current Code Structure

The bot currently has minimal structure:

  • main.py - Contains bot initialization, dispatcher setup, and command handlers

Adding New Commands

  1. Import necessary types and filters
  2. Decorate handler functions with @dp.message(Command("your_command"))
  3. Use async functions and await aiogram methods

Environment Setup for Development

  1. Create a .env file for local development
  2. Add BOT_TOKEN=your_token_here to the .env file
  3. Ensure .env is in .gitignore

Running Specific Tests

# Run all tests
pytest

# Run a specific test file
pytest tests/test_handlers.py

# Run a specific test function
pytest tests/test_handlers.py::test_start_command

# Run tests matching a pattern
pytest -k "test_command"

# Run with verbose output
pytest -v

# Run with coverage (if pytest-cov is installed)
pytest --cov=. --cov-report=term-missing

Code Quality Workflow

Before committing changes:

  1. Run ruff: ruff check .
  2. Run mypy: mypy .
  3. Run tests: pytest
  4. Fix any issues found

Common Issues and Solutions

  • Bot not responding: Check token validity and network connectivity
  • Handler not triggering: Verify filter order and dispatcher inclusion
  • Memory leaks: Ensure proper Bot cleanup with bot.session.close()
  • Type errors: Use proper types from aiogram.types module