@dongdev/fca-unofficial 3.0.31 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +224 -406
  3. package/dist/index.d.mts +1241 -0
  4. package/dist/index.d.ts +1241 -0
  5. package/dist/index.js +27749 -0
  6. package/dist/index.mjs +27713 -0
  7. package/docs/ARCHITECTURE.md +467 -0
  8. package/docs/DOCS.md +686 -0
  9. package/fca-config.example.json +33 -0
  10. package/package.json +32 -22
  11. package/test/fca.test.cjs +533 -0
  12. package/CHANGELOG.md +0 -296
  13. package/DOCS.md +0 -2712
  14. package/func/checkUpdate.js +0 -222
  15. package/func/logAdapter.js +0 -33
  16. package/func/logger.js +0 -48
  17. package/index.d.ts +0 -751
  18. package/index.js +0 -8
  19. package/module/config.js +0 -40
  20. package/module/login.js +0 -133
  21. package/module/loginHelper.js +0 -1296
  22. package/module/options.js +0 -44
  23. package/src/api/action/addExternalModule.js +0 -25
  24. package/src/api/action/changeAvatar.js +0 -137
  25. package/src/api/action/changeBio.js +0 -75
  26. package/src/api/action/enableAutoSaveAppState.js +0 -73
  27. package/src/api/action/getCurrentUserID.js +0 -7
  28. package/src/api/action/handleFriendRequest.js +0 -57
  29. package/src/api/action/logout.js +0 -76
  30. package/src/api/action/refreshFb_dtsg.js +0 -48
  31. package/src/api/action/setPostReaction.js +0 -106
  32. package/src/api/action/unfriend.js +0 -54
  33. package/src/api/http/httpGet.js +0 -46
  34. package/src/api/http/httpPost.js +0 -52
  35. package/src/api/http/postFormData.js +0 -47
  36. package/src/api/messaging/addUserToGroup.js +0 -68
  37. package/src/api/messaging/changeAdminStatus.js +0 -126
  38. package/src/api/messaging/changeArchivedStatus.js +0 -55
  39. package/src/api/messaging/changeBlockedStatus.js +0 -48
  40. package/src/api/messaging/changeGroupImage.js +0 -91
  41. package/src/api/messaging/changeNickname.js +0 -70
  42. package/src/api/messaging/changeThreadColor.js +0 -79
  43. package/src/api/messaging/changeThreadEmoji.js +0 -111
  44. package/src/api/messaging/createNewGroup.js +0 -88
  45. package/src/api/messaging/createPoll.js +0 -46
  46. package/src/api/messaging/createThemeAI.js +0 -98
  47. package/src/api/messaging/deleteMessage.js +0 -136
  48. package/src/api/messaging/deleteThread.js +0 -56
  49. package/src/api/messaging/editMessage.js +0 -68
  50. package/src/api/messaging/forwardAttachment.js +0 -57
  51. package/src/api/messaging/getEmojiUrl.js +0 -29
  52. package/src/api/messaging/getFriendsList.js +0 -82
  53. package/src/api/messaging/getMessage.js +0 -829
  54. package/src/api/messaging/getThemePictures.js +0 -62
  55. package/src/api/messaging/handleMessageRequest.js +0 -65
  56. package/src/api/messaging/markAsDelivered.js +0 -57
  57. package/src/api/messaging/markAsRead.js +0 -88
  58. package/src/api/messaging/markAsReadAll.js +0 -49
  59. package/src/api/messaging/markAsSeen.js +0 -61
  60. package/src/api/messaging/muteThread.js +0 -50
  61. package/src/api/messaging/removeUserFromGroup.js +0 -62
  62. package/src/api/messaging/resolvePhotoUrl.js +0 -43
  63. package/src/api/messaging/scheduler.js +0 -264
  64. package/src/api/messaging/searchForThread.js +0 -53
  65. package/src/api/messaging/sendMessage.js +0 -270
  66. package/src/api/messaging/sendTypingIndicator.js +0 -74
  67. package/src/api/messaging/setMessageReaction.js +0 -90
  68. package/src/api/messaging/setTitle.js +0 -124
  69. package/src/api/messaging/shareContact.js +0 -49
  70. package/src/api/messaging/threadColors.js +0 -128
  71. package/src/api/messaging/unsendMessage.js +0 -81
  72. package/src/api/messaging/uploadAttachment.js +0 -492
  73. package/src/api/socket/core/connectMqtt.js +0 -258
  74. package/src/api/socket/core/emitAuth.js +0 -103
  75. package/src/api/socket/core/getSeqID.js +0 -320
  76. package/src/api/socket/core/getTaskResponseData.js +0 -25
  77. package/src/api/socket/core/parseDelta.js +0 -377
  78. package/src/api/socket/detail/buildStream.js +0 -215
  79. package/src/api/socket/detail/constants.js +0 -28
  80. package/src/api/socket/listenMqtt.js +0 -377
  81. package/src/api/socket/middleware/index.js +0 -216
  82. package/src/api/threads/getThreadHistory.js +0 -664
  83. package/src/api/threads/getThreadInfo.js +0 -296
  84. package/src/api/threads/getThreadList.js +0 -293
  85. package/src/api/threads/getThreadPictures.js +0 -78
  86. package/src/api/users/getUserID.js +0 -65
  87. package/src/api/users/getUserInfo.js +0 -402
  88. package/src/api/users/getUserInfoV2.js +0 -134
  89. package/src/core/sendReqMqtt.js +0 -96
  90. package/src/database/helpers.js +0 -53
  91. package/src/database/models/index.js +0 -88
  92. package/src/database/models/thread.js +0 -50
  93. package/src/database/models/user.js +0 -46
  94. package/src/database/threadData.js +0 -94
  95. package/src/database/userData.js +0 -98
  96. package/src/remote/remoteClient.js +0 -123
  97. package/src/utils/broadcast.js +0 -51
  98. package/src/utils/client.js +0 -10
  99. package/src/utils/constants.js +0 -23
  100. package/src/utils/cookies.js +0 -68
  101. package/src/utils/format/attachment.js +0 -357
  102. package/src/utils/format/cookie.js +0 -9
  103. package/src/utils/format/date.js +0 -50
  104. package/src/utils/format/decode.js +0 -44
  105. package/src/utils/format/delta.js +0 -194
  106. package/src/utils/format/ids.js +0 -64
  107. package/src/utils/format/index.js +0 -64
  108. package/src/utils/format/message.js +0 -88
  109. package/src/utils/format/presence.js +0 -132
  110. package/src/utils/format/readTyp.js +0 -44
  111. package/src/utils/format/thread.js +0 -42
  112. package/src/utils/format/utils.js +0 -141
  113. package/src/utils/headers.js +0 -115
  114. package/src/utils/loginParser/autoLogin.js +0 -125
  115. package/src/utils/loginParser/helpers.js +0 -43
  116. package/src/utils/loginParser/index.js +0 -10
  117. package/src/utils/loginParser/parseAndCheckLogin.js +0 -220
  118. package/src/utils/loginParser/textUtils.js +0 -28
  119. package/src/utils/request/client.js +0 -26
  120. package/src/utils/request/config.js +0 -23
  121. package/src/utils/request/defaults.js +0 -46
  122. package/src/utils/request/helpers.js +0 -46
  123. package/src/utils/request/index.js +0 -17
  124. package/src/utils/request/methods.js +0 -163
  125. package/src/utils/request/proxy.js +0 -21
  126. package/src/utils/request/retry.js +0 -77
  127. package/src/utils/request/sanitize.js +0 -49
