Skip to content

murat-karasah/SmartChatBot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SmartChatBot - AI-Powered Business Chatbot Backend

.NET 8 PostgreSQL OpenAI DeepSeek Docker Tests License

A production-ready backend system that enables businesses to deploy AI-powered chatbots on WhatsApp and Telegram. Businesses upload their product/service knowledge base, and the AI automatically responds to customer inquiries with accurate, context-aware answers.


Features

  • Multi-Channel Support - Telegram Bot API & WhatsApp Business Cloud API
  • Multi-Provider AI - OpenAI GPT-4o-mini or DeepSeek Chat (switchable via config)
  • Knowledge Base (RAG-lite) - Upload business data, AI uses it to answer questions
  • Conversation Memory - Maintains chat history for contextual follow-ups
  • Multi-Tenant - Support multiple businesses with isolated data and API keys
  • Admin API - Full CRUD for businesses and knowledge base items
  • Bulk Import - Import knowledge base items in bulk via JSON
  • Demo Seed Data - One-click Pizza Palace demo for quick testing
  • API Key Authentication - Secure per-business API key system
  • Rate Limiting - 30 requests/minute per API key (Fixed Window)
  • Structured Logging - Serilog with console + rolling file sinks
  • Docker Ready - Single docker-compose up to run everything
  • Health Check - Built-in health endpoint for monitoring
  • Swagger UI - Interactive API documentation with XML comments
  • Unit Tests - 24 tests covering services, AI, and webhook parsing

Architecture

                    +------------------+
                    |   Telegram Bot   |
                    +--------+---------+
                             |
+------------------+         v          +------------------+
| WhatsApp Business|----> Webhook  <----| Direct API Chat  |
+------------------+    Controller      +------------------+
                             |
                    +--------v---------+
                    |  Business Logic   |
                    |  - Auth (API Key) |
                    |  - Rate Limiting  |
                    |  - Conversation   |
                    |  - Knowledge Base |
                    +--------+---------+
                             |
                    +--------v---------+
                    |   OpenAI GPT     |
                    |  (with context)  |
                    +------------------+
                             |
                    +--------v---------+
                    |   PostgreSQL DB   |
                    +------------------+

Quick Start

Prerequisites

  • Docker & Docker Compose
  • OpenAI API key

1. Clone & Configure

git clone https://github.com/murat-karasah/SmartChatBot.git
cd SmartChatBot
cp .env.example .env
# Edit .env and add your OpenAI API key

2. Run

docker-compose up -d

The API will be available at http://localhost:8080

3. Seed Demo Data

curl -X POST http://localhost:8080/api/admin/seed-demo

This creates a "Pizza Palace" demo business with 12 knowledge base items and returns an API key.

4. Start Chatting

curl -X POST http://localhost:8080/api/chat \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY_FROM_SEED" \
  -d '{"message": "What pizzas do you have?", "userId": "test-user-1"}'

API Documentation

Swagger UI is available at http://localhost:8080/swagger

Admin Endpoints

Method Endpoint Description
POST /api/admin/business Create a new business
GET /api/admin/businesses List all businesses
GET /api/admin/business/{id} Get business details
POST /api/admin/business/{id}/knowledge Add knowledge item
POST /api/admin/business/{id}/knowledge/bulk Bulk import knowledge
PUT /api/admin/knowledge/{itemId} Update knowledge item
DELETE /api/admin/knowledge/{itemId} Delete knowledge item
POST /api/admin/business/{id}/telegram/setup Configure Telegram bot
POST /api/admin/business/{id}/whatsapp/setup Configure WhatsApp
POST /api/admin/seed-demo Load demo data

Chat Endpoints

Method Endpoint Description
POST /api/chat Send a message (requires X-API-Key, rate limited)
GET /api/chat/history?userId={id} Get conversation history

Webhook Endpoints

Method Endpoint Description
POST /api/webhook/telegram/{apiKey} Telegram webhook receiver
GET /api/webhook/whatsapp/{apiKey} WhatsApp verification
POST /api/webhook/whatsapp/{apiKey} WhatsApp webhook receiver

