Telegram Bot Platform - Complete Technical Documentation

Telegram Bot Builder Platform - Complete Technical Documentation

Table of Contents

  1. Application Overview
  2. Technology Stack
  3. Database Architecture
  4. System Architecture
  5. Frontend Architecture
  6. Backend Architecture
  7. Security Features
  8. API Documentation
  9. cPanel Deployment Guide
  10. Production Setup
  11. Maintenance & Monitoring

Application Overview

Purpose

A comprehensive web platform for creating and managing Telegram chatbots without coding knowledge. Users can build sophisticated bots through an intuitive interface with visual menu builders, analytics tracking, and subscription management.

Key Features


Technology Stack

Frontend Technologies

Core Framework

UI & Styling

State Management & Data Fetching

Routing & Navigation

Additional Frontend Libraries

Backend Technologies

Core Runtime & Framework

Database & ORM

Authentication & Security

File Handling & Utilities

External Integrations

Development Tools


Database Architecture

Core Tables

Users Management

-- users: Core user accounts
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  username VARCHAR(50) UNIQUE NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL,
  password TEXT NOT NULL,
  first_name VARCHAR(100),
  last_name VARCHAR(100),
  created_at TIMESTAMP DEFAULT NOW()
);

-- admin_users: Administrative accounts
CREATE TABLE admin_users (
  id SERIAL PRIMARY KEY,
  username VARCHAR(50) UNIQUE NOT NULL,
  password TEXT NOT NULL,
  role VARCHAR(20) DEFAULT 'admin',
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT NOW(),
  last_login TIMESTAMP
);

Bot Management

