Skip to content

Latest commit

Β 

History

83 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Floppa FCA Banner



Floppa FCA Logo

@floppa/fca β€” Priyansh Facebook Chat API Engine

High-Performance Facebook Chat API Engine ported from Priyansh Rajput (fca-priyansh) with Native GoatBot v2 & Floppa-Chatbot Resilience
Priyansh Core Logic β€’ 24/7 Session Stability β€’ Adaptive Rate Limiter β€’ Anti-Suspension Warmup β€’ MQTT Realtime

Version Priyansh Core License Engine GoatBot v2 Core Creator Port Author Developer Contact


πŸ“– Overview

This repository ports and modernizes the complete Priyansh Facebook Chat API (fca-priyansh) core logic created by Priyansh Rajput, combining it with Gtajisan's (Farhan Muh Tasim / frnAlt) Floppa native resilience architecture for GoatBot v2 and Floppa-Chatbot.

Facebook now has an official API for chat bots here.

This API is the only way to automate chat functionalities on a personal Facebook user account. We do this by emulating the browser. This means doing the exact same GET/POST requests and tricking Facebook into thinking we're accessing the website normally. Because we're doing it this way, this API does not work with an OAuth bot token but requires the credentials or appState cookies of a Facebook account.

Disclaimer: We are not responsible if your account gets banned for spammy activities such as sending lots of messages to people you don't know, sending messages very quickly, sending spammy looking URLs, logging in and out very quickly... Be responsible Facebook citizens and enable warmup protection.

See below for projects using this API.


πŸ“‘ Table of Contents


🌟 Priyansh FCA Core Logic & Hybrid Integration

