This guide provides guidelines for developing new bots and contributing to existing ones.
bot-name/
├── README.md # Bot documentation
├── bot.py # Main bot class
├── config.yml # Bot configuration
├── requirements.txt # Python dependencies
├── tests/ # Unit tests
│ ├── __init__.py
│ ├── test_bot.py
│ └── fixtures/ # Test data
└── utils/ # Helper functions
├── __init__.py
└── helpers.py
Define:
# Create bot directory
mkdir -p bots/my-new-bot/tests/fixtures
cd bots/my-new-bot
# Create basic files
touch README.md bot.py config.yml requirements.txt
touch tests/__init__.py tests/test_bot.py
# bot.py
"""
My New Bot - Brief description
This bot does X, Y, and Z.
"""
from typing import Dict, Any, Optional
import logging
class MyNewBot:
"""
Main bot class for My New Bot.
Attributes:
config: Bot configuration dictionary
logger: Python logger instance
"""
def __init__(self, config: Optional[Dict[str, Any]] = None):
"""
Initialize the bot.
Args:
config: Optional configuration dictionary
"""
self.config = config or {}
self.logger = logging.getLogger(__name__)
self._setup()
def _setup(self):
"""Initialize bot resources and connections."""
self.logger.info("Setting up bot...")
# Initialize Azure services, databases, etc.
def process(self, input_data: Any) -> Dict[str, Any]:
"""
Main processing function.
Args:
input_data: Input to process
Returns:
Dictionary with processing results
Raises:
ValueError: If input is invalid
RuntimeError: If processing fails
"""
try:
# Validate input
self._validate_input(input_data)
# Process
result = self._do_processing(input_data)
# Log result
self.logger.info(f"Processed: {result}")
return result
except Exception as e:
self.logger.error(f"Error processing: {e}")
raise
def _validate_input(self, input_data: Any) -> None:
"""Validate input data."""
if not input_data:
raise ValueError("Input cannot be empty")
def _do_processing(self, input_data: Any) -> Dict[str, Any]:
"""
Perform the actual processing.
Override this method in subclasses.
"""
return {"status": "success", "data": input_data}
# CLI interface
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="My New Bot")
parser.add_argument("--file", help="Input file path")
parser.add_argument("--config", help="Config file path")
args = parser.parse_args()
# Load config if provided
config = {}
if args.config:
import yaml
with open(args.config) as f:
config = yaml.safe_load(f)
# Create and run bot
bot = MyNewBot(config)
result = bot.process(args.file)
print(result)
# config.yml
bot_name: my-new-bot
version: 1.0.0
# Capacity limits
capacity:
max_operations_per_day: 5000
max_concurrent: 4
timeout_seconds: 30
# Processing settings
processing:
retry_attempts: 3
retry_delay_seconds: 5
batch_size: 10
# Logging
logging:
level: INFO
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
# Dependencies
azure:
cognitive_services:
enabled: true
endpoint: ${AZURE_COGNITIVE_ENDPOINT}
key: ${AZURE_COGNITIVE_KEY}
# tests/test_bot.py
"""
Unit tests for My New Bot
"""
import pytest
from bots.my_new_bot.bot import MyNewBot
class TestMyNewBot:
"""Test suite for MyNewBot class."""
@pytest.fixture
def bot(self):
"""Create a bot instance for testing."""
return MyNewBot(config={"test_mode": True})
def test_initialization(self, bot):
"""Test bot initializes correctly."""
assert bot is not None
assert bot.config["test_mode"] is True
def test_process_valid_input(self, bot):
"""Test processing with valid input."""
result = bot.process("test input")
assert result["status"] == "success"
def test_process_invalid_input(self, bot):
"""Test processing with invalid input."""
with pytest.raises(ValueError):
bot.process(None)
def test_validate_input(self, bot):
"""Test input validation."""
# Valid input should not raise
bot._validate_input("valid")
# Invalid input should raise
with pytest.raises(ValueError):
bot._validate_input(None)
# Integration tests
class TestMyNewBotIntegration:
"""Integration tests for MyNewBot."""
def test_end_to_end_processing(self):
"""Test complete workflow."""
bot = MyNewBot()
result = bot.process("test data")
assert "status" in result
assert "data" in result
# My New Bot
## Purpose
Brief description of what this bot does.
## Features
- Feature 1
- Feature 2
- Feature 3
## Configuration
...
## Usage
...
## Status
⚠️ In Development / ✅ Production Ready
# Install quality tools
pip install black pylint mypy pytest pytest-cov
# Format code
black bots/my-new-bot/
# Lint code
pylint bots/my-new-bot/
# Type check
mypy bots/my-new-bot/
# Run tests with coverage
pytest bots/my-new-bot/tests/ --cov --cov-report=html
# Run all tests
pytest bots/ -v
# Run specific bot tests
pytest bots/my-new-bot/tests/ -v
# Run with coverage
pytest bots/my-new-bot/tests/ --cov=bots.my_new_bot --cov-report=html
# Run specific test
pytest bots/my-new-bot/tests/test_bot.py::TestMyNewBot::test_process_valid_input -v
bots/README.md to include your botbots/AGENT_INFRASTRUCTURE.md with capacity info# .github/workflows/my-new-bot.yml
name: My New Bot
on:
schedule:
- cron: '0 2 * * *' # Daily at 2 AM UTC
workflow_dispatch:
jobs:
run-bot:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install -r bots/my-new-bot/requirements.txt
- name: Run bot
env:
AZURE_COGNITIVE_KEY: $
run: |
python bots/my-new-bot/bot.py --config bots/my-new-bot/config.yml
git checkout -b feature/my-new-botblack, pylint, mypy, pytestLast Updated: December 2024