-- bots: Telegram bot configurations
CREATE TABLE bots (
  id SERIAL PRIMARY KEY,
  user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
  name VARCHAR(100) NOT NULL,
  username VARCHAR(100) UNIQUE NOT NULL,
  token TEXT NOT NULL,
  description TEXT,
  is_active BOOLEAN DEFAULT true,
  profile_picture TEXT,
  menu_structure JSONB DEFAULT '{}',
  settings JSONB DEFAULT '{}',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- bot_analytics: Usage statistics
CREATE TABLE bot_analytics (
  id SERIAL PRIMARY KEY,
  bot_id INTEGER REFERENCES bots(id) ON DELETE CASCADE,
  date TIMESTAMP DEFAULT NOW(),
  active_users INTEGER DEFAULT 0,
  messages_received INTEGER DEFAULT 0,
  messages_sent INTEGER DEFAULT 0
);

-- bot_interactions: Conversation logs
CREATE TABLE bot_interactions (
  id SERIAL PRIMARY KEY,
  bot_id INTEGER REFERENCES bots(id) ON DELETE CASCADE,
  telegram_user_id VARCHAR(50) NOT NULL,
  message_text TEXT,
  response TEXT,
  timestamp TIMESTAMP DEFAULT NOW()
);

Subscription System

-- subscription_plans: Available plans
CREATE TABLE subscription_plans (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  description TEXT,
  price INTEGER NOT NULL, -- in paise (INR)
  duration VARCHAR(20) NOT NULL, -- monthly, yearly, lifetime
  features JSONB DEFAULT '[]',
  max_bots INTEGER DEFAULT 1,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT NOW()
);

-- user_subscriptions: User plan assignments
CREATE TABLE user_subscriptions (
  id SERIAL PRIMARY KEY,
  user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
  plan_id INTEGER REFERENCES subscription_plans(id),
  status VARCHAR(20) DEFAULT 'active', -- active, cancelled, expired
  start_date TIMESTAMP DEFAULT NOW(),
  end_date TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW()
);

-- payments: Transaction records
CREATE TABLE payments (
  id SERIAL PRIMARY KEY,
  user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
  subscription_id INTEGER REFERENCES user_subscriptions(id),
  amount INTEGER NOT NULL, -- in paise
  currency VARCHAR(3) DEFAULT 'INR',
  payment_method VARCHAR(50),
  transaction_id VARCHAR(255),
  status VARCHAR(20) DEFAULT 'pending',
  gateway_response JSONB,
  created_at TIMESTAMP DEFAULT NOW()
);

Platform Management

-- announcements: Platform announcements
CREATE TABLE announcements (
  id SERIAL PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  content TEXT NOT NULL,
  type VARCHAR(50) DEFAULT 'info', -- info, warning, success, error
  is_active BOOLEAN DEFAULT true,
  created_by INTEGER REFERENCES admin_users(id),
  created_at TIMESTAMP DEFAULT NOW(),
  expires_at TIMESTAMP
);

-- activity_logs: Admin activity tracking
CREATE TABLE activity_logs (
  id SERIAL PRIMARY KEY,
  admin_id INTEGER REFERENCES admin_users(id),
  user_id INTEGER REFERENCES users(id),
  action VARCHAR(100) NOT NULL,
  details TEXT,
  ip_address INET,
  created_at TIMESTAMP DEFAULT NOW()
);

-- platform_settings: Dynamic configuration
CREATE TABLE platform_settings (
  id SERIAL PRIMARY KEY,
  key VARCHAR(100) UNIQUE NOT NULL,
  value TEXT,
  description TEXT,
  category VARCHAR(50) DEFAULT 'general',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW(),
  updated_by INTEGER REFERENCES admin_users(id)
);

Database Relationships


System Architecture

Monorepo Structure

├── client/               # Frontend React application
│   ├── src/
│   │   ├── components/   # Reusable UI components
│   │   ├── pages/        # Route components
│   │   ├── hooks/        # Custom React hooks
│   │   ├── lib/          # Utility functions
│   │   └── main.tsx      # Application entry point
│   └── index.html        # HTML template
├── server/               # Backend Express application
│   ├── services/         # Business logic services
│   ├── db.ts            # Database connection
│   ├── index.ts         # Server entry point
│   ├── routes.ts        # API route definitions
│   └── storage.ts       # Data access layer
├── shared/               # Shared code between frontend/backend
│   └── schema.ts        # Database schema and types
└── uploads/             # File upload storage

Request Flow

  1. Client Request → React Router (Wouter)
  2. API Call → TanStack Query → apiRequest utility
  3. Server Processing → Express routes → Authentication middleware
  4. Data Layer → Storage service → Drizzle ORM → PostgreSQL
  5. Response → JSON API → React components → UI update

Authentication Flow

  1. Login Request → Credentials validation → bcrypt comparison
  2. Session Creation → Express session → PostgreSQL session store
  3. Protected Routes → Middleware checks → Session validation
  4. Admin Access → Separate admin authentication → Role-based permissions

Frontend Architecture

Component Structure

components/
├── ui/                   # shadcn/ui base components
│   ├── button.tsx
│   ├── card.tsx
│   ├── dialog.tsx
│   └── ...
├── admin-navigation.tsx  # Admin panel navigation
├── bot-card.tsx         # Bot display component
├── menu-builder.tsx     # Visual bot menu editor
└── navigation.tsx       # Main app navigation

State Management Strategy

Routing Strategy

// Main application routes
<Route path="/" component={Dashboard} />
<Route path="/bots" component={BotsPage} />
<Route path="/bot-builder/:id?" component={BotBuilder} />
<Route path="/analytics" component={AnalyticsPage} />

// Admin routes (secured)
<Route path="/167admin/login" component={AdminLogin} />
<AdminProtectedRoute path="/167admin/dashboard" component={AdminDashboard} />
<AdminProtectedRoute path="/167admin/users" component={AdminUsers} />

Build Configuration


Backend Architecture

Express Server Structure

// Middleware stack
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session(sessionConfig));
app.use('/uploads', express.static('uploads'));

// Authentication middleware
const requireAuth = (req, res, next) => {
  if (!req.session.userId) {
    return res.status(401).json({ message: "Authentication required" });
  }
  next();
};

const requireAdminAuth = (req, res, next) => {
  if (!req.session.adminId) {
    return res.status(401).json({ message: "Admin authentication required" });
  }
  next();
};

API Route Organization

/api/
├── auth/              # User authentication
│   ├── POST /login
│   ├── POST /register
│   ├── POST /logout
│   └── GET /me
├── bots/              # Bot management
│   ├── GET /
│   ├── POST /
│   ├── PUT /:id
│   └── DELETE /:id
├── admin/             # Admin panel APIs
│   ├── POST /login
│   ├── GET /users
│   ├── GET /dashboard/stats
│   └── POST /upload-file
└── webhook/:token     # Telegram webhook endpoint

File Upload System

