# 📚 FCA-Priyansh Complete Documentation

**Comprehensive guides for Facebook Chat API (FCA) development**

**Maintained by:** [Priyanshu Rajput](https://priyanshuapi.xyz) | **GitHub:** [@priyanshfsdev](https://github.com/priyanshfsdev) | **GitLab:** [@priyanshufsdev](https://gitlab.com/priyanshufsdev) | **Instagram:** [@pri_yanshu12](https://instagram.com/pri_yanshu12) | **Telegram:** [@Priyanshrajput](https://t.me/Priyanshrajput)

---

## 📖 Table of Contents

1. [Getting Started Guide](#getting-started)
2. [Authentication & Login](#authentication)
3. [API Reference](#api-reference)
4. [Message Types & Features](#message-features)
5. [Event Handling](#event-handling)
6. [Advanced Topics](#advanced-topics)
7. [Troubleshooting](#troubleshooting)
8. [Best Practices](#best-practices)

---

## 🚀 Getting Started with FCA

### What is FCA-Priyansh?

**FCA (Facebook Chat API)** is a powerful Node.js library that allows you to:
- 🤖 Create automated Facebook Messenger bots
- 💬 Send and receive messages programmatically
- 📱 Build real-time chat applications
- 🔔 Implement notification systems
- 👥 Manage group conversations
- 📊 Monitor and log messages

FCA-Priyansh is the community-maintained fork with:
- ⚡ Faster feature updates
- 🐛 Active bug fixes
- 📈 Enhanced functionality
- 👥 Community support

### Installation

```bash
# From NPM (Recommended for production)
npm install fca-priyansh

# From GitLab (Latest development features)
npm install https://gitlab.com/priyanshufsdev/fca-priyansh.git

# From GitHub Mirror
npm install https://github.com/priyanshfsdev/fca-priyansh.git
```

### Minimum Requirements

- **Node.js:** 12.0 or higher (LTS recommended)
- **Operating System:** Windows, macOS, Linux
- **Internet:** Stable connection
- **Facebook Account:** For authentication
- **Basic JavaScript Knowledge:** For implementation

---

## 🔐 Authentication & Login Guide

### Method 1: Email & Password Login

**⚠️ Warning:** Storing passwords in code is NOT SAFE. Use AppState caching instead.

```javascript
const login = require("fca-priyansh");

login({
    email: "your@email.com",
    password: "your_password"
}, (err, api) => {
    if(err) return console.error(err);
    console.log("✅ Logged in successfully!");
    
    // Your bot code here
});
```

### Method 2: AppState Session Caching (RECOMMENDED)

#### Step 1: Generate and Save AppState

```javascript
const fs = require("fs");
const login = require("fca-priyansh");

var credentials = {
    email: "your@email.com",
    password: "your_password"
};

login(credentials, (err, api) => {
    if(err) return console.error(err);
    
    // Save the session
    var appState = api.getAppState();
    fs.writeFileSync('appstate.json', JSON.stringify(appState));
    console.log("✅ AppState saved! You can now use it for future logins.");
});
```

#### Step 2: Use Saved AppState (No Password Needed)

```javascript
const fs = require("fs");
const login = require("fca-priyansh");

var appState = JSON.parse(fs.readFileSync('appstate.json', 'utf8'));

login({appState: appState}, (err, api) => {
    if(err) return console.error(err);
    console.log("✅ Logged in using saved session!");
    
    // Your bot code here
});
```

### Login Options

```javascript
login(credentials, {
    pageID: "123456789",           // Login as a Facebook page
    selfListen: true,              // Receive your own messages
    listenEvents: true,            // Receive group events
    updatePresence: true,          // Show online status
    forceLogin: false,             // Force new login if session invalid
}, callback);
```

### Handling 2FA (Two-Factor Authentication)

```javascript
login({
    email: "your@email.com",
    password: "your_password",
    twoFactorNumber: "123456"      // Your 2FA code from authenticator app
}, (err, api) => {
    if(err) return console.error(err);
    // Logged in successfully
});
```

---

## 🎯 Core API Reference

### Message Operations

#### **api.sendMessage(message, threadID, [callback], [messageID])**

Send messages to individuals or groups.

**Parameters:**
- `message` (Object|String) - Message content object or text string
- `threadID` (String) - Target user or group ID
- `callback` (Function) - Optional callback for response
- `messageID` (String) - Optional message ID for replies

**Message Object Structure:**
```javascript
{
    body: "Text message",                           // Text content
    attachment: fs.createReadStream('image.jpg'),   // Single or array of files
    sticker: "STICKER_ID",                          // Sticker ID
    url: "https://example.com",                     // Link to share
    emoji: "😀",                                     // Emoji to react
    emojiSize: "large",                             // Emoji size: small/medium/large
    mentions: [{tag: "@name", id: "USER_ID"}]      // Mention users
}
```

**Example: Send Text Message**
```javascript
api.sendMessage("Hello! This is an automated message.", "USER_ID", (err) => {
    if(err) console.error("Failed to send message:", err);
    else console.log("✅ Message sent!");
});
```

**Example: Send Image**
```javascript
api.sendMessage({
    body: "Check out this image!",
    attachment: fs.createReadStream('photo.jpg')
}, "USER_ID");
```

**Example: Send Multiple Attachments**
```javascript
api.sendMessage({
    body: "Here are some files:",
    attachment: [
        fs.createReadStream('file1.pdf'),
        fs.createReadStream('file2.doc')
    ]
}, "USER_ID");
```

---

#### **api.sendTypingIndicator(threadID, [callback])**

Show "typing..." indicator in chat.

```javascript
api.sendTypingIndicator("USER_ID", (err) => {
    if(err) console.error(err);
    else console.log("Typing indicator sent");
});
```

---

#### **api.setMessageReaction(emoji, messageID, [callback])**

React to a message with emoji.

```javascript
api.setMessageReaction("😂", "MESSAGE_ID", (err) => {
    if(err) console.error(err);
    else console.log("✅ Reaction added!");
});
```

---

#### **api.deleteMessage(messageID, [callback])**

Delete a sent message (must be your own message).

```javascript
api.deleteMessage("MESSAGE_ID", (err) => {
    if(err) console.error(err);
    else console.log("✅ Message deleted!");
});
```

---

#### **api.unsendMessage(messageID, [callback])**

Unsend a message (removes for all participants).

```javascript
api.unsendMessage("MESSAGE_ID", (err) => {
    if(err) console.error(err);
    else console.log("✅ Message unsent!");
});
```

---

### Thread/Chat Operations

#### **api.getThreadList(limit, [timestamp], [callback])**

Get list of conversations.

```javascript
api.getThreadList(20, null, (err, threads) => {
    if(err) return console.error(err);
    
    threads.forEach(thread => {
        console.log(thread.name + " (" + thread.threadID + ")");
    });
});
```

---

#### **api.getThreadInfo(threadID, [callback])**

Get detailed information about a thread.

```javascript
api.getThreadInfo("THREAD_ID", (err, info) => {
    if(err) return console.error(err);
    
    console.log("Thread name:", info.threadName);
    console.log("Participants:", info.participantIDs);
    console.log("Unread count:", info.unreadCount);
});
```

---

#### **api.getThreadHistory(threadID, amount, [timestamp], [callback])**

Retrieve message history from a conversation.

```javascript
api.getThreadHistory("THREAD_ID", 10, null, (err, messages) => {
    if(err) return console.error(err);
    
    messages.forEach(msg => {
        console.log(msg.senderName + ": " + msg.body);
    });
});
```

---

#### **api.setTitle(newTitle, threadID, [callback])**

Change group chat title/name.

```javascript
api.setTitle("New Group Name 🎉", "GROUP_ID", (err) => {
    if(err) console.error(err);
    else console.log("✅ Title changed!");
});
```

---

#### **api.createNewGroup([names], [callback])**

Create a new group chat.

```javascript
var userIds = ["USER_ID_1", "USER_ID_2", "USER_ID_3"];

api.createNewGroup(userIds, (err, groupID) => {
    if(err) console.error(err);
    else console.log("✅ Group created: " + groupID);
});
```

---

### Message Markings

#### **api.markAsRead(threadID, [callback])**

Mark messages as read in a thread.

```javascript
api.markAsRead("THREAD_ID", (err) => {
    if(err) console.error(err);
    else console.log("✅ Marked as read!");
});
```

---

#### **api.markAsSeen(threadID, [callback])**

Mark thread as seen (removes notification badge).

```javascript
api.markAsSeen("THREAD_ID", (err) => {
    if(err) console.error(err);
});
```

---

### User Information

#### **api.getUserInfo(userIDs, [callback])**

Get information about users.

```javascript
api.getUserInfo(["USER_ID_1", "USER_ID_2"], (err, users) => {
    if(err) return console.error(err);
    
    Object.keys(users).forEach(id => {
        console.log(users[id].name);
        console.log(users[id].profilePicture);
    });
});
```

---

#### **api.getCurrentUserID()**

Get the ID of the logged-in account.

```javascript
var myID = api.getCurrentUserID();
console.log("My ID:", myID);
```

---

## 📞 Event Handling Guide

### Listening to Messages & Events

```javascript
api.setOptions({
    listenEvents: true,    // Receive group events
    selfListen: true       // Receive your own messages
});

api.listenMqtt((err, event) => {
    if(err) return console.error(err);
    
    switch(event.type) {
        case "message":
            console.log("Message from", event.senderName);
            console.log("Content:", event.body);
            break;
            
        case "event":
            console.log("Group event:", event.logMessageData);
            break;
    }
});
```

### Event Properties

**Message Event:**
```javascript
{
    type: "message",
    senderID: "USER_ID",
    senderName: "John Doe",
    threadID: "THREAD_ID",
    body: "Message text",
    isGroup: true,
    messageID: "MSG_ID",
    attachments: [],
    timestamp: 1609459200000
}
```

**Event (Group Change):**
```javascript
{
    type: "event",
    threadID: "GROUP_ID",
    logMessageType: "log:thread-name",  // Type of event
    logMessageData: {
        name: "New Group Name"           // Event details
    }
}
```

---

## 🔧 Advanced Topics

### Custom Error Handling

```javascript
login(credentials, (err, api) => {
    if(err) {
        switch(err.code) {
            case 1:  // Wrong email/password
                console.log("❌ Invalid credentials");
                break;
            case 2:  // 2FA needed
                console.log("⚠️ Two-factor authentication required");
                break;
            default:
                console.log("❌ Login failed:", err.message);
        }
        return;
    }
    
    // Successfully logged in
});
```

### Rate Limiting & Delays

```javascript
function sendMessageWithDelay(api, message, threadID, delayMs = 1000) {
    setTimeout(() => {
        api.sendMessage(message, threadID);
    }, delayMs);
}

// Send multiple messages with delays to avoid spam detection
var messages = ["Hello", "How are you?", "I'm a bot!"];
messages.forEach((msg, index) => {
    sendMessageWithDelay(api, msg, "THREAD_ID", index * 2000);
});
```

### Session Persistence

```javascript
const fs = require("fs");
const path = require("path");

const saveAppState = (appState, filePath = 'appstate.json') => {
    fs.writeFileSync(path.join(__dirname, filePath), 
                     JSON.stringify(appState, null, 2));
};

const loadAppState = (filePath = 'appstate.json') => {
    return JSON.parse(fs.readFileSync(path.join(__dirname, filePath), 'utf8'));
};

// Usage
saveAppState(api.getAppState());
// Later...
login({appState: loadAppState()}, callback);
```

---

## 🐛 Troubleshooting Common Issues

### Issue: "repository not found"
**Solution:** Check your GitLab/GitHub URL and credentials.

### Issue: Messages not sending
**Solution:**
1. Verify threadID is correct
2. Check account is not temporarily blocked
3. Ensure you have permission to message the user
4. Look for rate limiting (too many messages)

### Issue: Login fails with valid credentials
**Solution:**
1. Try manual login on Facebook.com
2. Check for 2FA or security alerts
3. Try disabling browser extensions
4. Wait 15 minutes if account is temporarily locked

### Issue: listenMqtt stops working
**Solution:**
1. Restart the bot
2. Check internet connection
3. Verify AppState is still valid
4. Re-login if session expired

---

## ✅ Best Practices

### 1. Secure Credential Management
```javascript
// ❌ DON'T: Store credentials in code
const credentials = {
    email: "user@gmail.com",
    password: "password123"
};

// ✅ DO: Use environment variables
const credentials = {
    email: process.env.FB_EMAIL,
    password: process.env.FB_PASSWORD
};

// ✅ BEST: Use saved AppState
const credentials = {
    appState: JSON.parse(fs.readFileSync('.appstate.json'))
};
```

### 2. Error Handling
```javascript
api.sendMessage(message, threadID, (err) => {
    if(err) {
        console.error("❌ Send failed:", err.message);
        // Retry logic or logging
    }
});
```

### 3. Rate Limiting
```javascript
// Add delays between messages
setTimeout(() => {
    api.sendMessage("Message 1", threadID);
}, 1000);

setTimeout(() => {
    api.sendMessage("Message 2", threadID);
}, 3000);
```

### 4. Logging & Monitoring
```javascript
api.setOptions({
    logLevel: "warning"  // Only show warnings and errors
});

// Log all events
api.listenMqtt((err, event) => {
    console.log(`[${new Date().toISOString()}] Event:`, event.type);
});
```

### 5. Graceful Shutdown
```javascript
const stopListening = api.listenMqtt((err, event) => {
    // Handle events
});

// Clean shutdown
process.on("SIGINT", () => {
    console.log("Shutting down...");
    stopListening();
    process.exit(0);
});
```

---

## 📞 Support & Community

### Get Help

- 📖 **Read Docs:** Check [README.md](README.md)
- 🐛 **Report Bugs:** [GitLab Issues](https://gitlab.com/priyanshufsdev/fca-priyansh/-/issues)
- 💬 **Ask Questions:** [Telegram Community](https://t.me/Priyanshrajput)
- 📧 **Email:** Contact via [priyanshuapi.xyz](https://priyanshuapi.xyz)

### Related Resources

- [Facebook Messenger Platform](https://developers.facebook.com/docs/messenger-platform)
- [Node.js Documentation](https://nodejs.org/docs/)
- [NPM Package](https://www.npmjs.com/package/fca-priyansh)

---

## 📝 License

This documentation and code are licensed under the MIT License. See [LICENSE](LICENSE) for details.

---

**Last Updated:** March 2026 | **Version:** FCA-Priyansh Latest | **Maintainer:** [Priyanshu Rajput](https://priyanshuapi.xyz)

**Happy Bot Building! 🤖** Built with ❤️ by the FCA Community
