Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Claude Code Telegram Bot Configuration

# === AUTHENTICATION SETUP ===
# Choose one of these Claude authentication methods:
#
# Option 1 (Recommended): Use existing Claude CLI authentication
# 1. Install Claude CLI: https://claude.ai/code
# 2. Login: claude auth login
# 3. Set USE_SDK=true (leave ANTHROPIC_API_KEY empty)
#
# Option 2: Direct API key
# 1. Get API key from: https://console.anthropic.com/
# 2. Set USE_SDK=true and ANTHROPIC_API_KEY=your-key
#
# Option 3: CLI subprocess mode (legacy)
# 1. Install and authenticate Claude CLI
# 2. Set USE_SDK=false

# === REQUIRED SETTINGS ===
# Telegram Bot Token from @BotFather
TELEGRAM_BOT_TOKEN=your_bot_token_here
Expand All @@ -23,6 +39,17 @@ ENABLE_TOKEN_AUTH=false
AUTH_TOKEN_SECRET=

# === CLAUDE SETTINGS ===
# Integration method: Use Python SDK (true) or CLI subprocess (false)
USE_SDK=true

# Anthropic API key for SDK integration (optional if using CLI authentication)
# Get your API key from: https://console.anthropic.com/
ANTHROPIC_API_KEY=

# Path to Claude CLI executable (optional - will auto-detect if not specified)
# Example: /usr/local/bin/claude or ~/.nvm/versions/node/v20.19.2/bin/claude
CLAUDE_CLI_PATH=

# Maximum conversation turns before requiring new session
CLAUDE_MAX_TURNS=10

Expand All @@ -32,6 +59,9 @@ CLAUDE_TIMEOUT_SECONDS=300
# Maximum cost per user in USD
CLAUDE_MAX_COST_PER_USER=10.0

# Allowed Claude tools (comma-separated list)
CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch

# === RATE LIMITING ===
# Number of requests allowed per window
RATE_LIMIT_REQUESTS=10
Expand Down
214 changes: 214 additions & 0 deletions FEATURE_IMPLEMENTATION_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
# Advanced Features Implementation Summary

## Overview
This document summarizes the implementation of advanced features for the Claude Code Telegram Bot as defined in TODO-7.

## Implemented Features

### 1. Enhanced File Upload Handling (`src/bot/features/file_handler.py`)
- **Multi-file Support**: Handles various file types (code, text, archives)
- **Archive Extraction**: Safely extracts and analyzes zip/tar files with security checks
- **Code Analysis**: Comprehensive codebase analysis with language detection, framework identification, and project structure visualization
- **Security**: File size limits, zip bomb prevention, path traversal protection

**Key Classes:**
- `FileHandler`: Main handler for file operations
- `ProcessedFile`: Result dataclass for processed files
- `CodebaseAnalysis`: Comprehensive analysis results

### 2. Git Integration (`src/bot/features/git_integration.py`)
- **Safe Git Operations**: Only allows read-only git commands (status, log, diff, etc.)
- **Repository Status**: Shows branch, changes, ahead/behind tracking
- **Diff Viewing**: Formatted diff output with emoji indicators
- **Commit History**: File-specific commit history with metadata
- **Security**: Command validation, path restrictions

**Key Classes:**
- `GitIntegration`: Main git operations handler
- `GitStatus`: Repository status information
- `CommitInfo`: Individual commit details

### 3. Quick Actions System (`src/bot/features/quick_actions.py`)
- **Predefined Actions**: Test, install, format, lint, security, optimize, document, refactor
- **Context-Aware**: Actions filtered based on project context (package files, test frameworks, etc.)
- **Extensible**: Easy to add new actions
- **Integration**: Executes actions through Claude Code

**Key Classes:**
- `QuickActionManager`: Manages and executes quick actions
- `QuickAction`: Individual action definition

### 4. Session Export (`src/bot/features/session_export.py`)
- **Multiple Formats**: Markdown, JSON, HTML export options
- **Rich Formatting**: Styled HTML output with syntax highlighting
- **Session Metadata**: Includes timestamps, costs, session info
- **File Generation**: Creates downloadable files through Telegram

**Key Classes:**
- `SessionExporter`: Handles session export in various formats
- `ExportedSession`: Export result with metadata
- `ExportFormat`: Supported export format enumeration

### 5. Image/Screenshot Support (`src/bot/features/image_handler.py`)
- **Image Processing**: Handles common image formats (PNG, JPG, GIF, etc.)
- **Type Detection**: Identifies screenshots, diagrams, UI mockups
- **Context-Aware Prompts**: Generates appropriate analysis prompts based on image type
- **Future-Ready**: Base64 encoding for future Claude vision API support

**Key Classes:**
- `ImageHandler`: Main image processing handler
- `ProcessedImage`: Processed image result with prompt and metadata

### 6. Conversation Enhancements (`src/bot/features/conversation_mode.py`)
- **Follow-up Suggestions**: Context-aware suggestions based on tools used and content
- **Context Preservation**: Maintains conversation state across messages
- **Smart Triggers**: Shows suggestions only when relevant
- **Interactive Keyboards**: Easy-to-use suggestion buttons

**Key Classes:**
- `ConversationEnhancer`: Manages conversation flow and suggestions
- `ConversationContext`: Maintains conversation state

### 7. Feature Registry (`src/bot/features/registry.py`)
- **Centralized Management**: Single point for all feature initialization
- **Configuration-Driven**: Features enabled/disabled based on settings
- **Graceful Degradation**: Handles missing dependencies gracefully
- **Lifecycle Management**: Proper startup and shutdown handling

## Integration Points

### Bot Core Integration (`src/bot/core.py`)
- Feature registry initialization during bot startup
- Feature registry added to dependency injection
- New commands registered: `/actions`, `/git`
- Graceful shutdown with feature cleanup

### Command Handlers (`src/bot/handlers/command.py`)
- **New Commands**:
- `/actions`: Shows context-aware quick actions
- `/git`: Git repository information and operations
- Enhanced `/export`: Session export with format selection
- **Updated Help**: Comprehensive help text with new features

### Callback Handlers (`src/bot/handlers/callback.py`)
- **New Callback Routes**:
- `quick:*`: Quick action execution
- `git:*`: Git operations (status, diff, log)
- `export:*`: Session export format selection
- `followup:*`: Follow-up suggestion handling
- **Enhanced Error Handling**: Better user feedback for feature errors

### Message Handlers (`src/bot/handlers/message.py`)
- **Enhanced File Processing**: Uses new FileHandler for improved file analysis
- **Image Support**: Processes images with new ImageHandler
- **Conversation Flow**: Adds follow-up suggestions after Claude responses
- **Fallback Support**: Graceful degradation when features unavailable

## Configuration

### Feature Flags
All features respect existing configuration flags:
- `enable_file_uploads`: Controls enhanced file handling
- `enable_git_integration`: Controls git operations
- `enable_quick_actions`: Controls quick action system

### Always-Enabled Features
- Session export (uses existing storage)
- Image handling (basic support)
- Conversation enhancements (improves UX)

## Security Considerations

### File Handling Security
- Archive bomb prevention (100MB limit)
- Path traversal protection
- File type validation
- Temporary file cleanup

### Git Security
- Read-only operations only
- Command validation whitelist
- Path restriction to approved directory
- No write operations (commit, push, etc.)

### Input Validation
- All user inputs validated
- Callback data validation
- File size and type restrictions
- Error message sanitization

## Testing Status

### Syntax Validation
- βœ… All feature files pass Python syntax validation
- βœ… Import validation successful
- βœ… Code formatting with Black/isort

### Integration Testing
- βœ… Features integrate with existing bot core
- βœ… Dependency injection working
- βœ… Graceful degradation tested

### Coverage
- New features included in coverage reports
- Existing functionality remains intact
- No breaking changes to current API

## Usage Examples

### Quick Actions
```
/actions
# Shows context-aware actions based on current directory
# Actions like "Run Tests" only appear if test framework detected
```

### Git Integration
```
/git
# Shows repository status, recent commits, changes
# Buttons for diff view, commit log, etc.
```

### Session Export
```
/export
# Shows format selection (Markdown, HTML, JSON)
# Generates downloadable file with conversation history
```

### Enhanced File Upload
- Upload zip files β†’ automatic extraction and analysis
- Upload code files β†’ enhanced analysis with language detection
- Upload images β†’ context-aware analysis prompts

### Conversation Flow
- After Claude responses β†’ smart follow-up suggestions
- Context-aware suggestions based on tools used
- One-click action execution

## Future Enhancements