Other

Method Endpoint Description
GET /health Health check

Environment Variables

Variable Description Default
POSTGRES_DB Database name smartchatbot
POSTGRES_USER Database user postgres
POSTGRES_PASSWORD Database password -
AI_PROVIDER AI provider: openai or deepseek openai
OPENAI_API_KEY OpenAI API key -
OPENAI_MODEL OpenAI model gpt-4o-mini
DEEPSEEK_API_KEY DeepSeek API key -
DEEPSEEK_MODEL DeepSeek model deepseek-chat

Switching AI Provider

By default, the system uses OpenAI. To switch to DeepSeek (cheaper alternative):

Option 1: Via .env file

AI_PROVIDER=deepseek
DEEPSEEK_API_KEY=sk-your-deepseek-key

Option 2: Via appsettings.json

{
  "AI": {
    "Provider": "deepseek"
  }
}

Both providers use the same OpenAI-compatible chat completions API, so switching is seamless with no code changes.


Telegram Bot Setup

  1. Create a bot via @BotFather on Telegram
  2. Copy the bot token
  3. Call the setup endpoint:
curl -X POST http://localhost:8080/api/admin/business/{id}/telegram/setup \
  -H "Content-Type: application/json" \
  -d '{"botToken": "YOUR_BOT_TOKEN", "baseUrl": "https://your-domain.com"}'

WhatsApp Setup

  1. Create a Meta Business account and WhatsApp Business API app
  2. Get your Phone Number ID, Access Token, and set a Verify Token
  3. Call the setup endpoint:
curl -X POST http://localhost:8080/api/admin/business/{id}/whatsapp/setup \
  -H "Content-Type: application/json" \
  -d '{
    "phoneNumberId": "YOUR_PHONE_ID",
    "accessToken": "YOUR_ACCESS_TOKEN",
    "verifyToken": "YOUR_VERIFY_TOKEN",
    "baseUrl": "https://your-domain.com"
  }'
  1. In Meta Developer Portal, set webhook URL to: https://your-domain.com/api/webhook/whatsapp/{apiKey}

Running Tests

dotnet test

24 unit tests covering:

  • AIServiceTests - OpenAI API integration, prompt building with knowledge context, error handling
  • KnowledgeBaseServiceTests - CRUD operations, keyword search relevance ordering
  • ConversationServiceTests - Conversation creation, message ordering, channel separation
  • WebhookParsingTests - Telegram and WhatsApp payload parsing, webhook verification

Tech Stack

  • Runtime: .NET 8 (ASP.NET Core Web API)
  • Database: PostgreSQL 16 with Entity Framework Core
  • AI: OpenAI GPT-4o-mini / DeepSeek Chat (configurable)
  • Messaging: Telegram Bot API, WhatsApp Business Cloud API
  • Logging: Serilog (Console + File sinks, structured logging)
  • Rate Limiting: ASP.NET Core Fixed Window Rate Limiter
  • Containerization: Docker & Docker Compose
  • Testing: xUnit + Moq
  • Documentation: Swagger / OpenAPI with XML comments

Project Structure

SmartChatBot/
├── src/
│   ├── SmartChatBot.API/
│   │   ├── Controllers/        # API endpoints (Admin, Chat, Webhooks)
│   │   ├── Services/           # Business logic (AI, Knowledge, Conversation, Telegram, WhatsApp)
│   │   ├── Models/             # Entities, DTOs, Webhook models
│   │   ├── Data/               # EF Core DbContext & Migrations
│   │   ├── Middleware/         # API key authentication
│   │   └── Program.cs          # App configuration & pipeline
│   └── SmartChatBot.Tests/     # 24 unit tests
├── docker-compose.yml          # PostgreSQL + API + pgAdmin
├── Dockerfile                  # Multi-stage build
├── .env.example
└── README.md

License

This project is licensed under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors