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
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.
- π Priyansh FCA Core Logic & Hybrid Integration
- π‘οΈ How We Ported Priyansh's FCA to Modern Bot Logic
- βοΈ Architecture & Core Logic Differences
- π GoatBot v2 & Floppa-Chatbot Compatibility
- π¦ Installation
- π Example Usage & Quick Start
- π¬ Main Functionality (Sending Messages, Attachments & Stickers)
- πΎ Saving Session (
appState) - π§ Listening to a Chat (
listenMqtt) - π Authentication & Universal Cookie Normalizer
- π§© Modern API Styles
- π€ MessengerBot (Event-Driven Engine)
- π οΈ Configuration (
fca-config.json&PriyanshFca.json) - π§ͺ Testing Your Bots
- β Frequently Asked Questions (FAQs)
- π Projects Using This API
- π¨βπ» Author & Developer Info
- π₯ Contributors & Credits
- π License
@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) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Main.js: Priyansh's authentication state machine, 2FA OTP prompt resolver (Otp_code), credential encryption viaExtra/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, andgetThreadInfo.
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:
- Universal Cookie Normalizer (
parseUniversalCookies):
Allows the bot to log in using standard JSON AppState arrays, browser Netscape tab-separated text (cookies.txt), or rawCookieheader strings without format conversion errors. - 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. - Session Stability Manager (
SessionStabilityManager):
Continuously validates session health in the background and proactively refreshesfb_dtsgtokens before they expire. - 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. - Circuit Breakers & Self-Healing (
ResilienceManager):
3-state circuit breakers (CLOSED,OPEN,HALF_OPEN) prevent bot freezes during transient Facebook outages. - Node 24 Compatibility:
Added native crypto fallbacks for legacyaes-js, UUID v4 compatibility hooks, and automatic localnode_modulespath resolution.
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) | β
globalAntiSuspension (Gradual startup warmup heuristics) |
|
| Rate Limiting Engine | β None (Uncontrolled bursts) | β
AdaptiveRateLimiter (6 sliding-window token buckets + dynamic penalty scaling) |
|
| Session Longevity | β Expires after hours (fb_dtsg loss) |
β
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+ | β 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 |
- Priyansh Logic: Required an exact JSON array format or email/password. Any formatting deviation (such as browser-exported Netscape
cookies.txtor 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.
- Priyansh Logic: Relied on static
autoRestartMinutesand 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.
- Priyansh Logic: Network exceptions or Facebook API timeouts were caught via standard
try/catchcallbacks, which could cause socket backlogs and memory leaks during extended outages. - Floppa Port: Uses
ResilienceManager. Endpoints transition betweenCLOSED,OPEN, andHALF_OPENstates, failing fast when Facebook is unresponsive and recovering automatically when connectivity returns.
- Priyansh Logic: Required custom bot bootstrap scripts to initialize
global.Fca. - Floppa Port: Seamlessly auto-initializes
global.Fcawhen required, providesapi.getCurrentUserID(),api.stopListening(), andapi.getHealthStatus(), and auto-registers with GoatBot v2's./fcalocal loader.
@floppa/fca is 100% compatible with GoatBot v2 and can be used immediately using any of these methods:
Clone directly into your bot root as ./fca:
git clone https://github.com/frnAlt/fca.git ./fcaGoatBot 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"));In your bot's config.json:
{
"optionsFca": {
"fca": "@floppa/fca"
}
}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;
});# Standard npm
npm install github:frnAlt/fca
# Or with HTTPS URL
npm install https://github.com/frnAlt/fca.git{
"dependencies": {
"@floppa/fca": "github:frnAlt/fca"
}
}Then run:
npm installIf you want a portable, standalone local engine without managing npm dependencies:
# In your bot root directory:
git clone https://github.com/frnAlt/fca.git ./fcaGoatBot 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.
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);
}
});
});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();api.sendMessage(message, threadID[, callback][, messageID])Various types of messages can be sent:
- Regular Text: Set
bodyto your message string. - Sticker: Set
stickerto the desired sticker ID. - File or Image: Set
attachmentto a readable stream or array of streams. - URL: Set
urlto a web link. - Emoji: Set
emojito the emoji character andemojiSize(small,medium,large).
Tip: To find your bot account's ID, check
api.getCurrentUserID()or thec_usercookie.
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);
});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);
});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!");
});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;
}
});
});@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) |
api.sendMessage("Hello!", threadID);
api.getThreadInfo(threadID, (err, info) => { ... });
api.setMessageReaction("β€οΈ", messageID);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.messagesclient.threadsclient.usersclient.accountclient.realtimeclient.httpclient.scheduler
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();{
"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
}
}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
}If you want to test your bots without risking personal accounts, use Facebook Whitehat Accounts.
-
How do I run tests?
Runnpm testornode test/fca.test.cjsfrom the repository root. -
Why doesn't
sendMessagealways work when logged in as a page?
Facebook pages cannot initiate conversations with users directly; this is Facebook policy to prevent page spam. -
What do I do when
logindoesn't work?
First verify you can log into Facebook via a web browser. If 2FA is enabled, provide your TOTP code or secret key intwofactor. For best results, useappState. -
How can I avoid logging in every time?
Useapi.getAppState()to export cookies and save toappstate.json, then pass{ appState: require("./appstate.json") }intologin(). -
Do you support sending messages as a page?
Yes, specify{ pageID: "100000000000000" }in the login options. -
How can I silence logging messages?
Callapi.setOptions({ logLevel: "silent" }).
- 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.
| 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 |
- Priyansh Rajput β Original author and creator of the Priyansh Facebook Chat API (
fca-priyansh) core logic. - Gtajisan (Farhan Muh Tasim / frnAlt) β Lead Developer of
@floppa/fca, GoatBot v2 adapter layer, universal cookies, and maintainer of the Floppa Ecosystem. - NeoKEX (lazyneoaz) β Creator of Metachat & Native Resilience architecture.
- PhαΊ‘m Minh Δα»ng (DongDev) β Foundational contributions, security patches, and optimizations.
- XNIL6X 404 β Contributor & maintainer.
- GoatBot v2 Community β Facebook Chat API open-source developers worldwide.
This project is licensed under the Apache License, Version 2.0.