### Planned Improvements
1. **Image Vision API**: Full image analysis when Claude gains vision capabilities
2. **Custom Actions**: User-defined quick actions
3. **Session Templates**: Reusable session configurations
4. **Advanced Git**: Selective file operations, branch management
5. **Plugin System**: Third-party feature extensions

### Architecture Ready For
- Additional export formats (PDF, Word)
- More git operations (when security permits)
- Advanced file processing (compilation, analysis)
- Multi-language code execution
- Integration with external tools

## Conclusion

The advanced features implementation successfully extends the Claude Code Telegram Bot with:
- **Enhanced User Experience**: Better file handling, quick actions, conversation flow
- **Developer Productivity**: Git integration, code analysis, session export
- **Robust Architecture**: Modular design, graceful degradation, security-first
- **Future-Proof Design**: Extensible, configurable, maintainable

All features are production-ready and integrate seamlessly with the existing codebase while maintaining backward compatibility and security standards.
51 changes: 45 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,30 @@ The following features are partially implemented or planned:
3. Save your bot token (it looks like `1234567890:ABC...`)
4. Note your bot username (e.g., `my_claude_bot`)

### 2. Install the Bot
### 2. Set Up Claude Authentication

Choose one of these authentication methods:

**Option 1: Use existing Claude CLI login (Recommended)**
```bash
# Install Claude CLI
# Follow instructions at https://claude.ai/code

# Authenticate with Claude
claude

# follow the prompts to authenticate

# The bot will automatically use your CLI credentials
```

**Option 2: Use API key directly**
```bash
# Get your API key from https://console.anthropic.com/
# You'll add this to your .env file in the next step
```

### 3. Install the Bot

```bash
# Clone the repository
Expand All @@ -121,7 +144,7 @@ curl -sSL https://install.python-poetry.org | python3 -
make dev
```

### 3. Configure Environment
### 4. Configure Environment

```bash
# Copy the example configuration
Expand All @@ -139,7 +162,7 @@ APPROVED_DIRECTORY=/Users/yourname/projects
ALLOWED_USERS=123456789 # Your Telegram user ID
```

### 4. Run the Bot
### 5. Run the Bot

```bash
# Start in debug mode
Expand All @@ -151,6 +174,8 @@ make run

πŸŽ‰ **That's it!** Message your bot on Telegram to get started.

> πŸ“‹ **Detailed Setup Guide**: For comprehensive setup instructions including authentication options and troubleshooting, see [docs/setup.md](docs/setup.md)

## πŸ“± Usage

### Basic Commands
Expand Down Expand Up @@ -250,6 +275,8 @@ ALLOWED_USERS=123456789,987654321 # Your Telegram user ID(s)

```bash
# Claude Settings
USE_SDK=true # Use Python SDK (default) or CLI subprocess
ANTHROPIC_API_KEY=sk-ant-api03-... # Optional: API key for SDK (if not using CLI auth)
CLAUDE_MAX_COST_PER_USER=10.0 # Max cost per user in USD
CLAUDE_TIMEOUT_SECONDS=300 # Timeout for operations
CLAUDE_ALLOWED_TOOLS="Read,Write,Edit,Bash,Glob,Grep,LS,Task,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch"
Expand Down Expand Up @@ -294,10 +321,22 @@ To get your Telegram user ID for the `ALLOWED_USERS` setting:
- βœ… Check that paths don't contain special characters

**Claude integration not working:**
- βœ… Verify Claude Code CLI is installed: `claude --version`
- βœ… Check if you're authenticated: `claude auth status`
- βœ… Ensure you have API credits available

*If using SDK mode (USE_SDK=true, which is default):*
- βœ… Check CLI authentication: `claude auth status`
- βœ… If no CLI auth, verify `ANTHROPIC_API_KEY` is set in .env
- βœ… Ensure API key has sufficient credits
- βœ… Check logs for "SDK initialization" messages

*If using CLI mode (USE_SDK=false):*
- βœ… Verify Claude CLI is installed: `claude --version`
- βœ… Check CLI authentication: `claude auth status`
- βœ… Ensure CLI has sufficient credits

*General troubleshooting:*
- βœ… Verify `CLAUDE_ALLOWED_TOOLS` includes necessary tools
- βœ… Check `CLAUDE_TIMEOUT_SECONDS` isn't too low
- βœ… Monitor usage with `/status` command

**High usage costs:**
- βœ… Adjust `CLAUDE_MAX_COST_PER_USER` to set spending limits
Expand Down
Loading