The application is structured as a single Python script with clear functional separation:
send_whatsapp_upload_and_broadcast.py
├── Imports and Configuration
├── Logging Configuration
├── Environment Management
├── Utility Functions
├── WhatsApp Cloud API Functions
├── Command Line Argument Parsing
└── Main Application Logic
Purpose: Provides comprehensive logging with multiple output options
Features:
- Multiple log levels (DEBUG, INFO, WARNING, ERROR)
- Console and file output support
- Timestamp formatting
- Sensitive data masking
Configuration:
logger = setup_logging(log_level="INFO", log_file="./logs/app.log")Functions:
load_env_file(path): Loads .env files with error handlingapply_env(vals): Safely applies environment variables
Security Features:
- Masks sensitive tokens in logs
- Validates file permissions
- Error handling for missing files
Functions:
sanitize_phone(raw): Cleans phone number formatvalidate_phone_number(phone): Validates number requirementsread_numbers_from_csv(path): Processes CSV files with validation
Validation Rules:
- Minimum 8 digits for international numbers
- Automatic sanitization (removes non-digits)
- Detailed logging of invalid entries
Core Functions:
upload_media(): Handles file upload to WhatsApp serverssend_template(): Sends approved message templatessend_document_by_id(): Sends document messagespost_json_messages(): Low-level API communication
Error Handling:
- Network timeout management
- API response validation
- Detailed error logging
- Automatic retry logic (future enhancement)
Function: validate_configuration(config)
Validates:
- Required fields presence
- File existence and permissions
- Numeric value ranges
- Template format compliance
- Path accessibility
-
Initialization
- Setup logging system
- Load environment configuration
- Apply CLI overrides
- Validate complete configuration
-
Preparation Phase
- Read and validate phone numbers from CSV
- Check file permissions and sizes
- Parse template configuration
-
Media Upload Phase
- Upload PDF to WhatsApp Cloud API
- Receive and validate media ID
- Handle upload errors gracefully
-
Broadcasting Phase
- Iterate through recipient list
- Send template message (if configured)
- Send document message
- Apply rate limiting
- Track success/failure statistics
-
Completion
- Generate final statistics
- Log operation summary
- Exit with appropriate status code
The application uses a three-tier configuration system:
- Environment Variables (lowest priority)
.envFile (medium priority)- Command Line Arguments (highest priority)
- Caught early in configuration validation
- Clear error messages with resolution guidance
- Prevents API calls with invalid configuration
- Timeout handling for API requests
- Detailed logging of request/response data
- Graceful degradation for individual failures
- Permission checking before operations
- Clear error messages for missing files
- Path validation and normalization
- Access tokens masked in logs (
token[:10]...) - Phone numbers partially masked in logs
- No sensitive data in debug output
- Validates file permissions before reading
- Creates directories with appropriate permissions
- Temporary file cleanup (if implemented)
- Validates API responses before processing
- Timeout protection against hanging requests
- Rate limiting to respect API constraints
- Environment variable loading details
- Phone number processing steps
- API request/response headers and payloads
- File system operations
- Rate limiting delays
- Operation phases and progress
- Configuration summary (sensitive data masked)
- Success/failure for each recipient
- Final statistics and timing
- Invalid phone numbers (with reasons)
- Non-critical configuration issues
- Recovery from minor errors
- Performance warnings
- Configuration validation failures
- API communication errors
- File system errors
- Fatal errors preventing operation
- Streams large files instead of loading entirely
- Processes phone numbers incrementally
- Limited log buffer sizes
- Reuses HTTP connections where possible
- Implements appropriate timeouts
- Rate limiting prevents API abuse
- Validates paths before operations
- Uses appropriate file encodings
- Handles large CSV files efficiently
The code is designed for easy extension:
- Add new functions following
send_document_by_idpattern - Extend payload generation
- Update configuration validation
- Extend MIME type detection
- Add format-specific validation
- Update upload logic if needed
- Implement exponential backoff
- Add retry logic with delays
- Respect API quota limits
- Add performance timing
- Implement success rate tracking
- Export metrics in standard formats
- Configuration validation functions
- Phone number processing
- Environment loading
- Utility functions
- API communication with test credentials
- File processing with sample data
- End-to-end workflow validation
- Use
--dry-runfor safe testing - Test with single recipient first
- Validate with DEBUG logging enabled
- All functions have comprehensive docstrings
- Type hints for parameters and return values
- Inline comments for complex logic
- Usage examples in docstrings
- Specific and actionable error descriptions
- Include relevant context (file paths, values)
- Suggest resolution steps where possible
- Log at appropriate levels
- Clear functional separation
- Logical grouping of related functions
- Consistent naming conventions
- Minimal code duplication
Last Updated: 2025-10-20
Version: 2.0.0