
# WhatsApp Web.js - WhatsApp Web Automation for Node.js

[![npm version](https://badge.fury.io/js/whatsapp-web-automation.svg)](https://www.npmjs.com/package/whatsapp-web-automation)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org/)

A pure Node.js library for automating WhatsApp Web, similar to [whatsapp-web.js](https://github.com/pedroslopez/whatsapp-web.js). Effectively controls WhatsApp Web in a browser using Puppeteer for authentic interactions like a real user.

## ⚠️ Important Disclaimer

**This library is not officially endorsed by WhatsApp.** WhatsApp does not allow bots or unofficial clients on their platform. Using this library may result in your WhatsApp account being banned. **Use at your own risk!**

## ✨ Features

- 🔐 **QR Code Authentication** - Connect by scanning QR code
- 💬 **Messages** - Send and receive text and media messages
- 👥 **Groups** - Complete group management (create, participants, admins)
- 📞 **Contacts** - Contact management and information
- 💾 **Persistent Sessions** - Avoid re-authentication by saving sessions
- 🎯 **Events** - Event-driven architecture
- 🤖 **Anti-detection** - Simulates human behavior with delays and randomization
- 📱 **Multi-device** - Support for WhatsApp's multi-device functionality

### Supported Message Types

| Feature | Status |
| --- | --- |
| Text messages | ✅ |
| Media messages (images/audio/documents) | ✅ |
| Video messages | ✅ |
| Stickers | ✅ |
| Location messages | ✅ |
| Contact cards | ✅ |
| Voice messages | ✅ |
| Message replies | ✅ |
| Message reactions | ✅ |
| Message deletion | ✅ |
| Message forwarding | ✅ |

### Group Features

| Feature | Status |
| --- | --- |
| Create groups | ✅ |
| Add/remove participants | ✅ |
| Promote/demote admins | ✅ |
| Group settings (name, description) | ✅ |
| Group invite links | ✅ |
| Leave groups | ✅ |
| Group notifications | ✅ |

## 📦 Installation

```bash
npm install whatsapp-web-automation
```

## 🚀 Quick Start

### Basic Usage

```javascript
const { Client } = require('whatsapp-web-automation');

// Create a new client instance
const client = new Client();

// QR Code event - scan with WhatsApp mobile app
client.on('qr', (qr) => {
    console.log('Scan this QR code with WhatsApp mobile app:');
    // The qr variable contains a base64 image data URL
    // Copy and paste it in a browser to see the QR code
    console.log(qr);
});

// Client is ready
client.on('ready', () => {
    console.log('WhatsApp client is ready!');
});

// Listen for new messages
client.on('message', async (message) => {
    console.log(`New message from ${message.from}: ${message.body}`);
    
    // Reply to messages that contain "hello"
    if (message.body.toLowerCase().includes('hello')) {
        await message.reply('Hello! How can I help you?');
    }
});

// Initialize the client
client.initialize();
```

### With Persistent Session (Recommended)

```javascript
const { Client, LocalAuth } = require('whatsapp-web-automation');

// Use LocalAuth to save session data
const client = new Client({
    authStrategy: new LocalAuth({
        clientId: 'my-bot',
        dataPath: './sessions'
    })
});

client.on('qr', (qr) => {
    console.log('Scan QR code (only needed first time):');
    console.log(qr);
});

client.on('ready', () => {
    console.log('Client is ready!');
});

client.on('message', async (message) => {
    if (message.body === '!ping') {
        await message.reply('pong');
    }
});

client.initialize();
```

## 📚 API Documentation

### Client Class

The main class for interacting with WhatsApp Web.

#### Constructor Options

```javascript
const client = new Client({
    authStrategy: new LocalAuth(), // Authentication strategy
    puppeteer: {
        headless: true,           // Run browser in headless mode
        args: ['--no-sandbox']    // Additional browser arguments
    },
    userAgent: 'Custom User Agent' // Custom user agent
});
```

#### Events

| Event | Description | Parameters |
|-------|-------------|------------|
| `qr` | QR code received for authentication | `qr` (string) - Base64 QR code image |
| `ready` | Client is ready to use | None |
| `message` | New message received | `message` (Message) |
| `message_create` | Message created (sent or received) | `message` (Message) |
| `auth_failure` | Authentication failed | `message` (string) |
| `disconnected` | Client disconnected | `reason` (string) |

#### Methods

##### `client.sendMessage(chatId, content, options)`

Send a message to a chat.

```javascript
// Send text message
await client.sendMessage('1234567890@c.us', 'Hello World!');

// Send with options
await client.sendMessage('1234567890@c.us', 'Hello!', {
    linkPreview: false
});
```

##### `client.getChats()`

Get all chats.

```javascript
const chats = await client.getChats();
console.log(`Found ${chats.length} chats`);
```

##### `client.getContacts()`

Get all contacts.

```javascript
const contacts = await client.getContacts();
console.log(`Found ${contacts.length} contacts`);
```

##### `client.isRegisteredUser(number)`

Check if a number is registered on WhatsApp.

```javascript
const isRegistered = await client.isRegisteredUser('1234567890');
console.log(`Number is registered: ${isRegistered}`);
```

### Message Class

Represents a WhatsApp message.

#### Properties

- `id` - Message ID
- `from` - Sender ID
- `to` - Recipient ID
- `body` - Message text content
- `type` - Message type
- `timestamp` - Message timestamp
- `fromMe` - Whether message was sent by the client

#### Methods

##### `message.reply(content, options)`

Reply to a message.

```javascript
client.on('message', async (message) => {
    if (message.body === 'Hi') {
        await message.reply('Hello there!');
    }
});
```

##### `message.forward(chatId)`

Forward a message to another chat.

```javascript
await message.forward('1234567890@c.us');
```

##### `message.delete(everyone)`

Delete a message.

```javascript
// Delete for me only
await message.delete();

// Delete for everyone (if sent recently)
await message.delete(true);
```

### MessageMedia Class

Handle media messages (images, videos, documents, audio).

#### Creating Media

```javascript
const { MessageMedia } = require('whatsapp-web-automation');

// From file path
const media = await MessageMedia.fromFilePath('./image.jpg');

// From URL (if implemented)
const media = await MessageMedia.fromUrl('https://example.com/image.jpg');

// Send media message
await client.sendMessage('1234567890@c.us', media, {
    caption: 'Check out this image!'
});
```

## 🔧 Advanced Usage

### Group Management

```javascript
// Create a group
const group = await client.createGroup('My Group', ['1234567890@c.us', '0987654321@c.us']);

// Get group info
const groupInfo = await group.getInfo();
console.log(groupInfo.name);

// Add participant
await group.addParticipants(['1111111111@c.us']);

// Remove participant
await group.removeParticipants(['1111111111@c.us']);

// Promote to admin
await group.promoteParticipants(['1234567890@c.us']);
```

### Message Filtering

```javascript
client.on('message', async (message) => {
    // Ignore messages from groups
    if (message.from.endsWith('@g.us')) return;
    
    // Ignore own messages
    if (message.fromMe) return;
    
    // Only respond to specific contacts
    const allowedContacts = ['1234567890@c.us', '0987654321@c.us'];
    if (!allowedContacts.includes(message.from)) return;
    
    // Process the message
    console.log(`Processing message: ${message.body}`);
});
```

### Auto-Reply Bot

```javascript
const responses = {
    'hello': 'Hi there! How can I help you?',
    'bye': 'Goodbye! Have a great day!',
    'help': 'Available commands:\n- hello\n- bye\n- help'
};

client.on('message', async (message) => {
    if (message.fromMe) return; // Ignore own messages
    
    const text = message.body.toLowerCase();
    
    if (responses[text]) {
        await message.reply(responses[text]);
    }
});
```

## 🛠️ Configuration

### Browser Configuration

```javascript
const client = new Client({
    puppeteer: {
        headless: false,          // Show browser window
        devtools: true,           // Open DevTools
        slowMo: 100,             // Slow down actions
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-extensions',
            '--disable-background-timer-throttling'
        ]
    }
});
```

### Session Management

```javascript
const { LocalAuth } = require('whatsapp-web-automation');

const authStrategy = new LocalAuth({
    clientId: 'unique-client-id',
    dataPath: './my-sessions',     // Custom session directory
    backupSyncIntervalMs: 300000   // Backup every 5 minutes
});

// Check if session exists
const hasAuth = await authStrategy.hasAuthData();
if (hasAuth) {
    console.log('Existing session found');
} else {
    console.log('First time setup - QR code required');
}
```

## 📱 QR Code Scanning

When you first run the client, you'll see a base64 data URL in the console:

1. **Method 1**: Copy the entire data URL and paste it in a new browser tab to see the QR code
2. **Method 2**: Use an online QR decoder like https://webqr.com
3. **Method 3**: Use your phone's camera to scan directly from the terminal/browser

On your phone:
1. Open WhatsApp
2. Go to Settings → Linked Devices
3. Tap "Link a Device"
4. Scan the QR code

## ⚠️ Important Notes

### Rate Limiting

WhatsApp has rate limits. Avoid:
- Sending too many messages in a short time
- Adding too many participants to groups quickly
- Making rapid API calls

### Best Practices

```javascript
// Add delays between actions
await new Promise(resolve => setTimeout(resolve, 1000));

// Handle errors gracefully
client.on('message', async (message) => {
    try {
        await message.reply('Hello!');
    } catch (error) {
        console.error('Failed to send message:', error);
    }
});

// Use session management for production
const client = new Client({
    authStrategy: new LocalAuth({ clientId: 'prod-bot' })
});
```

### Error Handling

```javascript
client.on('auth_failure', (message) => {
    console.error('Authentication failed:', message);
    process.exit(1);
});

client.on('disconnected', (reason) => {
    console.log('Client disconnected:', reason);
    // Implement reconnection logic if needed
});

// Graceful shutdown
process.on('SIGINT', async () => {
    console.log('Shutting down...');
    await client.destroy();
    process.exit(0);
});
```

## 🔍 Troubleshooting

### Common Issues

**QR Code not appearing**: Make sure you're copying the entire data URL starting with `data:image/png;base64,`

**Session not persisting**: Ensure the session directory has proper write permissions

**Browser crashes**: Try running with `headless: false` to see what's happening

**Rate limiting**: Add delays between API calls and reduce message frequency

### Debug Mode

```javascript
const client = new Client({
    puppeteer: {
        headless: false,
        devtools: true
    }
});

// Enable verbose logging
client.on('change_state', (state) => {
    console.log('State changed:', state);
});
```

## 📄 License

This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## ⚡ Support

If you encounter any issues or have questions, please open an issue on the GitHub repository.

---

**Remember**: This library is for educational purposes. Always respect WhatsApp's Terms of Service and use responsibly.
