Skip to content

About

WhatsApp group-management bot in TypeScript — command framework, auto-reply, analytics, English/Arabic i18n

Topics

Resources

Stars

14 stars

Watchers

0 watching

Forks

Repository files navigation

WhatsApp Web.js Pro Bot 🚀

WhatsApp TypeScript Node.js



Node.js Version TypeScript WhatsApp Web.js License PRs Welcome


🏆 Enterprise-Grade WhatsApp Bot Solution

Advanced group management • Smart auto-reply • Comprehensive analytics • Multi-language support


Features • Quick Start • Commands • Documentation • Support


✨ Features

🎯 Core Functionality

🤖 Advanced Command System
Extensible framework with custom prefix support

🌍 Multi-Language Support
Full i18n (English & Arabic) with per-chat preferences

🔐 Session Persistence
LocalAuth for seamless reconnection

📊 User Analytics Dashboard
Track activity, locations, groups & statistics

📢 Smart Broadcasting
Opt-in/out system with intelligent rate limiting

📝 Professional Logging
Structured logs with Pino & correlation IDs

👥 Professional Group Management

🎫 Access Control

  • ✅ Auto-approval system
  • 📍 Location verification
  • 💬 Introduction requirements

🛡️ Protection Systems

  • ⚠️ Warning management
  • 🚫 Anti-spam protection
  • 🔕 Quiet hours enforcement

📈 Analytics & Rules

  • 📋 Automated rule distribution
  • 📊 Detailed group statistics
  • 👁️ Member activity tracking

🔄 Smart Auto-Reply System

⚙️ Configuration

  • 🎯 Trigger customization (all/contacts/groups/private)
  • 📝 Dynamic templates with variables
  • ⏰ Active hours scheduling
  • 🚫 Smart exclusion lists

🧠 Intelligence

  • ⏱️ Natural reply delays
  • 🛡️ Anti-spam protection
  • 📊 Response analytics
  • 🔄 Context awareness

📡 Enhanced Data Collection

👤 User Profiles - Complete identity management
📍 Location Tracking - Geographic data storage
👁️ Activity Monitoring - Last seen patterns

🏷️ Group Analysis - Membership tracking
💬 Message Analytics - Interaction statistics
🔍 Media Detection - View-once & media tracking


📋 Requirements

Component Requirement Recommended
🟢 Node.js v18.0+ v20 LTS
📦 Package Manager npm / yarn npm v10+
💾 Database SQLite3 Latest
📱 WhatsApp Active account Business account
🌐 Browser Chromium-based Chrome/Edge

🚀 Quick Start

1️⃣ Clone Repository

# Clone the repository
git clone https://github.com/altmemy/wwebjs-pro-bot.git

# Navigate to directory
cd wwebjs-pro-bot

# Install dependencies
npm install

2️⃣ Configure Environment

# Create environment file
cp .env.example .env
📝 Configuration Example (Click to expand)
# ═══════════════════════════════════════════
# 🤖 BOT CONFIGURATION
# ═══════════════════════════════════════════
BOT_NAME=Pro WhatsApp Bot
CMD_PREFIX=/
DEFAULT_LANG=en
WWEBJS_CLIENT_ID=bot
LOG_LEVEL=info

# ═══════════════════════════════════════════
# 👑 ADMIN CONFIGURATION
# ═══════════════════════════════════════════
# Comma-separated JIDs or phone numbers
ADMINS=1234567890,9876543210@c.us

# ═══════════════════════════════════════════
# 🌐 OPTIONAL: SYSTEM CHROME
# ═══════════════════════════════════════════
# PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome-stable

3️⃣ Initialize Database

# Database auto-migrates on first run
npm run dev

📌 Tables created automatically:

  • users - User profiles & statistics
  • group_settings - Group configurations
  • pending_join_requests - Approval queue
  • member_warnings - Warning system
  • auto_reply_settings - Auto-reply config

4️⃣ Start the Bot

🔧 Development Mode

npm run dev

Hot-reload enabled

🏭 Production Mode

npm run build
npm start

Optimized performance

5️⃣ Authenticate

📱 WhatsApp → Settings → Linked Devices → Link a Device
📷 Scan the QR code displayed in terminal
✅ Session saved to storage/.wwebjs_auth

📱 Commands

🌐 General Commands

Command Description Access Example
/help 📚 Display available commands Everyone /help
/ping 🏓 Check bot status Everyone /ping
/lang 🌍 Change language Everyone /lang ar
/optin ✅ Subscribe to broadcasts Everyone /optin
/optout ❌ Unsubscribe from broadcasts Everyone /optout
/stats 📊 View statistics Admin /stats

👑 Admin Commands

Command Description Example
/broadcast 📢 Send to all subscribers /broadcast Hello everyone!
/group 👥 Manage group settings /group status 123456789@g.us
/autoreply 🔄 Configure auto-replies /autoreply enable

🛠️ Group Management (Admin Only)

⚙️ Group Configuration Commands (Click to expand)
# 📊 View Settings
/group status <groupId>

# 🎫 Join Requirements
/group autoapprove <groupId> [on|off]
/group requirelocation <groupId> [on|off]
/group requireintro <groupId> [on|off]

# 📋 Rules Management
/group rules <groupId> <rules text>
/group sendrules <groupId> [on|off]

# 👋 Welcome Configuration
/group welcome <groupId> <message>

# 🛡️ Protection Settings
/group antispam <groupId> [on|off]
/group maxmessages <groupId> <number>

# ⚠️ Warning System
/group maxwarnings <groupId> <number>
/group warn <groupId> <userId> <reason>

# 📎 Media Restrictions
/group allowmedia <groupId> [on|off]
/group allowlinks <groupId> [on|off]
/group allowforwards <groupId> [on|off]

🔄 Auto-Reply Configuration (Admin Only)

🤖 Auto-Reply Commands (Click to expand)
# 📊 View Status
/autoreply status

# 🔌 Enable/Disable
/autoreply enable
/autoreply disable

# 🎯 Reply Type
/autoreply type [all|contacts|groups|private]

# 📝 Message Template
/autoreply message <template>
# Available variables: {name}, {time}, {date}

# ⏰ Active Hours (24h format)
/autoreply hours <start> <end>
# Example: /autoreply hours 09:00 17:00

# ⏱️ Reply Delay
/autoreply delay <seconds>

# 🚫 Exclusions
/autoreply exclude group <groupId>
/autoreply exclude contact <contactId>
/autoreply include group <groupId>
/autoreply include contact <contactId>

🏗️ Architecture

📦 wwebjs-pro-bot/
│
├── 📂 src/
│   ├── 📄 index.ts              # Application bootstrap
│   ├── ⚙️ config.ts             # Environment config
│   ├── 📝 logger.ts             # Structured logging
│   │
│   ├── 📂 types/                # TypeScript definitions
│   │   ├── index.ts
│   │   └── group.ts
│   │
│   ├── 🌍 i18n/                 # Internationalization
│   │   └── index.ts
│   │
│   ├── 🔀 router/               # Message routing
│   │   └── messageRouter.ts
│   │
│   ├── 💻 commands/             # Command handlers
│   │   ├── index.ts
│   │   ├── help.ts
│   │   ├── ping.ts
│   │   ├── lang.ts
│   │   ├── optin.ts
│   │   ├── optout.ts
│   │   ├── broadcast.ts
│   │   ├── stats.ts
│   │   ├── group.ts
│   │   └── autoreply.ts
│   │
│   ├── 🔧 services/             # Business logic
│   │   ├── languageService.ts
│   │   ├── autoResponder.ts
│   │   ├── broadcastService.ts
│   │   ├── groupManager.ts
│   │   └── autoReplyManager.ts
│   │
│   ├── 💾 db/                   # Database layer
│   │   ├── index.ts
│   │   └── migrations.ts
│   │
│   └── 📊 repositories/         # Data access
│       └── userRepo.ts
│
├── 🌐 locales/                  # Translations
│   ├── en/common.json
│   └── ar/common.json
│
└── 💿 storage/                  # Persistent data
    ├── .wwebjs_auth/
    ├── .wwebjs_cache/
    ├── bot.db
    └── lang-prefs.json

🔧 Development Guide

🆕 Adding New Commands

Step 1: Create Handler

src/commands/mycommand.ts

import { CommandDef } from '../types';

export const myCommand: CommandDef = {
  name: 'mycommand',
  descriptionKey: 'commands.mycommand.description',
  usage: '/mycommand <arg>',
  adminOnly: false,
  
  async execute(ctx) {
    const { message, t, client, user } = ctx;
    
    // ✨ Command logic
    const args = message.body.split(' ').slice(1);
    
    // 👤 Access user data
    if (user) {
      logger.info(`Command from ${user.name}`);
    }
    
    // 💬 Send reply
    await message.reply(t('commands.mycommand.response'));
  },
};