// Multer configuration
const storage = multer.diskStorage({
  destination: './uploads',
  filename: (req, file, cb) => {
    const uniqueName = `${nanoid()}_${Date.now()}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

const upload = multer({ 
  storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
  fileFilter: (req, file, cb) => cb(null, true) // Allow all files
});

Database Connection

// Drizzle ORM configuration
import { drizzle } from 'drizzle-orm/neon-http';
import { neon } from '@neondatabase/serverless';

const client = neon(process.env.DATABASE_URL!);
export const db = drizzle(client);

Security Features

Authentication Security

Data Security

Access Control


API Documentation

Authentication Endpoints

POST /api/auth/register

{
  "username": "string",
  "email": "string", 
  "password": "string",
  "firstName": "string",
  "lastName": "string"
}

POST /api/auth/login

{
  "username": "string",
  "password": "string"
}

Bot Management Endpoints

GET /api/bots

Returns array of user’s bots

POST /api/bots

{
  "name": "string",
  "username": "string",
  "token": "string",
  "description": "string"
}

PUT /api/bots/:id

{
  "menuStructure": "object",
  "settings": "object",
  "isActive": "boolean"
}

Admin Endpoints

POST /api/admin/upload-file

Content-Type: multipart/form-data Field: file

Response:

{
  "success": true,
  "filename": "string",
  "originalName": "string",
  "size": "number",
  "url": "string"
}

GET /api/admin/dashboard/stats

{
  "totalUsers": "number",
  "totalBots": "number",
  "totalPayments": "number",
  "totalRevenue": "number",
  "activeSubscriptions": "number"
}

cPanel Deployment Guide

Prerequisites

Step 1: Build Application

# Install dependencies
npm install

# Build for production
npm run build

# This creates:
# - dist/public/ (frontend static files)
# - dist/index.js (backend server bundle)

Step 2: Database Setup

Create PostgreSQL Database

  1. cPanel → PostgreSQL Databases

  2. Create Database: yourdomain_botbuilder

  3. Create User: botbuilder_user with strong password

  4. Assign User: Grant all privileges to database

  5. Note Connection String:

    postgresql://botbuilder_user:password@localhost:5432/yourdomain_botbuilder

Initialize Database Schema

-- Execute all table creation scripts from shared/schema.ts
-- Or use migration tool:
npm run db:push

Create Default Admin User

INSERT INTO admin_users (username, password, role) 
VALUES ('admin', '$2b$10$hashed_password_here', 'super_admin');

Step 3: File Upload Structure

# In cPanel File Manager, create:
public_html/
├── dist/
   ├── public/          # Frontend assets
   └── index.js         # Backend server
├── uploads/             # File upload directory (755 permissions)
├── package.json
├── .env
└── .htaccess

Step 4: Environment Configuration

Create .env file:

NODE_ENV=production
DATABASE_URL=postgresql://botbuilder_user:password@localhost:5432/yourdomain_botbuilder
SESSION_SECRET=your_super_secure_random_string_here_min_32_chars
PORT=3000
REPLIT_DOMAINS=yourdomain.com

Create .htaccess:

RewriteEngine On

# Prevent access to sensitive files
<FilesMatch "\.(env|json)$">
    Order deny,allow
    Deny from all
</FilesMatch>

# Handle API and file upload routes
RewriteCond %{REQUEST_URI} ^/(api|uploads)/
RewriteRule ^(.*)$ http://localhost:3000/$1 [P,L]

# Handle frontend routing (SPA)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(api|uploads)/
RewriteRule ^(.*)$ dist/public/index.html [L]

# Serve static assets directly
RewriteCond %{REQUEST_URI} ^/assets/
RewriteRule ^assets/(.*)$ dist/public/assets/$1 [L]

# Security headers
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

Step 5: Node.js Application Setup

Method 1: cPanel Node.js Selector

  1. Access: cPanel → Node.js Selector

  2. Create Application:

  3. Install Dependencies:

    cd /public_html
    npm install --only=production

Method 2: Manual Setup (SSH Required)

# Navigate to public_html
cd /public_html

# Install Node.js dependencies
npm install --only=production

# Start application (use process manager)
npm start

Step 6: Process Management

# Install PM2 globally
npm install -g pm2

# Start application
pm2 start dist/index.js --name "bot-builder" --env production

# Auto-start on server reboot
pm2 startup
pm2 save

# Monitor application
pm2 monit

Option 2: Forever

npm install -g forever
forever start dist/index.js

Option 3: Cron Job Keepalive

# Add to cPanel Cron Jobs (every 5 minutes)
*/5 * * * * cd /public_html && /usr/local/bin/node dist/index.js > /dev/null 2>&1 || /usr/local/bin/node dist/index.js &

Step 7: SSL and Security

Enable SSL Certificate

  1. cPanel → SSL/TLS
  2. Let’s Encrypt: Free SSL certificate
  3. Force HTTPS: Redirect all HTTP to HTTPS

Update Telegram Webhooks

# Update bot webhooks to use HTTPS
curl -X POST "https://api.telegram.org/bot{BOT_TOKEN}/setWebhook" \
     -H "Content-Type: application/json" \
     -d '{"url": "https://yourdomain.com/api/webhook/{BOT_TOKEN}"}'

Step 8: Final Configuration

File Permissions

chmod 755 uploads/
chmod 644 dist/index.js
chmod 600 .env
chmod 644 .htaccess

Test Deployment

  1. Visit: https://yourdomain.com
  2. Register: Create user account
  3. Admin Panel: https://yourdomain.com/167admin/login
  4. File Upload: Test upload functionality
  5. Bot Creation: Create and test Telegram bot

Production Setup

Performance Optimization

Database Optimization

-- Create indexes for frequently queried columns
CREATE INDEX idx_bots_user_id ON bots (user_id);
CREATE INDEX idx_bot_interactions_bot_id ON bot_interactions (bot_id);
CREATE INDEX idx_bot_analytics_bot_id_date ON bot_analytics (bot_id, date);
CREATE INDEX idx_users_username ON users (username);
CREATE INDEX idx_users_email ON users (email);

Application Performance

// Enable compression
app.use(compression());

// Set appropriate cache headers
app.use('/uploads', express.static('uploads', {
  maxAge: '1d',
  etag: true,
  lastModified: true
}));

// Rate limiting
const rateLimit = require('express-rate-limit');
app.use('/api/', rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
}));

Monitoring and Logging

Application Logging

// Winston logger configuration
const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
    new winston.transports.File({ filename: 'logs/combined.log' })
  ]
});

Database Monitoring

-- Monitor database performance
SELECT 
  schemaname,
  tablename,
  n_tup_ins,
  n_tup_upd,
  n_tup_del
FROM pg_stat_user_tables;

-- Check slow queries
SELECT query, mean_time, calls 
FROM pg_stat_statements 
ORDER BY mean_time DESC 
LIMIT 10;

Backup Strategy

Database Backup

# Daily backup script
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
pg_dump -h localhost -U botbuilder_user yourdomain_botbuilder > backups/db_backup_$DATE.sql
find backups/ -name "db_backup_*.sql" -mtime +7 -delete

File Backup

# Backup uploads directory
tar -czf backups/uploads_backup_$(date +%Y%m%d).tar.gz uploads/

Security Hardening

Environment Security

# Secure file permissions
chmod 600 .env
chmod 755 uploads/
chown -R www-data:www-data uploads/

Database Security

-- Revoke unnecessary permissions
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO botbuilder_user;

-- Enable row level security where needed
ALTER TABLE users ENABLE ROW LEVEL SECURITY;

Maintenance & Monitoring

Regular Maintenance Tasks

Weekly Tasks

Monthly Tasks

Quarterly Tasks

Troubleshooting Guide

Common Issues

Application Won’t Start

# Check Node.js version
node --version

# Check dependencies
npm audit

# Check logs
tail -f logs/combined.log

Database Connection Issues

# Test database connection
psql -h localhost -U botbuilder_user -d yourdomain_botbuilder

# Check database status
systemctl status postgresql

File Upload Problems

# Check permissions
ls -la uploads/

# Check disk space
df -h

# Test upload endpoint
curl -X POST -F "file=@test.txt" https://yourdomain.com/api/admin/upload-file

Support and Updates

Version Control

Documentation Maintenance


Conclusion

This Telegram Bot Builder Platform represents a comprehensive solution for no-code bot creation with enterprise-level features including subscription management, admin oversight, and scalable architecture. The detailed technical documentation and deployment guide ensure successful implementation on shared hosting environments while maintaining security and performance standards.

For additional support or custom configurations, refer to the individual component documentation or contact the development team.


Document Version: 1.0
Last Updated: January 26, 2025
Total Pages: Comprehensive Technical Guide