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.
-- 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
);-- 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_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()
);-- 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)
);├── 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
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
// 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} />dist/public/// 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/
├── 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
// 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
});// 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);/167admin/* URLs{
"username": "string",
"email": "string",
"password": "string",
"firstName": "string",
"lastName": "string"
}{
"username": "string",
"password": "string"
}Returns array of user’s bots
{
"name": "string",
"username": "string",
"token": "string",
"description": "string"
}{
"menuStructure": "object",
"settings": "object",
"isActive": "boolean"
}Content-Type: multipart/form-data Field: file
Response:
{
"success": true,
"filename": "string",
"originalName": "string",
"size": "number",
"url": "string"
}{
"totalUsers": "number",
"totalBots": "number",
"totalPayments": "number",
"totalRevenue": "number",
"activeSubscriptions": "number"
}# Install dependencies
npm install
# Build for production
npm run build
# This creates:
# - dist/public/ (frontend static files)
# - dist/index.js (backend server bundle)cPanel → PostgreSQL Databases
Create Database:
yourdomain_botbuilder
Create User: botbuilder_user with
strong password
Assign User: Grant all privileges to database
Note Connection String:
postgresql://botbuilder_user:password@localhost:5432/yourdomain_botbuilder-- Execute all table creation scripts from shared/schema.ts
-- Or use migration tool:
npm run db:pushINSERT INTO admin_users (username, password, role)
VALUES ('admin', '$2b$10$hashed_password_here', 'super_admin');# In cPanel File Manager, create:
public_html/
├── dist/
│ ├── public/ # Frontend assets
│ └── index.js # Backend server
├── uploads/ # File upload directory (755 permissions)
├── package.json
├── .env
└── .htaccessNODE_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
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"Access: cPanel → Node.js Selector
Create Application:
/public_htmldist/index.jsInstall Dependencies:
cd /public_html
npm install --only=production# Navigate to public_html
cd /public_html
# Install Node.js dependencies
npm install --only=production
# Start application (use process manager)
npm start# 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 monitnpm install -g forever
forever start dist/index.js# 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 &# 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}"}'chmod 755 uploads/
chmod 644 dist/index.js
chmod 600 .env
chmod 644 .htaccesshttps://yourdomain.comhttps://yourdomain.com/167admin/login-- 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);// 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
}));// 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' })
]
});-- 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;# 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# Backup uploads directory
tar -czf backups/uploads_backup_$(date +%Y%m%d).tar.gz uploads/# Secure file permissions
chmod 600 .env
chmod 755 uploads/
chown -R www-data:www-data uploads/-- 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;Application Won’t Start
# Check Node.js version
node --version
# Check dependencies
npm audit
# Check logs
tail -f logs/combined.logDatabase Connection Issues
# Test database connection
psql -h localhost -U botbuilder_user -d yourdomain_botbuilder
# Check database status
systemctl status postgresqlFile 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-fileThis 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