@floppa/fca keeps all of Priyansh's original Facebook Chat API code stuff completely intact while extending it with enterprise-grade resilience:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                              @floppa/fca                               β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚      Priyansh FCA Core Logic     β”‚    Native Resilience & Stability    β”‚
β”‚    (Created by Priyansh Rajput)  β”‚      (Engineered by Gtajisan)       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β€’ High-Speed MQTT Delta v1/v2    β”‚ β€’ SessionStabilityManager (Tokens)  β”‚
β”‚ β€’ Main.js Login Engine & 2FA     β”‚ β€’ AdaptiveRateLimiter (Buckets)     β”‚
β”‚ β€’ Broadcast & Multi-Language     β”‚ β€’ ResilienceManager (Circuit Breakerβ”‚
β”‚ β€’ Checkpoint Bypass Routines     β”‚ β€’ BotHealthMonitor (0-100 Score)    β”‚
β”‚ β€’ Extra Database & Balancer      β”‚ β€’ Lifecycle & Socket Pooling        β”‚
β”‚ β€’ Horizon_Database Storage       β”‚ β€’ Anti-Suspension Warmup Curves     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                   GoatBot v2 Universal Adapter Layer                   β”‚
β”‚ β€’ parseUniversalCookies (AppState, Netscape, Header strings)           β”‚
β”‚ β€’ globalAntiSuspension (Warmup heuristics & protection)               β”‚
β”‚ β€’ Domain-Based Modular Facades (Messages, Threads, Users, Account)     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

What Priyansh Core Modules Are Preserved:

  • Main.js: Priyansh's authentication state machine, 2FA OTP prompt resolver (Otp_code), credential encryption via Extra/Security, checkpoint bypass handlers (CheckPointBypass 956), and fast config loader (PriyanshFca.json).
  • src/listenMqtt.js & src/listenMqttV1.js: High-performance real-time MQTT Delta protocol parsers, decoding delta messages, delivery receipts, read markers, reactions, unsends, and typing events.
  • utils.js: Core HTTP request builder, streaming attachments, proxy management (setProxy), form-data builders, and cookie jar handling.
  • Language/: Multi-language localization engine supporting English (en), Vietnamese (vi), and customizable notification templates.
  • Extra/:
    • Extra/Balancer.js: Traffic balancing and connection load distribution.
    • Extra/Bypass/: 956 checkpoint challenge resolution routines.
    • Extra/Database/: SQLite persistent storage with automatic JSON fallback for Node 24 compatibility.
    • Extra/ExtraScreenShot.js: Programmatic screenshot capture helper.
    • Extra/ExtraUptimeRobot.js: Integrated uptime keep-alive pinger.
  • Horizon_Database/: Thread and user data directory used by ChernobyL data engine.
  • Complete FB Methods: Full implementations of sendMessage, changeNickname, changeThreadColor, changeThreadEmoji, changeGroupImage, deleteMessage, unsendMessage, addUserToGroup, removeUserFromGroup, createPoll, getUserInfo, and getThreadInfo.

πŸ›‘οΈ How We Ported Priyansh's FCA to Modern Bot Logic

To make Priyansh's core engine seamlessly drive modern bot frameworks like GoatBot v2, Floppa-Chatbot, and Baka-Chan, the following modern systems were integrated:

  1. Universal Cookie Normalizer (parseUniversalCookies):
    Allows the bot to log in using standard JSON AppState arrays, browser Netscape tab-separated text (cookies.txt), or raw Cookie header strings without format conversion errors.
  2. Anti-Suspension Warmup System (globalAntiSuspension):
    Implements an intelligent warmup curve upon bot startup. Outgoing message velocity is gently accelerated to avoid sudden velocity spikes that trigger Facebook security checkpoints.
  3. Session Stability Manager (SessionStabilityManager):
    Continuously validates session health in the background and proactively refreshes fb_dtsg tokens before they expire.
  4. Adaptive Rate Limiter (AdaptiveRateLimiter):
    Features separate token buckets for messages (60/min), threads (30/min), users (40/min), media (20/min), and global actions (150/min), automatically backing off when Facebook returns warning headers.
  5. Circuit Breakers & Self-Healing (ResilienceManager):
    3-state circuit breakers (CLOSED, OPEN, HALF_OPEN) prevent bot freezes during transient Facebook outages.
  6. Node 24 Compatibility:
    Added native crypto fallbacks for legacy aes-js, UUID v4 compatibility hooks, and automatic local node_modules path resolution.

βš–οΈ Architecture & Core Logic Differences

Below is an in-depth technical comparison highlighting the evolutionary differences between Classic Legacy FCA, Priyansh FCA Core, and our Floppa @floppa/fca engine:

Architectural Dimension Classic Legacy FCA (fca-unofficial) Priyansh FCA Core (fca-priyansh) Floppa Hybrid Engine (@floppa/fca)
Facebook Protocol Legacy Sync HTTP / Polling High-Speed MQTT Delta v1/v2 Enhanced MQTT Delta v1/v2 + Circuit Breakers
Authentication Logic Basic credentials / raw AppState 2FA OTP (Otp_code) + Encrypted state + 956 bypass Priyansh 2FA + parseUniversalCookies (AppState, Netscape, Header strings)
Anti-Suspension & Warmup ❌ None (Rapid account checkpoint) ⚠️ Manual delays βœ… globalAntiSuspension (Gradual startup warmup heuristics)
Rate Limiting Engine ❌ None (Uncontrolled bursts) ⚠️ Basic static timeout βœ… AdaptiveRateLimiter (6 sliding-window token buckets + dynamic penalty scaling)
Session Longevity ❌ Expires after hours (fb_dtsg loss) ⚠️ Requires full re-login βœ… SessionStabilityManager (Automated background token renewal)
Database & Persistence ❌ None / plaintext JSON βœ… SQLite (Extra/Database) + Horizon_Database βœ… Resilient SQLite + auto JSON fallback for zero-crash Node 24 support
Bot Framework Integration Mirai only Priyansh-Bot & customized Mirai 🐐 100% GoatBot v2, Floppa-Chatbot, Baka-Chan, & Mirai drop-in (./fca)
API Architecture Flat monolithic callback Flat callback + basic promises Dual-mode: Flat API + Grouped Domain Facades + createMessengerBot
Runtime & Dependencies ❌ Crashes on Node 20+ ⚠️ Native compile errors on Node 24 βœ… Modern Node 24 support with native crypto & auto-resolving local modules
Distribution Method Broken public npm GitHub fork (Porter-union-rom-updates/Fca) πŸ”’ Independent GitHub engine (frnAlt/fca) & local drop-in clone

πŸ” Deep Dive: Logic Improvements in Floppa's Port

1. Credential Ingestion Logic (Universal Cookie Parser)

  • Priyansh Logic: Required an exact JSON array format or email/password. Any formatting deviation (such as browser-exported Netscape cookies.txt or raw semicolon-separated headers) threw a parsing exception.
  • Floppa Port: Injects parseUniversalCookies. It dynamically inspects the input type, sanitizes attribute keys (domain, expires, samesite), strips Netscape #HttpOnly_ prefixes, and deduplicates cookie pairs on the fly.

2. Outgoing Traffic Regulation (Adaptive Rate Limiter)

  • Priyansh Logic: Relied on static autoRestartMinutes and bot-level sleep calls.
  • Floppa Port: Implements AdaptiveRateLimiter. Every outbound request (sendMessage, changeNickname, setReaction, uploadAttachment) is routed through independent rate limit buckets with sliding-window accounting. If Facebook responds with temporary rate limit headers, the limiter automatically scales down request velocity without crashing the bot.

3. Error Resilience & Self-Healing (Circuit Breakers)

  • Priyansh Logic: Network exceptions or Facebook API timeouts were caught via standard try/catch callbacks, which could cause socket backlogs and memory leaks during extended outages.
  • Floppa Port: Uses ResilienceManager. Endpoints transition between CLOSED, OPEN, and HALF_OPEN states, failing fast when Facebook is unresponsive and recovering automatically when connectivity returns.

4. Zero-Config GoatBot v2 Integration

  • Priyansh Logic: Required custom bot bootstrap scripts to initialize global.Fca.
  • Floppa Port: Seamlessly auto-initializes global.Fca when required, provides api.getCurrentUserID(), api.stopListening(), and api.getHealthStatus(), and auto-registers with GoatBot v2's ./fca local loader.

🐐 GoatBot v2 & Floppa-Chatbot Compatibility

@floppa/fca is 100% compatible with GoatBot v2 and can be used immediately using any of these methods:

Method 1: Local Engine Drop-In (Zero Configuration)

Clone directly into your bot root as ./fca:

git clone https://github.com/frnAlt/fca.git ./fca

GoatBot v2's login loader (bot/login/login.js) automatically detects ./fca and loads it as the native engine:

const localFca = defaultRequire(path.join(process.cwd(), "fca"));

Method 2: Bot Configuration (config.json)

In your bot's config.json:

{
  "optionsFca": {
    "fca": "@floppa/fca"
  }
}

Method 3: Direct Require

const login = require("@floppa/fca");

login({ appState }, global.GoatBot.config.optionsFca, async (err, api) => {
  if (err) return console.error("Login failed:", err);
  global.GoatBot.fcaApi = api;
});

πŸ“¦ Installation

Direct from GitHub (Public HTTPS β€” No NPM Account Needed)

# Standard npm
npm install github:frnAlt/fca

# Or with HTTPS URL
npm install https://github.com/frnAlt/fca.git

Add to package.json:

{
  "dependencies": {
    "@floppa/fca": "github:frnAlt/fca"
  }
}

Then run:

npm install

2. Local Drop-In Engine (No npm Needed β€” Recommended for GoatBot v2)

If you want a portable, standalone local engine without managing npm dependencies:

# In your bot root directory:
git clone https://github.com/frnAlt/fca.git ./fca

GoatBot v2 and Floppa-Chatbot will automatically detect and prioritize ./fca as the native local engine with zero configuration required!

πŸ”’ Independent GitHub Distribution: This library is maintained and distributed exclusively via GitHub (frnAlt/fca) and direct local drop-in. It is not published on the public npm registry to ensure complete stability, security, and full autonomy over your bot infrastructure.


πŸš€ Example Usage & Quick Start

Basic Echo Bot (Callback Style)

const login = require("@floppa/fca");

// Login with Facebook credentials or AppState
login({ email: "FB_EMAIL", password: "FB_PASSWORD" }, (err, api) => {
  if (err) return console.error(err);

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

  api.listenMqtt((err, message) => {
    if (err) return console.error("MQTT Error:", err);
    if (message.type === "message") {
      api.sendMessage(message.body, message.threadID);
    }
  });
});

Modern Async / Await Style

const { login } = require("@floppa/fca");

async function main() {
  const api = await login(
    { appState: require("./appstate.json") },
    { listenEvents: true, autoReconnect: true }
  );

  console.log(`Bot logged in! UID: ${api.getCurrentUserID()}`);

  api.listenMqtt(async (err, event) => {
    if (err) return console.error(err);
    if (event.type === "message" && event.body === "ping") {
      await api.sendMessage("pong! πŸ“", event.threadID);
    }
  });
}

main();

πŸ’¬ Main Functionality

Sending a Message

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

Various types of messages can be sent:

  • Regular Text: Set body to your message string.
  • Sticker: Set sticker to the desired sticker ID.
  • File or Image: Set attachment to a readable stream or array of streams.
  • URL: Set url to a web link.
  • Emoji: Set emoji to the emoji character and emojiSize (small, medium, large).

Tip: To find your bot account's ID, check api.getCurrentUserID() or the c_user cookie.

Example: Basic Message

const login = require("@floppa/fca");

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

  var targetID = "100000000000000";
  api.sendMessage("Hey from Floppa FCA!", targetID);
});

Example: File & Media Upload

const fs = require("fs");
const login = require("@floppa/fca");

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

  var targetID = "100000000000000";
  var msg = {
    body: "Check out this image!",
    attachment: fs.createReadStream(__dirname + "/image.jpg")
  };
  api.sendMessage(msg, targetID);
});

πŸ’Ύ Saving Session (appState)

To avoid logging in with passwords every time, export and save your session cookies:

const fs = require("fs");
const login = require("@floppa/fca");

login({ email: "FB_EMAIL", password: "FB_PASSWORD" }, (err, api) => {
  if (err) return console.error(err);

  fs.writeFileSync("appstate.json", JSON.stringify(api.getAppState(), null, 2));
  console.log("AppState saved successfully!");
});

🎧 Listening to a Chat (listenMqtt)

api.listenMqtt receives messages, typing indicators, reactions, and thread events:

const fs = require("fs");
const login = require("@floppa/fca");

login({ appState: JSON.parse(fs.readFileSync("appstate.json", "utf8")) }, (err, api) => {
  if (err) return console.error(err);

  api.setOptions({ listenEvents: true });

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

    api.markAsRead(event.threadID, () => {});

    switch (event.type) {
      case "message":
        if (event.body === "/stop") {
          api.sendMessage("Goodbye! πŸ‘‹", event.threadID);
          return stopListening();
        }
        api.sendMessage("Echo: " + event.body, event.threadID);
        break;
      case "event":
        console.log("Thread event:", event);
        break;
    }
  });
});

πŸ”‘ Authentication & Universal Cookie Normalizer

@floppa/fca provides universal credential parsing through parseUniversalCookies:

Strategy Description
JSON AppState Array of cookie objects ([ { key, value, domain, path, ... } ]). Recommended for 24/7 uptime.
Raw Cookie String Semicolon-delimited header string: "c_user=1000...; xs=2%3A...; datr=...;"
Netscape Format Browser tab-delimited text (cookies.txt)
Email & Password Standard web login with automated 2FA (TOTP secret key supported via twofactor)

🧩 Modern API Styles

1. Flat API (Classic Priyansh Compatibility)

api.sendMessage("Hello!", threadID);
api.getThreadInfo(threadID, (err, info) => { ... });
api.setMessageReaction("❀️", messageID);

2. Grouped Domain Client Facade

Organized by functional domain for modern TypeScript / ES codebases:

const { createFcaClient } = require("@floppa/fca");

const client = createFcaClient(api);

await client.messages.send("Hello world!", threadID);
await client.threads.getInfo(threadID);
await client.users.getInfo(userID);

Available namespaces:

  • client.messages
  • client.threads
  • client.users
  • client.account
  • client.realtime
  • client.http
  • client.scheduler

πŸ€– MessengerBot (Event-Driven Engine)

const { createMessengerBot } = require("@floppa/fca");

async function start() {
  const bot = await createMessengerBot(
    { appState: require("./appstate.json") },
    {
      listenEvents: true,
      stopOnSignals: true,
      commandPrefix: "!"
    }
  );

  bot.on("error", (err) => console.error("Bot error:", err));

  bot.on("messageCreate", (event) => {
    console.log(`[${event.threadID}] ${event.body}`);
  });

  bot.command("ping", async (ctx) => {
    await ctx.replyAsync("pong! πŸ“");
  });

  bot.hears(/hello/i, async (ctx) => {
    await ctx.replyAsync("Hello there!");
  });
}

start();

πŸ› οΈ Configuration

fca-config.json

{
  "autoUpdate": false,
  "checkUpdate": {
    "enabled": false,
    "packageName": "@floppa/fca",
    "notifyIfCurrent": false
  },
  "mqtt": {
    "enabled": true,
    "reconnectInterval": 3600
  },
  "autoLogin": true,
  "antiSuspension": {
    "enabled": true,
    "warmupOnStart": true
  },
  "healthMonitor": {
    "enabled": true,
    "logIntervalMs": 3600000
  }
}

PriyanshFca.json

Priyansh core options can also be customized via PriyanshFca.json:

{
  "Language": "en",
  "MainColor": "#9900FF",
  "MainName": "[ FCA-FLOPPA ]",
  "DevMode": false,
  "Login2Fa": false,
  "AutoLogin": false,
  "EncryptFeature": true,
  "ResetDataLogin": false
}

πŸ§ͺ Testing Your Bots

If you want to test your bots without risking personal accounts, use Facebook Whitehat Accounts.


❓ Frequently Asked Questions (FAQs)

  1. How do I run tests?
    Run npm test or node test/fca.test.cjs from the repository root.

  2. Why doesn't sendMessage always work when logged in as a page?
    Facebook pages cannot initiate conversations with users directly; this is Facebook policy to prevent page spam.

  3. What do I do when login doesn't work?
    First verify you can log into Facebook via a web browser. If 2FA is enabled, provide your TOTP code or secret key in twofactor. For best results, use appState.

  4. How can I avoid logging in every time?
    Use api.getAppState() to export cookies and save to appstate.json, then pass { appState: require("./appstate.json") } into login().

  5. Do you support sending messages as a page?
    Yes, specify { pageID: "100000000000000" } in the login options.

  6. How can I silence logging messages?
    Call api.setOptions({ logLevel: "silent" }).


🌐 Projects Using This API

  • Floppa-Chatbot β€” Modern Facebook Messenger bot powered by Floppa Engine.
  • GoatBot v2 β€” GoatBot v2 platform integration.
  • Priyansh-Bot β€” Facebook Messenger Bot made by Priyansh Rajput.
  • c3c β€” Customizable plugin-based chatbot supporting Facebook & Discord.

πŸ‘¨β€πŸ’» Author & Developer Info

Role Details
Original FCA Creator Priyansh Rajput (Facebook Profile)
Port Author & Lead Maintainer Gtajisan (Farhan Muh Tasim)
GitHub Account @frnAlt
Repository frnAlt/fca
Direct Contact / Email sultana01537118@gmail.com
Primary Bot Framework Floppa-Chatbot

πŸ‘₯ Contributors & Credits


πŸ“„ License

This project is licensed under the Apache License, Version 2.0.

Priyansh Facebook Chat API Core Logic Β© Priyansh Rajput. Floppa Native Engine & GoatBot v2 Port Β© Gtajisan (frnAlt).

About

Priyansh Facebook Chat API Engine

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages