JSPM

@johnlester-0369/fca-unofficial

3.0.33
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 252
  • Score
    100M100P100Q65576F
  • License MIT

Unofficial Facebook Chat API for Node.js - Interact with Facebook Messenger programmatically

Package Exports

  • @johnlester-0369/fca-unofficial

Readme

๐Ÿ’ฌ @dongdev/fca-unofficial

Unofficial Facebook Chat API for Node.js - Interact with Facebook Messenger programmatically

Features โ€ข Installation โ€ข Quick Start โ€ข Documentation โ€ข Support


๐Ÿ“‹ Table of Contents


โš ๏ธ Disclaimer & Support Policy

READ THIS BEFORE USING OR OPENING AN ISSUE.

This repository is provided "AS IS" and is entirely open-source. By using this project, you explicitly agree to the following terms:

  1. Use at your own risk: We are NOT responsible if your account gets banned for spammy activities (sending messages too fast, unsolicited mass messaging, suspicious URLs, or rapid login/logout).
  2. No Spoon-Feeding: This is a tool for developers. If you cannot read source code, navigate directories, or use basic search tools (Ctrl + Shift + F), you should not be using this library.
  3. No Free Programming Lessons: I maintain the core updates and security patches for the community for free. I do not provide free JavaScript/TypeScript tutorials, nor will I tell you exactly which line of code to edit for your specific bot.
  4. Custom Features = Paid Service: Brainpower and time are not free. If you need me to write custom logic, reverse-engineer specific endpoints, or provide 1-on-1 support for your personal project, that is a paid service.

If you don't like this policy, feel free to fork the repository and maintain it yourself.

Recommendations to avoid bans:

  • Use Firefox or the fca.dongdev.id.vn flow to reduce logout issues (especially on iOS).
  • Prefer AppState over email/password when possible.
  • Use strict rate limiting in your bots.

โšก Why this fork?

Unlike other outdated forks, @dongdev/fca-unofficial is built with a focus on real-world practicality and performance:

  • Performance First: Stripped out legacy, redundant code that causes technical debt.
  • Modernized Architecture: Adapted to the latest Facebook backend structure.
  • Clean Logic: No messy wrappers. The codebase is straightforward and easy to navigate if you actually open the files.

โœจ Features

  • โœ… Full Messenger API - Send messages, files, stickers, and more
  • โœ… Real-time Events - Listen to messages, reactions, and thread events
  • โœ… User Account Support - Works with personal Facebook accounts (not just Pages)
  • โœ… AppState Support - Save login state to avoid re-authentication
  • โœ… MQTT Protocol - Real-time messaging via MQTT
  • โœ… TypeScript Support - Includes TypeScript definitions
  • โœ… Active Development - Regularly updated and maintained

๐Ÿ” Introduction

Facebook provides an official API for chat bots, but it's only available for Facebook Pages.

@dongdev/fca-unofficial is the API that allows you to automate chat functionalities on a user account by emulating the browser. This means:

  • ๐Ÿ”„ Making the exact same GET/POST requests as a browser
  • ๐Ÿ” Does not work with auth tokens
  • ๐Ÿ“ Requires Facebook account credentials (email/password) or AppState

Perfect for:

  • ๐Ÿค– Building chatbots
  • ๐Ÿ“ฑ Automating message responses
  • ๐Ÿ”” Creating notification systems
  • ๐ŸŽฎ Building interactive games
  • ๐Ÿ“Š Analytics and monitoring

๐Ÿ“ฆ Installation

npm install @dongdev/fca-unofficial@latest

Requirements:

  • Node.js >= 12.0.0
  • Active Facebook account

๐Ÿš€ Quick Start

1๏ธโƒฃ Login and Simple Echo Bot

const login = require("@dongdev/fca-unofficial");

login({ appState: [] }, (err, api) => {
  if (err) return console.error(err);

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

    // Echo back the received message
    if (event.type === "message") {
      api.sendMessage(event.body, event.threadID);
    }
  });
});

2๏ธโƒฃ Send Text Message

const login = require("@dongdev/fca-unofficial");

login({ appState: [] }, (err, api) => {
  if (err) {
    console.error("Login Error:", err);
    return;
  }

  const yourID = "000000000000000"; // Replace with actual Facebook ID
  const msg = "Hey! ๐Ÿ‘‹";

  api.sendMessage(msg, yourID, (err) => {
    if (err) console.error("Message Sending Error:", err);
    else console.log("โœ… Message sent successfully!");
  });
});

๐Ÿ’ก Tip: To find your Facebook ID, look inside the cookies under the name c_user

3๏ธโƒฃ Send File/Image

const login = require("@dongdev/fca-unofficial");
const fs = require("fs");