package/README.md CHANGED
@@ -1,524 +1,342 @@
1
- <div align="center">
1
+ # @dongdev/fca-unofficial
2
2
 
3
- # 💬 @dongdev/fca-unofficial
3
+ An **unofficial** Node.js library for interacting with **Facebook Messenger** through user-session emulation. It speaks the same HTTP/GraphQL and MQTT protocols the browser client uses, giving you programmatic access to messages, threads, reactions, typing indicators, and more — all in TypeScript with full type definitions.
4
4
 
5
- **Unofficial Facebook Chat API for Node.js** - Interact with Facebook Messenger programmatically
6
-
7
- [Features](#-features) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Documentation](#-documentation) • [Support](#-author--support)
8
-
9
- </div>
10
-
11
- ---
12
-
13
- ## 📋 Table of Contents
14
-
15
- - [⚠️ Disclaimer & Support Policy](#️-disclaimer--support-policy)
16
- - [⚡ Why this fork?](#-why-this-fork)
17
- - [✨ Features](#-features)
18
- - [🔍 Introduction](#-introduction)
19
- - [📦 Installation](#-installation)
20
- - [🚀 Quick Start](#-quick-start)
21
- - [📝 Message Types](#-message-types)
22
- - [💾 AppState Management](#-appstate-management)
23
- - [🔄 Auto Login](#-auto-login)
24
- - [👂 Listening for Messages](#-listening-for-messages)
25
- - [🎯 API Quick Reference](#-api-quick-reference)
26
- - [📚 Documentation](#-documentation)
27
- - [🛠️ Projects Using This API](#️-projects-using-this-api)
28
- - [🤝 Contributing](#-contributing)
29
- - [📄 License](#-license)
30
- - [👨‍💻 Author & Support](#-author--support)
31
-
32
- ---
33
-
34
- ## ⚠️ Disclaimer & Support Policy
35
-
36
- <div align="center">
37
-
38
- **READ THIS BEFORE USING OR OPENING AN ISSUE.**
39
-
40
- </div>
41
-
42
- This repository is provided **"AS IS"** and is entirely open-source. By using this project, you explicitly agree to the following terms:
43
-
44
- 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).
45
- 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.
46
- 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.
47
- 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**.
48
-
49
- If you don't like this policy, feel free to fork the repository and maintain it yourself.
50
-
51
- **Recommendations to avoid bans:**
52
-
53
- - Use **Firefox** or the [fca.dongdev.id.vn](https://fca.dongdev.id.vn) flow to reduce logout issues (especially on iOS).
54
- - Prefer **AppState** over email/password when possible.
55
- - Use strict **rate limiting** in your bots.
5
+ > **Disclaimer:** This library operates by emulating a logged-in browser session. Using it may violate Facebook / Meta's Terms of Service and could result in account restrictions or bans. The author assumes **no responsibility** for how you use this software. Use it only for lawful purposes and at your own risk.
56
6
 
57
7
  ---
58
8
 
59
- ## Why this fork?
9
+ ## Table of Contents
60
10
 
61
- Unlike other outdated forks, `@dongdev/fca-unofficial` is built with a focus on **real-world practicality and performance**:
62
-
63
- - **Performance First:** Stripped out legacy, redundant code that causes technical debt.
64
- - **Modernized Architecture:** Adapted to the latest Facebook backend structure.
65
- - **Clean Logic:** No messy wrappers. The codebase is straightforward and easy to navigate if you actually open the files.
66
-
67
- ---
68
-
69
- ## ✨ Features
70
-
71
- - ✅ **Full Messenger API** - Send messages, files, stickers, and more
72
- - ✅ **Real-time Events** - Listen to messages, reactions, and thread events
73
- - ✅ **User Account Support** - Works with personal Facebook accounts (not just Pages)
74
- - ✅ **AppState Support** - Save login state to avoid re-authentication
75
- - ✅ **MQTT Protocol** - Real-time messaging via MQTT
76
- - ✅ **TypeScript Support** - Includes TypeScript definitions
77
- - ✅ **Active Development** - Regularly updated and maintained
11
+ - [Installation](#installation)
12
+ - [Quick Start](#quick-start)
13
+ - [Authentication](#authentication)
14
+ - [API Styles](#api-styles)
15
+ - [MessengerBot (Event-Driven)](#messengerbot-event-driven)
16
+ - [Configuration](#configuration)
17
+ - [Features Overview](#features-overview)
18
+ - [Project Documentation](#project-documentation)
19
+ - [Requirements](#requirements)
20
+ - [License](#license)
21
+ - [Links](#links)
78
22
 
79
23
  ---
80
24
 
81
- ## 🔍 Introduction
82
-
83
- Facebook provides an [official API for chat bots](https://developers.facebook.com/docs/messenger-platform), but it's **only available for Facebook Pages**.
84
-
85
- `@dongdev/fca-unofficial` is the API that allows you to automate chat functionalities on a **user account** by emulating the browser. This means:
86
-
87
- - 🔄 Making the exact same GET/POST requests as a browser
88
- - 🔐 Does not work with auth tokens
89
- - 📝 Requires Facebook account credentials (email/password) or AppState
25
+ ## Installation
90
26
 
91
- **Perfect for:**
92
-
93
- - 🤖 Building chatbots
94
- - 📱 Automating message responses
95
- - 🔔 Creating notification systems
96
- - 🎮 Building interactive games
97
- - 📊 Analytics and monitoring
98
-
99
- ---
27
+ ```bash
28
+ npm install @dongdev/fca-unofficial@latest
29
+ ```
100
30
 
101
- ## 📦 Installation
31
+ If you clone the repository and want to work with the source directly:
102
32
 
103
33
  ```bash
104
- npm install @dongdev/fca-unofficial@latest
34
+ git clone https://github.com/dongp06/fca-unofficial.git
35
+ cd fca-unofficial
36
+ npm install
37
+ npm run build
105
38
  ```
106
39
 
107
- **Requirements:**
40
+ The build produces three artifacts in `dist/`:
108
41
 
109
- - Node.js >= 12.0.0
110
- - Active Facebook account
42
+ | File | Format |
43
+ |-------------------|---------------------|
44
+ | `dist/index.js` | CommonJS (CJS) |
45
+ | `dist/index.mjs` | ES Modules (ESM) |
46
+ | `dist/index.d.ts` | TypeScript typings |
111
47
 
112
48
  ---
113
49
 
114
- ## 🚀 Quick Start
50
+ ## Quick Start
115
51
 
116
- ### 1️⃣ Login and Simple Echo Bot
52
+ ### Event-driven bot (recommended)
117
53
 
118
54
  ```javascript
119
- const login = require("@dongdev/fca-unofficial");
120
-
121
- login({ appState: [] }, (err, api) => {
122
- if (err) return console.error(err);
55
+ const { createMessengerBot } = require("@dongdev/fca-unofficial");
56
+
57
+ async function main() {
58
+ const bot = await createMessengerBot(
59
+ { appState: require("./appstate.json") },
60
+ {
61
+ listenEvents: true,
62
+ stopOnSignals: true,
63
+ commandPrefix: "/"
64
+ }
65
+ );
123
66
 
124
- api.listenMqtt((err, event) => {
125
- if (err) return console.error(err);
67
+ bot.on("error", (err) => console.error("Bot error:", err));
126
68
 
127
- // Echo back the received message
128
- if (event.type === "message") {
129
- api.sendMessage(event.body, event.threadID);
69
+ bot.on("messageCreate", (event) => {
70
+ if (event.body) {
71
+ console.log(`[${event.threadID}] ${event.body}`);
130
72
  }
131
73
  });
132
- });
133
- ```
134
-
135
- ### 2️⃣ Send Text Message
136
-
137
- ```javascript
138
- const login = require("@dongdev/fca-unofficial");
139
-
140
- login({ appState: [] }, (err, api) => {
141
- if (err) {
142
- console.error("Login Error:", err);
143
- return;
144
- }
145
-
146
- const yourID = "000000000000000"; // Replace with actual Facebook ID
147
- const msg = "Hey! 👋";
148
74
 
149
- api.sendMessage(msg, yourID, (err) => {
150
- if (err) console.error("Message Sending Error:", err);
151
- else console.log("✅ Message sent successfully!");
75
+ bot.command("ping", async (ctx) => {
76
+ await ctx.replyAsync("pong");
152
77
  });
153
- });
154
- ```
78
+ }
155
79
 
156
- > **💡 Tip:** To find your Facebook ID, look inside the cookies under the name `c_user`
80
+ main();
81
+ ```
157
82
 
158
- ### 3️⃣ Send File/Image
83
+ ### Legacy callback style
159
84
 
160
85
  ```javascript
161
- const login = require("@dongdev/fca-unofficial");
162
- const fs = require("fs");
86
+ const { login } = require("@dongdev/fca-unofficial");
163
87
 
164
- login({ appState: [] }, (err, api) => {
165
- if (err) {
166
- console.error("Login Error:", err);
167
- return;
168
- }
169
-
170
- const yourID = "000000000000000";
171
- const imagePath = __dirname + "/image.jpg";
172
-
173
- // Check if file exists
174
- if (!fs.existsSync(imagePath)) {
175
- console.error("❌ Error: Image file not found!");
176
- return;
177
- }
88
+ async function main() {
89
+ const ctx = await login({ appState: require("./appstate.json") });
90
+ const api = ctx.api;
178
91
 
179
- const msg = {
180
- body: "Check out this image! 📷",
181
- attachment: fs.createReadStream(imagePath),
182
- };
183
-
184
- api.sendMessage(msg, yourID, (err) => {
185
- if (err) console.error("Message Sending Error:", err);
186
- else console.log("✅ Image sent successfully!");
92
+ api.listenMqtt((err, event) => {
93
+ if (err) return console.error(err);
94
+ if (event.type === "message") {
95
+ api.sendMessage(`Echo: ${event.body}`, event.threadID);
96
+ }
187
97
  });
188
- });
98
+ }
99
+
100
+ main();
189
101
  ```
190
102
 
191
103
  ---
192
104
 
193
- ## 📝 Message Types
105
+ ## Authentication
194
106
 
195
- | Type | Usage | Example |
196
- | ---------------- | ------------------------------------------- | -------------------------------------------------- |
197
- | **Regular text** | `{ body: "message text" }` | `{ body: "Hello!" }` |
198
- | **Sticker** | `{ sticker: "sticker_id" }` | `{ sticker: "369239263222822" }` |
199
- | **File/Image** | `{ attachment: fs.createReadStream(path) }` | `{ attachment: fs.createReadStream("image.jpg") }` |
200
- | **URL** | `{ url: "https://example.com" }` | `{ url: "https://github.com" }` |
201
- | **Large emoji** | `{ emoji: "👍", emojiSize: "large" }` | `{ emoji: "👍", emojiSize: "large" }` |
107
+ The library supports multiple credential strategies. Pass **one** of the following to `login()` or `createMessengerBot()`:
202
108
 
203
- > **📌 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.
109
+ | Credential | Description |
110
+ |----------------|-------------------------------------------------------------------------------------------------------------|
111
+ | `appState` | An array of cookie objects (`{ key, value, domain, path, ... }`) exported from a browser extension or tool. **Recommended for bots.** |
112
+ | `Cookie` | A raw cookie header string, e.g. `"c_user=...; xs=...; ..."`. |
113
+ | `email` + `password` | Web login credentials. Prone to checkpoints and CAPTCHAs; **not recommended** for long-running bots. |
204
114
 
205
- **Emoji sizes:** `small` | `medium` | `large`
115
+ You can also use `loginViaAPI` / `tokensViaAPI` for token-based authentication through an external API server (see `fca-config.json` → `apiServer`).
206
116
 
207
117
  ---
208
118
 
209
- ## 💾 AppState Management
119
+ ## API Styles
210
120
 
211
- ### Save AppState
121
+ After authentication, you get an `FcaContext` object. The library offers two ways to call Messenger functions:
212
122
 
213
- Save your login session to avoid re-authentication:
123
+ ### 1. Flat API (legacy-compatible)
214
124
 
215
- ```javascript
216
- const fs = require("fs");
217
- const login = require("@dongdev/fca-unofficial");
218
-
219
- const credentials = { email: "YOUR_EMAIL", password: "YOUR_PASSWORD" }; // Or use existing appState
220
-
221
- login(credentials, (err, api) => {
222
- if (err) {
223
- console.error("Login Error:", err);
224
- return;
225
- }
226
-
227
- try {
228
- const appState = JSON.stringify(api.getAppState(), null, 2);
229
- fs.writeFileSync("appstate.json", appState);
230
- console.log("✅ AppState saved successfully!");
231
- } catch (error) {
232
- console.error("❌ Error saving AppState:", error);
233
- }
234
- });
235
- ```
236
-
237
- ### Use Saved AppState
238
-
239
- Load your saved AppState for faster login:
125
+ Every method lives directly on `ctx.api`:
240
126
 
241
127
  ```javascript
242
- const fs = require("fs");
243
- const login = require("@dongdev/fca-unofficial");
244
-
245
- login(
246
- { appState: JSON.parse(fs.readFileSync("appstate.json", "utf8")) },
247
- (err, api) => {
248
- if (err) {
249
- console.error("Login Error:", err);
250
- return;
251
- }
252
-
253
- console.log("✅ Logged in successfully!");
254
- // Your code here
255
- },
256
- );
128
+ api.sendMessage("Hello!", threadID);
129
+ api.getThreadInfo(threadID, (err, info) => { ... });
130
+ api.setMessageReaction(":heart:", messageID);
257
131
  ```
258
132
 
259
- ---
133
+ ### 2. Namespaced client facade
260
134
 
261
- ## 🔄 Auto Login
135
+ Group related methods under domain namespaces for cleaner code:
262
136
 
263
- 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.
137
+ ```typescript
138
+ import { createFcaClient } from "@dongdev/fca-unofficial";
264
139
 
265
- 1. Create **`fca-config.json`** in your project root (same folder as where you run `node`):
140
+ const client = createFcaClient(ctx.api);
266
141
 
267
- ```json
268
- {
269
- "autoLogin": true,
270
- "apiServer": "https://minhdong.site",
271
- "apiKey": "",
272
- "credentials": {
273
- "email": "YOUR_EMAIL_OR_PHONE",
274
- "password": "YOUR_PASSWORD",
275
- "twofactor": ""
276
- }
277
- }
142
+ await client.messages.send("Hello!", threadID);
143
+ await client.threads.getInfo(threadID);
144
+ await client.users.getInfo(userID);
278
145
  ```
279
146
 
280
- 2. **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.
281
-
282
- - Set **`autoLogin`** to `false` to disable automatic re-login.
283
- - **`twofactor`**: Base32 secret for 2FA (not the 6-digit code). Leave empty if you do not use 2FA.
284
- - **`apiServer`** / **`apiKey`**: Optional; used for external iOS-style login. Default server is `https://minhdong.site`.
285
-
286
- Keep **`fca-config.json`** out of version control (add it to `.gitignore`) since it contains credentials.
147
+ Available namespaces: `messages`, `threads`, `users`, `account`, `realtime`, `http`, `scheduler`.
287
148
 
288
149
  ---
289
150
 
290
- ## 🔐 Security, Trust & Supply Chain
291
-
292
- - Published via **GitHub Actions** using `npm publish --provenance`, so the tarball on npm can be cryptographically tied back to this repo.
293
- - Core runtime code in `module/` and `src/` is **readable JavaScript** with no obfuscated logic.
294
- - Legacy forks (such as Horizon) are kept only for reference and are **not** shipped in the npm package.
295
- - No telemetry or hidden network calls:
296
- - All HTTP traffic is implemented in `src/utils/request.js` and `module/loginHelper.js`.
297
- - External URLs (such as `apiServer` or proxies) are fully user‑configurable.
298
- - The npm publish account uses **2FA** and dedicated automation tokens.
299
-
300
- See `SECURITY.md` for more details.
151
+ ## MessengerBot (Event-Driven)
301
152
 
302
- ---
153
+ `MessengerBot` provides a high-level, event-driven interface inspired by Discord.js and Telegraf.
303
154
 
304
- ## 👂 Listening for Messages
155
+ ### Creating a bot
305
156
 
306
- ### Echo Bot with Stop Command
157
+ ```typescript
158
+ import { createMessengerBot } from "@dongdev/fca-unofficial";
307
159
 
308
- ```javascript
309
- const fs = require("fs");
310
- const login = require("@dongdev/fca-unofficial");
311
-
312
- login(
313
- { appState: JSON.parse(fs.readFileSync("appstate.json", "utf8")) },
314
- (err, api) => {
315
- if (err) return console.error("Login Error:", err);
316
-
317
- // Enable listening to events (join/leave, title change, etc.)
318
- api.setOptions({ listenEvents: true });
319
-
320
- const stopListening = api.listenMqtt((err, event) => {
321
- if (err) return console.error("Listen Error:", err);
322
-
323
- // Mark as read
324
- api.markAsRead(event.threadID, (err) => {
325
- if (err) console.error("Mark as read error:", err);
326
- });
327
-
328
- // Handle different event types
329
- switch (event.type) {
330
- case "message":
331
- if (event.body && event.body.trim().toLowerCase() === "/stop") {
332
- api.sendMessage("Goodbye… 👋", event.threadID);
333
- stopListening();
334
- return;
335
- }
336
- api.sendMessage(`🤖 BOT: ${event.body}`, event.threadID);
337
- break;
338
-
339
- case "event":
340
- console.log("📢 Event Received:", event);
341
- break;
342
- }
343
- });
344
- },
160
+ const bot = await createMessengerBot(
161
+ { appState: require("./appstate.json") },
162
+ {
163
+ listenEvents: true,
164
+ stopOnSignals: true,
165
+ commandPrefix: "/",
166
+ maxEventListeners: 64,
167
+ enableComposer: true
168
+ }
345
169
  );
346
170
  ```
347
171
 
348
- ### Listen Options
349
-
350
- Configure listening behavior:
351
-
352
- ```javascript
353
- api.setOptions({
354
- listenEvents: true, // Receive events (join/leave, rename, etc.)
355
- selfListen: true, // Receive messages from yourself
356
- logLevel: "silent", // Disable logs (silent/error/warn/info/verbose)
357
- });
358
- ```
359
-
360
- ---
361
-
362
- ## 🎯 API Quick Reference
363
-
364
- _(For full details, please read the source code or `DOCS.md`)_
365
-
366
- ### 📨 Messaging
367
-
368
- `sendMessage`, `sendTypingIndicator`, `getMessage`, `editMessage`, `deleteMessage`, `unsendMessage`, `setMessageReaction`, `forwardAttachment`, `uploadAttachment`, `createPoll`
369
-
370
- ### 📬 Read Receipt & Delivery
371
-
372
- `markAsRead`, `markAsReadAll`, `markAsDelivered`, `markAsSeen`
172
+ ### Events
373
173
 
374
- ### 👥 Thread Management
174
+ | Event | Trigger |
175
+ |----------------------|----------------------------------------------|
176
+ | `message` | Any incoming message (including replies) |
177
+ | `messageCreate` | Alias for `message` |
178
+ | `message_reply` | A reply to an existing message |
179
+ | `messageReactionAdd` | A reaction is added to a message |
180
+ | `messageDelete` | A message is unsent/deleted |
181
+ | `typingStart` | A user starts typing |
182
+ | `typingStop` | A user stops typing |
183
+ | `threadUpdate` | Thread metadata changes (title, participants) |
184
+ | `ready` | MQTT connection established |
185
+ | `raw` / `update` | Every MQTT delta (unfiltered) |
186
+ | `error` | Any error during listening |
375
187
 
376
- `getThreadInfo`, `getThreadList`, `getThreadHistory`, `deleteThread`, `changeThreadColor`, `changeThreadEmoji`, `changeGroupImage`, `setTitle`, `changeNickname`
188
+ ### Composer middleware
377
189
 
378
- ### 👤 User & Group Management
379
-
380
- `getUserInfo`, `getFriendsList`, `getCurrentUserID`, `createNewGroup`, `addUserToGroup`, `removeUserFromGroup`, `changeAdminStatus`
381
-
382
- ### ⚙️ Thread Settings & Actions
383
-
384
- `muteThread`, `changeArchivedStatus`, `changeBlockedStatus`, `handleMessageRequest`, `changeAvatar`, `changeBio`, `handleFriendRequest`, `unfriend`
385
-
386
- ### 🔐 Auth & Listening
387
-
388
- `logout`, `getAppState`, `setOptions`, `listenMqtt`
389
-
390
- ---
391
- ## 🎛 Event Hooks & Remote Control (Advanced)
392
-
393
- Starting from `3.x`, the API instance also behaves like an **EventEmitter** for lifecycle and remote‑control events:
394
-
395
- - **Lifecycle events**:
396
- - `sessionExpired` — login session is no longer valid, auto‑login will be attempted (if configured).
397
- - `autoLoginSuccess` — auto‑login succeeded and the failed request will be retried.
398
- - `autoLoginFailed` — auto‑login could not recover the session.
399
- - `checkpoint` — generic checkpoint, with subtype in `{ type: "282" | "956" | "scraping_warning" }`.
400
- - `checkpoint_282`, `checkpoint_956` — more specific checkpoint events.
401
- - `loginBlocked` — Facebook actively blocked the login (error `1357001`).
402
- - `rateLimit` — HTTP 429 detected on Facebook endpoints.
403
- - `networkError` — network‑level failure (timeouts, DNS, connection reset, etc.).
404
-
405
- Usage:
190
+ The composer pipeline processes `message` and `message_reply` events through a chain of middleware functions:
406
191
 
407
192
  ```javascript
408
- api.on("checkpoint_956", ({ res }) => {
409
- console.error("Checkpoint 956 detected, manual action required.");
193
+ // Global middleware
194
+ bot.use(async (ctx, next) => {
195
+ console.log(`[${ctx.threadID}] ${ctx.text}`);
196
+ await next();
410
197
  });
411
198
 
412
- api.on("rateLimit", ({ url, method }) => {
413
- console.warn("Rate limit hit on", method, url);
199
+ // Command handler — matches "/ping" at the start of a message
200
+ bot.command("ping", async (ctx) => {
201
+ await ctx.replyAsync("pong");
414
202
  });
415
- ```
416
-
417
- - **Remote control events** (when `remoteControl.enabled` is `true` in `fca-config.json`):
418
- - `remoteConnected` / `remoteDisconnected`
419
- - `remoteStop`
420
- - `remoteBroadcast`
421
- - `remoteMessage` (raw messages from your WS backend)
422
203
 
423
- See `examples/remote-control.js` for a concrete integration example.
424
-
425
- ---
426
-
427
- ## 🌐 Proxy Configuration & Broadcast Helper
204
+ // Pattern matching regex or substring
205
+ bot.hears(/hello/i, async (ctx) => {
206
+ await ctx.replyAsync("Hi there!");
207
+ });
428
208
 
429
- - **Proxy support**:
430
- - You can pass a proxy per‑login:
209
+ bot.hears("goodbye", async (ctx) => {
210
+ ctx.reply("See you later!");
211
+ });
431
212
 
432
- ```javascript
433
- login({ appState }, (err, api) => {
434
- if (err) return console.error(err);
435
- api.setOptions({ proxy: "http://user:pass@host:port" });
213
+ // Error handler for the composer chain
214
+ bot.catch((err, ctx) => {
215
+ console.error("Composer error:", err);
436
216
  });
437
217
  ```
438
218
 
439
- - Or define a default in `fca-config.json`:
219
+ ### MessengerContext
440
220
 
441
- ```json
442
- {
443
- "proxy": "http://user:pass@host:port"
444
- }
445
- ```
221
+ Each composer handler receives a `MessengerContext` with:
446
222
 
447
- - All HTTP calls go through this proxy using `https-proxy-agent`.
223
+ | Property / Method | Description |
224
+ |-----------------------|-----------------------------------------------|
225
+ | `ctx.text` | Trimmed message body |
226
+ | `ctx.body` | Raw message body |
227
+ | `ctx.threadID` | Thread the message belongs to |
228
+ | `ctx.senderID` | User who sent the message |
229
+ | `ctx.messageID` | Unique message identifier |
230
+ | `ctx.event` | Full `MessageEvent` object |
231
+ | `ctx.reply(payload)` | Send a reply (callback-style) |
232
+ | `ctx.replyAsync(payload)` | Send a reply (returns a `Promise`) |
448
233
 
449
- - **Broadcast helper** (optional util):
450
- - Not part of the public API surface on purpose (to avoid encouraging spam).
451
- - You can use it manually:
234
+ ### Lifecycle
452
235
 
453
236
  ```javascript
454
- const broadcast = require("@dongdev/fca-unofficial/src/utils/broadcast");
237
+ await bot.launch({ stopOnSignals: true });
455
238
 
456
- const threads = ["1000...", "2000..."];
457
- await broadcast(api, threads, { body: "Hello!" }, {
458
- delayMs: 1200,
459
- skipBlocked: true
460
- });
239
+ // Graceful shutdown
240
+ await bot.stop();
461
241
  ```
462
242
 
463
- ---
243
+ When `stopOnSignals` is `true`, the bot automatically calls `stop()` on `SIGINT` / `SIGTERM`.
464
244
 
465
- ## 📚 Documentation
245
+ ---
466
246
 
467
- - **[DOCS.md](./DOCS.md)** — Full API reference, examples, and best practices.
468
- - **[docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md)** — Codebase structure and modules (for contributors).
469
- - For implementation details, the `src/` folder is the authoritative reference.
247
+ ## Configuration
470
248
 
471
- ---
249
+ Copy the example config and edit it:
472
250
 
473
- ## 🛠️ Projects Using This API
251
+ ```bash
252
+ cp fca-config.example.json fca-config.json
253
+ ```
474
254
 
475
- Here are some awesome projects built with `@dongdev/fca-unofficial`:
476
- _(See [GitHub Repository](https://github.com/Donix-VN/fca-unofficial) for the full list)._
255
+ ### Configuration blocks
256
+
257
+ | Block | Purpose |
258
+ |-----------------|-------------------------------------------------------------------------------|
259
+ | `checkUpdate` | Automatic npm version check on startup |
260
+ | `mqtt` | MQTT reconnect interval, enable/disable realtime |
261
+ | `autoLogin` | Re-authenticate automatically when the session expires |
262
+ | `credentials` | Email / password / 2FA secret for auto-login |
263
+ | `antiGetInfo` | Toggle SQLite-backed caching for `getThreadInfo` / `getUserInfo` |
264
+ | `remoteControl` | WebSocket-based remote control for external dashboards |
265
+ | `apiServer` | External API server URL for token-based login |
266
+
267
+ ### Login options (`FcaOptions`)
268
+
269
+ | Option | Type | Default | Description |
270
+ |-------------------|-----------|-----------|--------------------------------------------------|
271
+ | `listenEvents` | `boolean` | `false` | Receive thread events (not just messages) |
272
+ | `selfListen` | `boolean` | `false` | Receive your own messages |
273
+ | `selfListenEvent` | `boolean` | `false` | Receive your own thread events |
274
+ | `listenTyping` | `boolean` | `false` | Receive typing indicators |
275
+ | `updatePresence` | `boolean` | `false` | Receive presence/online status updates |
276
+ | `forceLogin` | `boolean` | `false` | Force login even if already logged in |
277
+ | `autoMarkRead` | `boolean` | `false` | Automatically mark messages as read |
278
+ | `autoReconnect` | `boolean` | `false` | Reconnect MQTT automatically on disconnect |
279
+ | `online` | `boolean` | `false` | Appear online to other users |
280
+ | `emitReady` | `boolean` | `false` | Emit a `ready` event when MQTT connects |
281
+ | `userAgent` | `string` | Chrome UA | Custom User-Agent header |
282
+ | `proxy` | `string` | — | HTTP/SOCKS proxy URL |
283
+ | `pageID` | `string` | — | Act as a Facebook Page instead of a user |
284
+ | `logLevel` | `string` | `"info"` | Logging verbosity (`silly`, `info`, `warn`, `error`, `silent`) |
477
285
 
478
286
  ---
479
287
 
480
- ## 🤝 Contributing
288
+ ## Features Overview
481
289
 
482
- Contributions are welcome! If you want to optimize something or fix a bug:
290
+ ### Messaging
291
+ Send text, attachments, stickers; edit, unsend, delete messages; forward attachments; upload files; set reactions; share contacts; send typing indicators; mark as read/delivered/seen.
483
292
 
484
- 1. 🍴 Fork the repository
485
- 2. 🌿 Create a new branch
486
- 3. 💾 Commit your changes
487
- 4. 📤 Push to the branch
488
- 5. 🔄 Open a Pull Request
293
+ ### Threads
294
+ Get thread info and history; list threads; search threads; create groups; add/remove participants; change admin status; change group name, image, color, emoji; create polls; archive/mute/delete threads; handle message requests.
489
295
 
490
- **Rule:** Keep it clean, minimal, and performant. No bloated dependencies.
296
+ ### Users
297
+ Look up user info (single and batch); resolve user IDs from vanity URLs; get friends list.
491
298
 
492
- ---
299
+ ### Account
300
+ Change avatar, bio, blocked status; handle friend requests; unfriend; set post reactions; refresh `fb_dtsg`; logout; manage external modules; auto-save app state.
301
+
302
+ ### Realtime (MQTT)
303
+ Persistent WebSocket connection to Facebook's MQTT broker. Receives messages, reactions, typing indicators, presence, thread events, read receipts, and more in real time. Automatic reconnection with debounce and jitter.
493
304
 
494
- ## 📄 License
305
+ ### Database (optional)
306
+ SQLite-backed caching via Sequelize. Thread and user data are cached locally to reduce API calls. Thread cache is kept in sync with realtime events through `attachThreadInfoRealtimeSync`.
495
307
 
496
- This project is licensed under the **MIT License** - see the [LICENSE-MIT](./LICENSE-MIT) file for details.
308
+ ### Scheduler
309
+ Built-in scheduling domain for deferred or periodic tasks.
497
310
 
498
311
  ---
499
312
 
500
- ## 👨‍💻 Author & Support
313
+ ## Project Documentation
501
314
 
502
- <div align="center">
315
+ | Document | Contents |
316
+ |------------------------------------------------|---------------------------------------------------------|
317
+ | [docs/DOCS.md](./docs/DOCS.md) | Full API reference: login, facade, MessengerBot, MQTT, caching |
318
+ | [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | Source tree layout, bootstrap flow, module design |
319
+ | [CHANGELOG](https://github.com/dongp06/fca-unofficial/blob/main/CHANGELOG.md) | Version history (repository only; not in the npm package) |
320
+ | [fca-config.example.json](./fca-config.example.json) | Sample configuration file |
503
321
 
504
- **Maintained by DongDev (Donix)**
322
+ ---
505
323
 
506
- </div>
324
+ ## Requirements
507
325
 
508
- ### 🛠️ Need Custom Work?
326
+ - **Node.js** >= 14.0.0 (LTS recommended)
327
+ - **npm** or any compatible package manager
509
328
 
510
- 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.**
329
+ ---
511
330
 
512
- ### 🔗 Links
331
+ ## License
513
332
 
514
- - 📦 [NPM Package](https://www.npmjs.com/package/@dongdev/fca-unofficial)
515
- - 🐙 [GitHub Repository](https://github.com/Donix-VN/fca-unofficial)
516
- - 🐛 [Issue Tracker](https://github.com/Donix-VN/fca-unofficial/issues)
333
+ This project is licensed under the **Apache License, Version 2.0**. See the [LICENSE](./LICENSE) file for the full text.
517
334
 
518
335
  ---
519
336
 
520
- <div align="center">
521
-
522
- Made with ❤️ (and a lot of caffeine) for the developer community.
337
+ ## Links
523
338
 
524
- </div>
339
+ - **npm:** [@dongdev/fca-unofficial](https://www.npmjs.com/package/@dongdev/fca-unofficial)
340
+ - **GitHub:** [dongp06/fca-unofficial](https://github.com/dongp06/fca-unofficial)
341
+ - **Issues:** [GitHub Issues](https://github.com/dongp06/fca-unofficial/issues)
342
+ - **Author:** DongDev — [GitHub](https://github.com/dongp06)