Step 2: Register Command

src/commands/index.ts

import { myCommand } from './mycommand';

// In constructor
this.register(myCommand);

Step 3: Add Translations

🇬🇧 English (en/common.json) 🇸🇦 Arabic (ar/common.json)
{
  "commands": {
    "mycommand": {
      "description": "My command description",
      "response": "Command executed!"
    }
  }
}
{
  "commands": {
    "mycommand": {
      "description": "وصف الأمر",
      "response": "تم تنفيذ الأمر!"
    }
  }
}

💾 Extending Database Schema

📊 Database Extension Example (Click to expand)

1. Add Migration

// src/db/migrations.ts
export function runMigrations() {
  const db = getDb();
  
  db.exec(`
    CREATE TABLE IF NOT EXISTS my_table (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      user_id TEXT NOT NULL,
      data TEXT,
      created_at INTEGER NOT NULL,
      FOREIGN KEY (user_id) REFERENCES users(jid)
    )
  `);
  
  db.close();
}

2. Create Repository

// src/repositories/myRepo.ts
import { getDb } from '../db';

export class MyRepo {
  static create(data: MyData) {
    const db = getDb();
    const stmt = db.prepare(`
      INSERT INTO my_table (user_id, data, created_at)
      VALUES (?, ?, ?)
    `);
    const result = stmt.run(data.userId, data.data, Date.now());
    db.close();
    return result;
  }
  
  static findByUser(userId: string) {
    const db = getDb();
    const rows = db.prepare('SELECT * FROM my_table WHERE user_id = ?')
      .all(userId);
    db.close();
    return rows;
  }
}

🔌 Working with Services

// 🔨 Create service
export class MyService {
  private client: Client;
  
  constructor(client: Client) {
    this.client = client;
  }
  
  async processData(message: Message) {
    const chat = await message.getChat();
    const contact = await message.getContact();
    
    return {
      chatId: chat.id._serialized,
      userName: contact.pushname
    };
  }
}

// ✨ Use in handler
const myService = new MyService(client);
const result = await myService.processData(message);

📨 Message Type Detection

client.on('message', async (message: Message) => {
  // 🖼️ Media detection
  if (message.hasMedia) {
    const media = await message.downloadMedia();
    logger.info(`Media: ${media.mimetype}`);
  }
  
  // 📍 Location detection
  if (message.location) {
    logger.info(`Location: ${message.location.latitude}, ${message.location.longitude}`);
  }
  
  // 👁️ Ephemeral detection
  if (message.isEphemeral) {
    logger.info('View-once detected');
  }
  
  // 💬 Type checking
  switch(message.type) {
    case 'chat': // Text
    case 'image': // Image
    case 'video': // Video
    case 'document': // Document
  }
});

🔍 API Reference

📦 CommandContext

interface CommandContext {
  message: Message;              // WhatsApp message
  client: Client;               // WhatsApp client
  user?: User;                  // Database user
  lang: string;                 // Current language
  t: TFunction;                 // Translation function
  isAdmin: boolean;             // Admin status
  groupManager?: GroupManager;  // Group service
  autoReplyManager?: AutoReplyManager; // Auto-reply service
}

👤 User Object

interface User {
  jid: string;                  // WhatsApp JID
  number: string;               // Phone number
  name?: string;                // Display name
  pushname?: string;            // WhatsApp name
  profilePic?: string;          // Avatar URL
  isSubscribed: boolean;        // Broadcast status
  firstSeenAt: number;          // First interaction
  lastSeenAt: number;           // Last interaction
  messageCount: number;         // Total messages
  groups?: string[];            // Group memberships
  lastLocation?: {              // Location data
    latitude: number;
    longitude: number;
    address?: string;
  };
}

👥 GroupSettings

interface GroupSettings {
  groupId: string;
  groupName?: string;
  autoApproveJoins: boolean;
  requireLocation: boolean;
  requireIntroduction: boolean;
  joinWelcomeMessage?: string;
  rules?: string;
  sendRulesOnJoin: boolean;
  maxWarnings: number;
  antiSpamEnabled: boolean;
  maxMessagesPerMinute?: number;
  allowMedia: boolean;
  allowLinks: boolean;
  allowForwards: boolean;
}

🚦 Testing

🧪 Unit Tests

npm test

🔍 Linting

npm run lint
npm run lint:fix

📝 Type Check

npm run typecheck

🏗️ Build

npm run build

💡 Development Tips

Tip Description
🎯 TypeScript Strict Enable strict mode for better type safety
🏛️ Repository Pattern Separate data access from business logic
🔧 Service Layer Keep commands thin, services rich
🛡️ Error Handling Always wrap async operations in try-catch
📝 Strategic Logging Use structured logs with correlation IDs
🧪 Edge Cases Test network failures & rate limits
⏱️ Rate Limits Add delays in bulk operations

🛠️ Troubleshooting

❗ Common Issues

📱 QR Code Not Showing
# Check terminal width
# Ensure LOG_LEVEL != 'error'
# Restart with:
npm run dev
🔄 Authentication Loop
# Clear session data
rm -rf storage/.wwebjs_auth
rm -rf storage/.wwebjs_cache

# Ensure stable internet
# Check WhatsApp Web accessibility
💾 Database Errors
# Reset database (WARNING: Data loss!)
rm storage/bot.db
npm run dev  # Auto-recreates with migrations
🌐 Puppeteer Issues
# Option 1: Use system Chrome
export PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome-stable

# Option 2: Install dependencies (Ubuntu/Debian)
sudo apt-get install -y \
  libnss3 libatk-bridge2.0-0 libdrm2 \
  libxkbcommon0 libgbm1 libasound2
📦 TypeScript Errors
# Clean rebuild
rm -rf dist/
npm run build

⚡ Performance Optimization

Optimization Implementation
🗄️ Indexes Add database indexes for frequent queries
📦 Batching Process messages in batches
💾 Caching Cache frequently accessed data
🔄 Pooling Reuse database connections
🚀 Lazy Load Load services on demand

📈 Monitoring

🏥 Health Checks

app.get('/health', (req, res) => {
  res.json({
    status: client.info ? 'ready' : 'connecting',
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    version: pkg.version
  });
});

📊 Key Metrics

  • ⏱️ Message processing time
  • 🎯 Command execution duration
  • 💾 Database query performance
  • 🧠 Memory usage trends
  • ❌ Error rates by type
  • 👥 User engagement metrics

🔐 Security Best Practices

Practice Description
🔑 Environment Variables Never commit .env files
🧹 Input Validation Sanitize all user inputs
🚦 Rate Limiting Prevent abuse with limits
👮 Access Control Verify admin privileges
🔒 Data Encryption Encrypt sensitive data
📦 Dependencies Regular security updates
📝 Audit Logging Log all admin actions
💾 Backup Strategy Automated backups

👨‍💻 Author

Altememy

X (Twitter)

🚀 Available for custom bot development & consulting
📧 Contact via X for project inquiries


📜 License

This project is licensed under a Custom Attribution License - See LICENSE file for details.

License Terms:

Permission Status
✅ Use, modify, distribute Allowed
✅ Commercial use Allowed
✅ Private use Allowed
❌ Reselling as-is Not Allowed
ℹ️ Attribution Required

Contributing

  • 📝 Follow existing code style
  • 🧪 Add tests for new features
  • 📚 Update documentation
  • ✅ Pass TypeScript compilation
  • 🔍 Run linter before commit

⚖️ Legal & Compliance

📱 WhatsApp Terms of Service

Requirement Description
✅ Consent Obtain explicit user consent
🔄 Opt-out Provide clear unsubscribe options
⏱️ Rate Limits Respect WhatsApp limits
⚖️ Legal Use No illegal activities

🛡️ Data Protection

Compliance Implementation
🇪🇺 GDPR Implement for EU operations
📤 Data Export Provide export capabilities
📝 Retention Policy Document data policies
🔒 Security Secure user data properly

⚠️ Disclaimer

This bot is not officially affiliated with WhatsApp or Meta. Use at your own risk and ensure compliance with all applicable laws and WhatsApp's Terms of Service.



Built with ❤️ using whatsapp-web.js

Created by Altememy


Made with Love

About

WhatsApp group-management bot in TypeScript — command framework, auto-reply, analytics, English/Arabic i18n

Topics

Resources

Stars

14 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages