<div align="center">

<img src="https://i.imgur.com/EDFXxM4.jpeg" alt="FCA-SIFU" width="100%" />

<br>

<h3>Advance Facebook Chat API for Node.js  {Made by SIFAT} </h3>
<p>Real-time MQTT · Auto-revival · Stealth stack · Full Messenger surface</p>

<br>

[![npm](https://img.shields.io/npm/v/fca-sifu?style=for-the-badge&color=06b6d4&labelColor=0f172a&logo=npm&logoColor=white)](https://www.npmjs.com/package/fca-sifu)
[![downloads](https://img.shields.io/npm/dm/fca-sifu?style=for-the-badge&color=10b981&labelColor=0f172a&logo=npm&logoColor=white)](https://www.npmjs.com/package/fca-sifu)
[![node](https://img.shields.io/badge/node-%E2%89%A518.0-22c55e?style=for-the-badge&labelColor=0f172a&logo=node.js&logoColor=white)](https://nodejs.org)
[![license](https://img.shields.io/badge/license-MIT-a78bfa?style=for-the-badge&labelColor=0f172a)](LICENSE)
[![stars](https://img.shields.io/github/stars/myb-sifu/fca-sifu?style=for-the-badge&color=f59e0b&labelColor=0f172a&logo=github&logoColor=white)](https://github.com/myb-sifu/fca-sifu)

<br>

[Install](#-install) · [Quick Start](#-quick-start) · [API Reference](#-api-reference) · [Stealth System](#-stealth-system) · [Themes](#-ai-themes) · [FAQ](#-faq)

</div>

---

## Overview

FCA-SIFU is a drop-in Facebook Chat API built for longevity. It replaces polling with a direct MQTT connection, wraps every session in a layered protection stack, and exposes the full Messenger surface through a clean async API.

Works out of the box with **Goat-Bot V2**, **Mirai**, **MARIN-BOT-V1**, and any bot that previously used `fca-unofficial`.

<br>

## Feature Matrix

| Area | What you get |
|------|-------------|
| **Transport** | MQTT-first, sub-second delivery, auto-reconnect |
| **Session** | Cookie + email/password login, TOTP 2FA support |
| **Stealth** | Identity rotation, warmup mode, circuit breaker |
| **Reliability** | Auto-revival, token refresh cycle, session watchdog |
| **Rate limiting** | Adaptive gate — stays under Facebook's thresholds |
| **Vault** | AES-encrypted runtime secret store (`SifuCipher`) |
| **Messaging** | Send, edit, react, unsend, forward, broadcast |
| **Threads** | Create, manage, archive, delete, theme, emoji |
| **AI Themes** | Generate Messenger themes from a text prompt |
| **Media** | Attachments, images, video, location, stickers |
| **Users** | Profile, avatar, bio, cover, friends, block |
| **Groups** | Create, admin, image, polls, notes, add/remove |
| **TypeScript** | Full `.d.ts` type definitions included |

<br>

## Install

```bash
npm install fca-sifu
```

> Requires **Node.js ≥ 18**

<br>

## Quick Start

```js
const login = require("fca-sifu");

login({ appState: require("./appstate.json") }, (err, api) => {
    if (err) return console.error(err);

    api.setOptions({
        listenEvents:     true,
        autoMarkDelivery: true,
        autoMarkRead:     false,
    });

    api.listenMqtt((err, event) => {
        if (err) return console.error(err);

        if (event.type === "message" && event.body === "/ping") {
            api.sendMessage("pong", event.threadID);
        }
    });
});
```

Both callback and Promise styles are supported on every method.

<br>

## Login Options

<details open>
<summary><strong>Cookie login (recommended)</strong></summary>
<br>

Export cookies from your browser with a tool like *C3C FBState*, save as `appstate.json`, then:

```js
login({ appState: require("./appstate.json") }, callback);
```

</details>

<details>
<summary><strong>Email + password</strong></summary>
<br>

```js
login({ email: "you@example.com", password: "••••••••" }, callback);
```

</details>

<details>
<summary><strong>Email + password + TOTP 2FA</strong></summary>
<br>

```js
login({
    email:      "you@example.com",
    password:   "••••••••",
    totpSecret: "YOUR_TOTP_SECRET",
}, callback);
```

</details>

<details>
<summary><strong>With options and proxy</strong></summary>
<br>

```js
login(credentials, {
    online:           true,
    selfListen:       false,
    listenEvents:     true,
    autoMarkDelivery: true,
    autoReconnect:    true,
    proxy:            "http://user:pass@host:port",
}, callback);
```

</details>

<br>

## API Reference

### Messaging

```js
// Send
api.sendMessage("Hello!", threadID);
api.sendMessage({ body: "look", attachment: fs.createReadStream("img.png") }, threadID);

// Edit / delete
api.editMessage("corrected text", messageID);
api.unsendMessage(messageID);

// Forward
api.forwardMessage(messageID, threadID);
api.broadcastMessage("Announcement", [id1, id2, id3]);

// Schedule (sends after delay)
api.scheduleMessage("Reminder!", threadID, Date.now() + 60_000);
```

### Reactions & Receipts

```js
api.setMessageReaction("❤️", messageID);
api.markAsRead(threadID);
api.markAsDelivered(threadID);
api.markAsReadAll();

// Auto-unsend any message the bot sent when someone reacts
api.unsendOnReaction();                        // all reactions
api.unsendOnReaction({ triggers: ["😡","👎"] }); // specific reactions
api.unsendOnReaction.disable();
```

> Call `unsendOnReaction()` **before** `listenMqtt()` so it can hook into the stream.

### Threads

```js
api.getThreadInfo(threadID);
api.getThreadHistory(threadID, 30, null);
api.getThreadList(10, null, ["INBOX"]);
api.changeNickname("Bot", threadID, userID);
api.changeGroupImage(imageStream, threadID);
api.changeThreadName("New name", threadID);
api.createNewGroup([uid1, uid2], "Group name");
api.addUserToGroup(userID, threadID);
api.removeUserFromGroup(userID, threadID);
api.changeAdminStatus(threadID, userID, true);
api.createPoll("Question?", threadID, { "Yes": true, "No": false });
```

### Users & Friends

```js
api.getUserInfo(userID);
api.getUserInfoV2(userID);
api.getFriendsList();
api.addFriend(userID);
api.changeAvatar(imageStream);
api.changeBio("New bio");
```

### Real-time

```js
api.listenMqtt(callback);    // start listener
api.stopListening();          // stop listener
api.isSessionAlive();         // → Promise<boolean>
api.getHealthStatus();        // MQTT, rate-limiter, token cycle stats
```

### Session & Tokens

```js
api.getAppState();            // export current cookie state
api.refreshTokens();          // force token refresh
api.getCycleStatus();         // token cycle health
api.disconnect();             // graceful logout
```

<br>

## AI Themes

Generate and apply Messenger themes from a natural-language prompt.

```js
// Generate themes
const themes = await api.createAITheme("ocean sunset", 3);
console.log(themes[0].name, themes[0].preview_image_urls.light_mode);

// Apply a theme to a thread
await api.setThreadTheme(threadID, { themeId: themes[0].id });

// Or use the unified theme() helper
await api.theme("ai:dark neon galaxy", threadID);
await api.theme("list", threadID);   // list all available themes
await api.theme("ocean", threadID);  // fuzzy match by name
await api.theme("undo", threadID);   // revert to previous

// Full AI theme producer (structured output)
const result = await api.produceMetaTheme("aurora borealis", { numThemes: 2 });
console.log(result.themes[0].colors.gradient);
```

<br>

## Stealth System

Four cooperating managers run automatically after login:

```
┌─────────────┬─────────────────────────────────────────────────┐
│ Shield      │ Circuit breaker + warmup mode on fresh starts   │
│ Revive      │ Detects expired sessions and re-authenticates   │
│ Heartbeat   │ Refreshes auth tokens before expiry             │
│ Gate        │ Adaptive rate-limiter, respects FB thresholds   │
└─────────────┴─────────────────────────────────────────────────┘
```

You can inspect or control them at runtime:

```js
api.shield.getStatus();
api.shield.reset();
api.isAutoReviveActive();
api.enableAutoRevive(false);

const { globalRateLimiter, globalShield, globalMonitor } = require("fca-sifu");
globalRateLimiter.pause(5000);
globalShield.setDailyLimit(200);
```

### Encrypted Vault

```js
const { globalCipher } = require("fca-sifu");

globalCipher.set("myToken", "secret-value");
globalCipher.get("myToken");   // decrypted
globalCipher.delete("myToken");
```

<br>

## Top-level Exports

```js
const {
    connect,              // login function
    globalShield,         // circuit breaker
    globalReviveManager,  // session revival
    globalGate,           // rate limiter
    globalRateLimiter,    // rate limiter (alias)
    globalMonitor,        // telemetry
    globalCache,          // in-memory cache
    globalCipher,         // encrypted vault
    CycleManager,         // token refresh
    TokenRefreshManager,
    SifuCipher,
    configureRateLimiter,
    getRateLimiterStats,
} = require("fca-sifu");
```

<br>

## Compatibility

| Framework | Status |
|-----------|--------|
| Goat-Bot V2 | Drop-in |
| Mirai | Drop-in |
| MARIN-BOT-V1 | Drop-in |
| fca-unofficial | Drop-in replacement |
| Custom bots | Full support |

<br>

## FAQ

<details>
<summary><strong>How do I get an appstate.json?</strong></summary>
<br>
Use the <em>C3C FBState</em> browser extension to export your Facebook session cookies as JSON. Log in to Facebook in your browser first, then export.
</details>

<details>
<summary><strong>Will this get my account banned?</strong></summary>
<br>
Any third-party Messenger automation carries some risk. FCA-SIFU reduces it through identity rotation, adaptive rate-limiting, and warmup mode — but no tool can eliminate it entirely. Use a secondary account when possible.
</details>

<details>
<summary><strong>My session dies after a few hours. Why?</strong></summary>
<br>
Facebook cookies expire. The Revive manager handles this automatically when <code>autoReLogin: true</code> (default). If it still fails, export a fresh appstate — your cookies may have been invalidated server-side.
</details>

<details>
<summary><strong>Does it support TypeScript?</strong></summary>
<br>
Yes. Type definitions are bundled at <code>fca-sifu/fca-sifu/datastore/models/types/index.d.ts</code> and resolve automatically when you install the package.
</details>

<details>
<summary><strong>How do I run multiple accounts?</strong></summary>
<br>

```js
const [api1, api2] = await Promise.all([
    login({ appState: state1 }),
    login({ appState: state2 }),
]);
```

Each call returns an independent API instance with its own session.
</details>

<br>

## Disclaimer

This project is not affiliated with, endorsed by, or sponsored by Meta Platforms. Use at your own risk and in accordance with Facebook's [Terms of Service](https://www.facebook.com/legal/terms). The maintainers accept no liability for account actions taken by Meta.

<br>

## License

[MIT](LICENSE) © 2026 **SIFAT**

<br>

---

<div align="center">

Built by [SIFAT](https://github.com/myb-sifu) · [GitHub](https://github.com/myb-sifu/fca-sifu) · [npm](https://www.npmjs.com/package/fca-sifu)

If FCA-SIFU saved you time, a ⭐ on GitHub goes a long way.

</div>
