This guide provides detailed information for developers working on the WhatsApp ChatGPT Bot C# implementation.
- Architecture Overview
- Key Components
- Development Setup
- Project Structure
- Configuration Management
- API Integration
- Testing
- Deployment
- Troubleshooting
The C# implementation follows modern .NET 8 patterns with clean architecture principles:
┌─────────────────────────────────────────────────────────────┐
│ HTTP Layer (ASP.NET Core) │
├─────────────────────────────────────────────────────────────┤
│ Controllers/WebhookController.cs - REST API endpoints │
├─────────────────────────────────────────────────────────────┤
│ Business Logic Layer │
├─────────────────────────────────────────────────────────────┤
│ Bot/ChatBot.cs - Core message processing │
│ Bot/FunctionHandler.cs - OpenAI function calling │
├─────────────────────────────────────────────────────────────┤
│ Service Layer │
├─────────────────────────────────────────────────────────────┤
│ Api/OpenAIClient.cs - OpenAI API integration │
│ Api/WassengerClient.cs - WhatsApp API integration │
│ Services/MemoryStore.cs - Caching and state management │
│ Services/NgrokTunnel.cs - Development tunneling │
├─────────────────────────────────────────────────────────────┤
│ Configuration Layer │
├─────────────────────────────────────────────────────────────┤
│ Config/BotConfig.cs - Centralized configuration │
│ Models/ - Data transfer objects │
└─────────────────────────────────────────────────────────────┘
The main application handles:
- Dependency injection configuration
- Service registration and lifetime management
- Environment-based configuration loading
- Application startup and initialization
- Development vs production mode handling
Key Features:
LoadFromEnvironment()- Loads configuration from environment variablesInitializeBotServicesAsync()- Complete bot initializationSetupWebhookAsync()- Webhook registration with Ngrok support- HTTP client configuration with retry policies
Core bot functionality:
- Message processing and filtering
- Chat assignment and human handoff
- Rate limiting and quota management
- Audio transcription and TTS
- Image analysis
- Conversation memory management
Key Methods:
ProcessMessageAsync()- Main message processing pipelineCanReplyAsync()- Message filtering logicAssignChatToAgentAsync()- Human handoff functionalityGenerateResponseWithFunctionsAsync()- AI response generation with function calling
OpenAI API integration:
- Chat completions with function calling
- Audio transcription (Whisper)
- Text-to-speech generation
- Image analysis (GPT-4V)
- Retry logic and error handling
Key Methods:
CreateChatCompletionAsync()- Chat completion with toolsTranscribeAudioAsync()- Audio to text conversionGenerateSpeechAsync()- Text to speech conversionAnalyzeImageAsync()- Image analysis
WhatsApp API integration:
- Message sending (text, media, location, etc.)
- Device management and status checking
- Contact and chat operations
- Webhook registration
- Labels and metadata management
Key Methods:
SendMessageAsync()- Send WhatsApp messagesLoadDeviceAsync()- Device loading with cachingRegisterWebhookAsync()- Webhook endpoint registrationDownloadMediaAsync()- Media file downloads
Centralized configuration management:
- Environment variable handling
- Default values and validation
- API configuration
- Bot behavior settings
- Feature toggles
In-memory caching and state management:
- Conversation history storage
- Rate limiting counters
- Device and member caching
- Thread-safe operations
-
.NET 8 SDK
# macOS brew install --cask dotnet # Windows # Download from https://dotnet.microsoft.com/download/dotnet/8.0 # Linux (Ubuntu/Debian) sudo apt-get install -y dotnet-sdk-8.0
-
IDE/Editor (optional but recommended)
- Visual Studio 2022 (Windows/Mac)
- Visual Studio Code with C# extension
- JetBrains Rider
-
Development Tools
- Ngrok (for local development)
- Git
- Postman or similar for API testing
-
Clone and setup:
git clone <repository-url> cd whatsapp-chatgpt-bot-csharp ./setup.sh
-
Configure environment:
cp .env.example .env # Edit .env with your API keys -
Test installation:
./test.sh
src/WhatsAppChatBot/
├── Program.cs # Application entry point
├── WhatsAppChatBot.csproj # Project configuration
├── appsettings.json # Application settings
├── appsettings.Development.json
│
├── Api/ # External API clients
│ ├── OpenAIClient.cs # OpenAI integration
│ └── WassengerClient.cs # Wassenger integration
│
├── Bot/ # Core bot logic
│ ├── ChatBot.cs # Main bot implementation
│ └── FunctionHandler.cs # Function calling logic
│
├── Config/ # Configuration management
│ └── BotConfig.cs # Centralized config
│
├── Controllers/ # HTTP controllers
│ └── WebhookController.cs # API endpoints
│
├── Models/ # Data models
│ ├── OpenAIModels.cs # OpenAI API models
│ ├── WassengerModels.cs # Wassenger API models
│ └── WebhookModels.cs # Webhook models
│
└── Services/ # Business services
├── MemoryStore.cs # Caching service
└── NgrokTunnel.cs # Development tunneling
The application uses environment variables for configuration:
# API Configuration
API_KEY=your_wassenger_api_key
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-4o
# Server Configuration
PORT=8080
WEBHOOK_URL=https://yourdomain.com/webhook
PRODUCTION=false
DEV=true
# Development
NGROK_TOKEN=your_ngrok_token
LOG_LEVEL=InformationConfiguration is managed through strongly-typed classes:
// Main configuration class
public class BotConfig
{
public ApiConfig Api { get; set; }
public ServerConfig Server { get; set; }
public FeaturesConfig Features { get; set; }
public LimitsConfig Limits { get; set; }
// ... more configs
}
// API configuration
public class ApiConfig
{
public string ApiKey { get; set; }
public string OpenAiKey { get; set; }
public string OpenAiModel { get; set; }
}Services are registered in Program.cs:
builder.Services.AddSingleton(botConfig);
builder.Services.AddSingleton<IMemoryStore, MemoryStore>();
builder.Services.AddSingleton<IChatBot, ChatBot>();
builder.Services.AddHttpClient<IOpenAIClient, OpenAIClient>();HTTP clients are configured with retry policies:
builder.Services.AddHttpClient<IOpenAIClient, OpenAIClient>()
.AddPolicyHandler(GetRetryPolicy());
private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(
retryCount: 3,
sleepDurationProvider: retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}The OpenAI client supports:
- Chat completions with function calling
- Audio transcription (Whisper)
- Text-to-speech (TTS)
- Image analysis (GPT-4V)
// Example: Chat completion with tools
var response = await _openAiClient.CreateChatCompletionAsync(
messages,
tools: functionTools);The Wassenger client handles:
- Device management
- Message sending
- Webhook registration
- Media downloads
// Example: Send a message
await _wassengerClient.SendMessageAsync(new SendMessageRequest
{
Phone = data.FromNumber,
Message = response,
Device = device.Id
});Run the validation script:
./test.shThis script validates:
- Project structure
- Dependencies
- Compilation
- Configuration
-
API Endpoints:
# Health check curl http://localhost:8080/ # Webhook test curl -X POST http://localhost:8080/webhook \ -H "Content-Type: application/json" \ -d '{"event":"message:in:new","data":{...}}'
-
Message Flow:
- Send a WhatsApp message to your connected number
- Check logs for processing steps
- Verify response is received
To add unit tests:
-
Create test project:
dotnet new xunit -n WhatsAppChatBot.Tests dotnet add reference ../WhatsAppChatBot/WhatsAppChatBot.csproj
-
Add test packages:
dotnet add package Moq dotnet add package Microsoft.AspNetCore.Mvc.Testing
-
Example test structure:
public class ChatBotTests { [Fact] public async Task ProcessMessage_ShouldReply_WhenValidMessage() { // Arrange var mockConfig = new Mock<BotConfig>(); var chatBot = new ChatBot(mockConfig.Object, ...); // Act await chatBot.ProcessMessageAsync(testData, testDevice); // Assert // Verify expected behavior } }
# Run in development mode
cd src/WhatsAppChatBot
dotnet run
# Run with hot reload
dotnet watch run# Build image
docker build -t whatsapp-chatbot .
# Run container
docker run -d \
--name whatsapp-chatbot \
-p 8080:8080 \
-e API_KEY=your_key \
-e OPENAI_API_KEY=your_key \
whatsapp-chatbot# Publish for deployment
dotnet publish -c Release -o ./publish
# Deploy to Azure
az webapp deployment source config-zip \
--resource-group myResourceGroup \
--name myapp \
--src publish.zip-
Publish application:
dotnet publish -c Release
-
Create deployment package
-
Upload to Elastic Beanstalk
- Uses Ngrok for tunneling
- Detailed logging enabled
- Swagger UI available
- Requires WEBHOOK_URL
- Minimal logging
- Health checks enabled
-
Build Errors
# Clear and restore dotnet clean dotnet restore dotnet build -
Missing Dependencies
# Check project file cat WhatsAppChatBot.csproj # Restore specific package dotnet add package PackageName
-
Configuration Issues
# Validate environment cat .env # Check configuration loading # Add logging in BotConfig.LoadFromEnvironment()
-
API Connection Issues
# Test API connectivity curl -H "Authorization: Bearer $OPENAI_API_KEY" \ https://api.openai.com/v1/models curl -H "Authorization: $API_KEY" \ https://api.wassenger.com/v1/devices
-
Enable detailed logging:
export LOG_LEVEL=Debug -
Use Visual Studio debugger:
- Set breakpoints in key methods
- Inspect variable values
- Step through execution
-
Add custom logging:
_logger.LogDebug("Processing message: {MessageId}", data.Id);
-
Memory usage:
// Monitor cache size var cacheSize = _memoryStore.GetAllData().Count; _logger.LogInformation("Cache size: {Size}", cacheSize);
-
Response times:
var stopwatch = Stopwatch.StartNew(); await ProcessMessage(data); _logger.LogInformation("Processing took: {ElapsedMs}ms", stopwatch.ElapsedMilliseconds);
- Use dependency injection for all services
- Implement interfaces for testability
- Follow SOLID principles
- Use async/await for I/O operations
- Use try-catch blocks appropriately
- Log errors with context
- Return meaningful error responses
- Implement circuit breaker pattern for external APIs
- Validate all inputs
- Use environment variables for secrets
- Implement rate limiting
- Secure webhook endpoints
- Cache frequently accessed data
- Use connection pooling for HTTP clients
- Implement proper disposal patterns
- Monitor memory usage