login({ appState: [] }, (err, api) => {
  if (err) {
    console.error("Login Error:", err);
    return;
  }

  const yourID = "000000000000000";
  const imagePath = __dirname + "/image.jpg";

  // Check if file exists
  if (!fs.existsSync(imagePath)) {
    console.error("โŒ Error: Image file not found!");
    return;
  }

  const msg = {
    body: "Check out this image! ๐Ÿ“ท",
    attachment: fs.createReadStream(imagePath),
  };

  api.sendMessage(msg, yourID, (err) => {
    if (err) console.error("Message Sending Error:", err);
    else console.log("โœ… Image sent successfully!");
  });
});

๐Ÿ“ Message Types

Type Usage Example
Regular text { body: "message text" } { body: "Hello!" }
Sticker { sticker: "sticker_id" } { sticker: "369239263222822" }
File/Image { attachment: fs.createReadStream(path) } { attachment: fs.createReadStream("image.jpg") }
URL { url: "https://example.com" } { url: "https://github.com" }
Large emoji { emoji: "๐Ÿ‘", emojiSize: "large" } { emoji: "๐Ÿ‘", emojiSize: "large" }

๐Ÿ“Œ Note: A message can only be a regular message (which can be empty) and optionally one of the following: a sticker, an attachment, or a URL.

Emoji sizes: small | medium | large


๐Ÿ’พ AppState Management

Save AppState

Save your login session to avoid re-authentication:

const fs = require("fs");
const login = require("@dongdev/fca-unofficial");

const credentials = { email: "YOUR_EMAIL", password: "YOUR_PASSWORD" }; // Or use existing appState

login(credentials, (err, api) => {
  if (err) {
    console.error("Login Error:", err);
    return;
  }

  try {
    const appState = JSON.stringify(api.getAppState(), null, 2);
    fs.writeFileSync("appstate.json", appState);
    console.log("โœ… AppState saved successfully!");
  } catch (error) {
    console.error("โŒ Error saving AppState:", error);
  }
});

Use Saved AppState

Load your saved AppState for faster login:

const fs = require("fs");
const login = require("@dongdev/fca-unofficial");

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

    console.log("โœ… Logged in successfully!");
    // Your code here
  },
);

๐Ÿ”„ Auto Login

When your session (AppState) expires, the library can automatically re-login using credentials from a config file, so your bot can keep running without manual intervention.

  1. Create fca-config.json in your project root (same folder as where you run node):
{
  "autoLogin": true,
  "apiServer": "https://minhdong.site",
  "apiKey": "",
  "credentials": {
    "email": "YOUR_EMAIL_OR_PHONE",
    "password": "YOUR_PASSWORD",
    "twofactor": ""
  }
}
  1. Log in with AppState as usual. If the session later expires (e.g. Facebook invalidates cookies), the library will use credentials (and optionally the external apiServer) to log in again and retry the request.
  • Set autoLogin to false to disable automatic re-login.
  • twofactor: Base32 secret for 2FA (not the 6-digit code). Leave empty if you do not use 2FA.
  • apiServer / apiKey: Optional; used for external iOS-style login. Default server is https://minhdong.site.

Keep fca-config.json out of version control (add it to .gitignore) since it contains credentials.


๐Ÿ” Security, Trust & Supply Chain

  • Published via GitHub Actions using npm publish --provenance, so the tarball on npm can be cryptographically tied back to this repo.
  • Core runtime code in module/ and src/ is readable JavaScript with no obfuscated logic.
  • Legacy forks (such as Horizon) are kept only for reference and are not shipped in the npm package.
  • No telemetry or hidden network calls:
    • All HTTP traffic is implemented in src/utils/request.js and module/loginHelper.js.
    • External URLs (such as apiServer or proxies) are fully userโ€‘configurable.
  • The npm publish account uses 2FA and dedicated automation tokens.

See SECURITY.md for more details.


๐Ÿ‘‚ Listening for Messages

Echo Bot with Stop Command

const fs = require("fs");
const login = require("@dongdev/fca-unofficial");

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

    // Enable listening to events (join/leave, title change, etc.)
    api.setOptions({ listenEvents: true });

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

      // Mark as read
      api.markAsRead(event.threadID, (err) => {
        if (err) console.error("Mark as read error:", err);
      });

      // Handle different event types
      switch (event.type) {
        case "message":
          if (event.body && event.body.trim().toLowerCase() === "/stop") {
            api.sendMessage("Goodbyeโ€ฆ ๐Ÿ‘‹", event.threadID);
            stopListening();
            return;
          }
          api.sendMessage(`๐Ÿค– BOT: ${event.body}`, event.threadID);
          break;

        case "event":
          console.log("๐Ÿ“ข Event Received:", event);
          break;
      }
    });
  },
);

Listen Options

Configure listening behavior:

