Advanced group management • Smart auto-reply • Comprehensive analytics • Multi-language support
Features • Quick Start • Commands • Documentation • Support
|
🤖 Advanced Command System 🌍 Multi-Language Support 🔐 Session Persistence |
📊 User Analytics Dashboard 📢 Smart Broadcasting 📝 Professional Logging |
|
|
|
|
|
|
👤 User Profiles - Complete identity management |
🏷️ Group Analysis - Membership tracking |
| Component | Requirement | Recommended |
|---|---|---|
| 🟢 Node.js | v18.0+ | v20 LTS |
| 📦 Package Manager | npm / yarn | npm v10+ |
| 💾 Database | SQLite3 | Latest |
| Active account | Business account | |
| 🌐 Browser | Chromium-based | Chrome/Edge |
# Clone the repository
git clone https://github.com/altmemy/wwebjs-pro-bot.git
# Navigate to directory
cd wwebjs-pro-bot
# Install dependencies
npm install# 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# Database auto-migrates on first run
npm run dev📌 Tables created automatically:
users- User profiles & statisticsgroup_settings- Group configurationspending_join_requests- Approval queuemember_warnings- Warning systemauto_reply_settings- Auto-reply config
npm run devHot-reload enabled |
npm run build
npm startOptimized performance |
📱 WhatsApp → Settings → Linked Devices → Link a Device
📷 Scan the QR code displayed in terminal
✅ Session saved to storage/.wwebjs_auth
| 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 |
| 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 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 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>📦 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
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'));
},
};src/commands/index.ts
import { myCommand } from './mycommand';
// In constructor
this.register(myCommand);| 🇬🇧 English (en/common.json) | 🇸🇦 Arabic (ar/common.json) |
|---|---|
{
"commands": {
"mycommand": {
"description": "My command description",
"response": "Command executed!"
}
}
} |
{
"commands": {
"mycommand": {
"description": "وصف الأمر",
"response": "تم تنفيذ الأمر!"
}
}
} |
📊 Database Extension Example (Click to expand)
// 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();
}// 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;
}
}// 🔨 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);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
}
});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
}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;
};
}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;
}
npm test |
npm run lint
npm run lint:fix |
npm run typecheck |
npm run build |
| 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 |
📱 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| 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 |
app.get('/health', (req, res) => {
res.json({
status: client.info ? 'ready' : 'connecting',
uptime: process.uptime(),
memory: process.memoryUsage(),
version: pkg.version
});
});- ⏱️ Message processing time
- 🎯 Command execution duration
- 💾 Database query performance
- 🧠 Memory usage trends
- ❌ Error rates by type
- 👥 User engagement metrics
| 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 |
This project is licensed under a Custom Attribution License - See LICENSE file for details.
| Permission | Status |
|---|---|
| ✅ Use, modify, distribute | Allowed |
| ✅ Commercial use | Allowed |
| ✅ Private use | Allowed |
| ❌ Reselling as-is | Not Allowed |
| ℹ️ Attribution | Required |
- 📝 Follow existing code style
- 🧪 Add tests for new features
- 📚 Update documentation
- ✅ Pass TypeScript compilation
- 🔍 Run linter before commit
| Requirement | Description |
|---|---|
| ✅ Consent | Obtain explicit user consent |
| 🔄 Opt-out | Provide clear unsubscribe options |
| ⏱️ Rate Limits | Respect WhatsApp limits |
| ⚖️ Legal Use | No illegal activities |
| Compliance | Implementation |
|---|---|
| 🇪🇺 GDPR | Implement for EU operations |
| 📤 Data Export | Provide export capabilities |
| 📝 Retention Policy | Document data policies |
| 🔒 Security | Secure user data properly |
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.