api.setOptions({
  listenEvents: true, // Receive events (join/leave, rename, etc.)
  selfListen: true, // Receive messages from yourself
  logLevel: "silent", // Disable logs (silent/error/warn/info/verbose)
});

๐ŸŽฏ API Quick Reference

(For full details, please read the source code or DOCS.md)

๐Ÿ“จ Messaging

sendMessage, sendTypingIndicator, getMessage, editMessage, deleteMessage, unsendMessage, setMessageReaction, forwardAttachment, uploadAttachment, createPoll

๐Ÿ“ฌ Read Receipt & Delivery

markAsRead, markAsReadAll, markAsDelivered, markAsSeen

๐Ÿ‘ฅ Thread Management

getThreadInfo, getThreadList, getThreadHistory, deleteThread, changeThreadColor, changeThreadEmoji, changeGroupImage, setTitle, changeNickname

๐Ÿ‘ค User & Group Management

getUserInfo, getFriendsList, getCurrentUserID, createNewGroup, addUserToGroup, removeUserFromGroup, changeAdminStatus

โš™๏ธ Thread Settings & Actions

muteThread, changeArchivedStatus, changeBlockedStatus, handleMessageRequest, changeAvatar, changeBio, handleFriendRequest, unfriend

๐Ÿ” Auth & Listening

logout, getAppState, setOptions, listenMqtt


๐ŸŽ› Event Hooks & Remote Control (Advanced)

Starting from 3.x, the API instance also behaves like an EventEmitter for lifecycle and remoteโ€‘control events:

  • Lifecycle events:
    • sessionExpired โ€” login session is no longer valid, autoโ€‘login will be attempted (if configured).
    • autoLoginSuccess โ€” autoโ€‘login succeeded and the failed request will be retried.
    • autoLoginFailed โ€” autoโ€‘login could not recover the session.
    • checkpoint โ€” generic checkpoint, with subtype in { type: "282" | "956" | "scraping_warning" }.
    • checkpoint_282, checkpoint_956 โ€” more specific checkpoint events.
    • loginBlocked โ€” Facebook actively blocked the login (error 1357001).
    • rateLimit โ€” HTTP 429 detected on Facebook endpoints.
    • networkError โ€” networkโ€‘level failure (timeouts, DNS, connection reset, etc.).

Usage:

api.on("checkpoint_956", ({ res }) => {
  console.error("Checkpoint 956 detected, manual action required.");
});

api.on("rateLimit", ({ url, method }) => {
  console.warn("Rate limit hit on", method, url);
});
  • Remote control events (when remoteControl.enabled is true in fca-config.json):
    • remoteConnected / remoteDisconnected
    • remoteStop
    • remoteBroadcast
    • remoteMessage (raw messages from your WS backend)

See examples/remote-control.js for a concrete integration example.


๐ŸŒ Proxy Configuration & Broadcast Helper

  • Proxy support:
    • You can pass a proxy perโ€‘login:
login({ appState }, (err, api) => {
  if (err) return console.error(err);
  api.setOptions({ proxy: "http://user:pass@host:port" });
});
  • Or define a default in fca-config.json:
{
  "proxy": "http://user:pass@host:port"
}
  • All HTTP calls go through this proxy using https-proxy-agent.

  • Broadcast helper (optional util):

    • Not part of the public API surface on purpose (to avoid encouraging spam).
    • You can use it manually:
const broadcast = require("@dongdev/fca-unofficial/src/utils/broadcast");

const threads = ["1000...", "2000..."];
await broadcast(api, threads, { body: "Hello!" }, {
  delayMs: 1200,
  skipBlocked: true
});

๐Ÿ“š Documentation

  • DOCS.md โ€” Full API reference, examples, and best practices.
  • docs/ARCHITECTURE.md โ€” Codebase structure and modules (for contributors).
  • For implementation details, the src/ folder is the authoritative reference.

๐Ÿ› ๏ธ Projects Using This API

Here are some awesome projects built with @dongdev/fca-unofficial: (See GitHub Repository for the full list).


๐Ÿค Contributing

Contributions are welcome! If you want to optimize something or fix a bug:

  1. ๐Ÿด Fork the repository
  2. ๐ŸŒฟ Create a new branch
  3. ๐Ÿ’พ Commit your changes
  4. ๐Ÿ“ค Push to the branch
  5. ๐Ÿ”„ Open a Pull Request

Rule: Keep it clean, minimal, and performant. No bloated dependencies.


๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE-MIT file for details.


๐Ÿ‘จโ€๐Ÿ’ป Author & Support

Maintained by DongDev (Donix)

๐Ÿ› ๏ธ Need Custom Work?

If you have the budget and need specialized features, API reverse-engineering, or private bot development, reach out to me directly via Facebook. Do not contact me for free coding lessons.


Made with โค๏ธ (and a lot of caffeine) for the developer community.