fca-nx 6.8.1 → 6.8.3

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.
package/README.md CHANGED
@@ -148,30 +148,6 @@ on load when this key is configured.
148
148
  api.sendMessage("Hello world!", threadID);
149
149
 
150
150
  ```
151
- ### Message Effects
152
- ```javascript
153
- api.sendMessage(
154
- {
155
- body: "I love you! ❤️",
156
- textEffect: "love"
157
- },
158
- threadID
159
- );
160
- ```
161
-
162
- Built-in effect names are `heart`, `hearts`, `love`, `gift`, `present`, `fire`,
163
- `flame`, `confetti`, `confecti`, `party`, `sparkles`, `sparkle`, `star`, and
164
- `magic`. You can also pass a custom numeric effect ID:
165
-
166
- ```javascript
167
- api.sendMessage({ body: "Party time!", effect: "confetti" }, threadID);
168
- api.sendMessage({ body: "Custom effect", textEffect: 27 }, threadID);
169
- ```
170
-
171
- The aliases `textEffect`, `text_effect`, `effect`, `effectName`, and their
172
- snake/camel-case ID variants are accepted. Effects are applied through both
173
- the MQTT sender and the legacy fallback sender.
174
-
175
151
  ### Send Attachment
176
152
  ```javascript
177
153
  const fs = require("fs");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.8.1",
4
- "description": "Facebook Messenger API for Node.js \u2027 hardened sendMessage + listenMqtt (cascade fallback, soft MQTT, anti-reconnect-storm)",
3
+ "version": "6.8.3",
4
+ "description": "Facebook Messenger API \u2014 no bump, no text effects, single MQTT session",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -14,7 +14,6 @@ const log = require("../../../func/logAdapter");
14
14
  const { getType } = require("../../utils/format");
15
15
  const { isReadableStream } = require("../../utils/constants");
16
16
  const { generateOfflineThreadingID } = require("../../utils/format");
17
- const { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
18
17
 
19
18
  module.exports = function (defaultFuncs, api, ctx) {
20
19
  const uploadAttachment = require("./uploadAttachment")(defaultFuncs, api, ctx);
@@ -172,16 +171,6 @@ module.exports = function (defaultFuncs, api, ctx) {
172
171
  metadata_dataclass: JSON.stringify({ media_accessibility_metadata: { alt_text: null } })
173
172
  };
174
173
 
175
- const textEffectId = getTextEffectId(m);
176
- if (textEffectId) payload0.text_effect_id = textEffectId;
177
- const effectArray = getTextEffectIds(m);
178
- if (effectArray.length) {
179
- payload0.text_effect_ids = effectArray.map((id) => {
180
- const n = Number(id);
181
- return Number.isFinite(n) && String(n) === String(id) ? n : id;
182
- });
183
- }
184
-
185
174
  const mentionData = buildMentionData(m, baseBody);
186
175
  if (mentionData) payload0.mention_data = mentionData;
187
176
 
@@ -3,14 +3,10 @@
3
3
  var utils = require("../../utils/utils");
4
4
  var logger = require("../../utils/logger");
5
5
  var bluebird = require("bluebird");
6
- var { getTextEffectId } = require("../../utils/textEffects");
7
6
 
8
7
  var allowedProperties = {
9
8
  attachment: true, url: true, sticker: true, emoji: true,
10
- emojiSize: true, body: true, mentions: true, location: true, text_effect_ids: true,
11
- textEffect: true, text_effect: true, text_effect_id: true, textEffectId: true,
12
- textEffectID: true, effect: true, effect_id: true, effectID: true,
13
- text_effect_name: true, effectName: true, effect_name: true,
9
+ emojiSize: true, body: true, mentions: true, location: true
14
10
  };
15
11
 
16
12
  module.exports = function (defaultFuncs, api, ctx) {
@@ -118,6 +114,7 @@ module.exports = function (defaultFuncs, api, ctx) {
118
114
 
119
115
  return function OldMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
120
116
  if (typeof msg === "string") msg = { body: msg };
117
+ ["text_effect_ids", "textEffect", "text_effect", "text_effect_id", "textEffectId", "textEffectID", "effect", "effect_id", "effectID", "text_effect_name", "effectName", "effect_name"].forEach(function (k) { delete msg[k]; });
121
118
 
122
119
  if (msg.body && /(https?:\/\/|www\.|t\.me\/|fb\.me\/|youtu\.be\/|facebook\.com\/|youtube\.com\/)/i.test(msg.body)) {
123
120
  return require('./sendMessage')(defaultFuncs, api, ctx)(msg, threadID, callback, replyToMessage, false);
@@ -138,8 +135,6 @@ module.exports = function (defaultFuncs, api, ctx) {
138
135
 
139
136
  var form = {};
140
137
  if (msg.body) form.body = msg.body;
141
- var textEffectId = getTextEffectId(msg);
142
- if (textEffectId) form.text_effect_id = textEffectId;
143
138
 
144
139
  if (msg.mentions && Array.isArray(msg.mentions)) {
145
140
  form.body = msg.body || "";
@@ -6,11 +6,11 @@
6
6
  const { formatID } = require("../../../utils/format");
7
7
  const { getSessionIdentity } = require("../../../utils/clientIdentity");
8
8
 
9
- const DEFAULT_RECONNECT_DELAY_MS = 2000;
10
- const MAX_RECONNECT_DELAY_MS = 60000;
11
- const MAX_RECONNECT_ATTEMPTS = 8 // [Hardened5] hit long cooldown sooner instead of hammering; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
12
- const MAX_RECONNECT_COOLDOWN_MS = 15 * 60 * 1000 /* [Hardened5] longer cooldown */; // after exhausting fast retries, wait this long before trying again (never give up permanently)
13
- const T_MS_WAIT_TIMEOUT_MS = 5000;
9
+ const DEFAULT_RECONNECT_DELAY_MS = 15000;
10
+ const MAX_RECONNECT_DELAY_MS = 120000;
11
+ const MAX_RECONNECT_ATTEMPTS = 6
12
+ const MAX_RECONNECT_COOLDOWN_MS = 45 * 60 * 1000;
13
+ const T_MS_WAIT_TIMEOUT_MS = 20000;
14
14
 
15
15
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
16
16
  // attempts have happened for this session (reset to 0 on a successful
@@ -51,6 +51,7 @@ module.exports = function createListenMqtt(deps) {
51
51
  return function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
52
52
 
53
53
  function scheduleReconnect(delayMs) {
54
+ ctx._mqttConnecting = false;
54
55
  const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
55
56
  if (ctx._reconnectTimer) {
56
57
  logger("mqtt reconnect already scheduled", "warn");
@@ -94,6 +95,16 @@ module.exports = function createListenMqtt(deps) {
94
95
  return /No subscription existed|client disconnecting|socket hang up|ECONNRESET/i.test(msg || "");
95
96
  }
96
97
 
98
+ if (ctx.mqttClient && ctx.mqttClient.connected && !ctx._ending) {
99
+ logger("mqtt connect skipped - already connected", "warn");
100
+ return;
101
+ }
102
+ if (ctx._mqttConnecting) {
103
+ logger("mqtt connect skipped - already connecting", "warn");
104
+ return;
105
+ }
106
+ ctx._mqttConnecting = true;
107
+
97
108
  // Ensure only one MQTT connection exists for this session, and that any
98
109
  // previous connection is fully closed (listeners removed, socket ended)
99
110
  // before a new one is opened. Without this, a reconnect racing with a
@@ -103,7 +114,7 @@ module.exports = function createListenMqtt(deps) {
103
114
  if (ctx.mqttClient) {
104
115
  try {
105
116
  ctx.mqttClient.removeAllListeners();
106
- if (ctx.mqttClient.connected) ctx.mqttClient.end(true);
117
+ ctx.mqttClient.end(true);
107
118
  } catch (_) { }
108
119
  ctx.mqttClient = undefined;
109
120
  }
@@ -118,7 +129,12 @@ module.exports = function createListenMqtt(deps) {
118
129
  }
119
130
  // Prefer offline presence unless user explicitly set online:true
120
131
  const chatOn = ctx.globalOptions.online === true;
121
- const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
132
+ // Same browser tab for the life of the process. A new sid on every
133
+ // reconnect looks like a new login and is a common suspend trigger.
134
+ if (!ctx._edgeSid) {
135
+ ctx._edgeSid = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
136
+ }
137
+ const sessionID = ctx._edgeSid;
122
138
  const username = {
123
139
  u: ctx.userID, s: sessionID, chat_on: chatOn, fg: false, d: ctx.clientId,
124
140
  ct: "websocket", aid: 219994525426954, aids: null, mqtt_sid: "",
@@ -161,10 +177,10 @@ module.exports = function createListenMqtt(deps) {
161
177
  protocolVersion: 13,
162
178
  binaryType: "arraybuffer"
163
179
  },
164
- keepalive: 30,
180
+ keepalive: 60,
165
181
  reschedulePings: true,
166
182
  reconnectPeriod: 0,
167
- connectTimeout: 5000
183
+ connectTimeout: 20000
168
184
  };
169
185
  if (ctx.globalOptions.proxy !== undefined) {
170
186
  const agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
@@ -178,6 +194,7 @@ module.exports = function createListenMqtt(deps) {
178
194
  const mqttClient = ctx.mqttClient;
179
195
 
180
196
  mqttClient.on("error", function (err) {
197
+ ctx._mqttConnecting = false;
181
198
  const msg = String(err && err.message ? err.message : err || "");
182
199
  if ((ctx._ending || ctx._cycling) && /No subscription existed|client disconnecting/i.test(msg)) {
183
200
  logger(`mqtt expected during shutdown: ${msg}`, "info");
@@ -200,23 +217,12 @@ module.exports = function createListenMqtt(deps) {
200
217
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
201
218
  }
202
219
 
203
- // Plain 401/403/"Not logged in" is often a cookie/token race — recover softly.
204
- logger(`mqtt transient auth error; refreshing session then reconnecting (no logout): ${msg}`, "warn");
205
- (async () => {
206
- try {
207
- if (api && typeof api.refreshFb_dtsg === "function") {
208
- await api.refreshFb_dtsg();
209
- }
210
- } catch (_) {}
211
- try {
212
- const { get } = require("../../../utils/request");
213
- const { saveCookies } = require("../../../utils/client");
214
- await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
215
- } catch (_) {}
216
- if (!ctx._ending && ctx.globalOptions && ctx.globalOptions.autoReconnect !== false) {
217
- scheduleReconnect();
218
- }
219
- })();
220
+ // Plain 401/403/"Not logged in" is often a cookie race. Do not hit
221
+ // facebook.com (that is a fresh login). Wait, then open one socket.
222
+ logger(`mqtt transient auth error; one delayed reconnect (no homepage login): ${msg}`, "warn");
223
+ if (!ctx._ending && ctx.globalOptions && ctx.globalOptions.autoReconnect !== false) {
224
+ scheduleReconnect(30000);
225
+ }
220
226
  return;
221
227
  }
222
228
  logger(`mqtt error: ${msg}`, "error");
@@ -246,6 +252,8 @@ module.exports = function createListenMqtt(deps) {
246
252
  ctx._cycling = false;
247
253
  ctx.loggedIn = true;
248
254
  ctx._sessionRecovering = false;
255
+ ctx._mqttConnecting = false;
256
+ ctx._tmsMisses = 0;
249
257
  // A successful connect means the session/identity/network are fine -
250
258
  // reset the backoff counter so a later transient failure starts a
251
259
  // fresh backoff sequence instead of inheriting a long delay from an
@@ -273,7 +281,14 @@ module.exports = function createListenMqtt(deps) {
273
281
  logger("mqtt t_ms timeout skipped - ending", "warn");
274
282
  return;
275
283
  }
276
- logger("mqtt t_ms timeout, cycling", "warn");
284
+ logger("mqtt t_ms timeout", "warn");
285
+ ctx._tmsMisses = (ctx._tmsMisses || 0) + 1;
286
+ if (ctx._tmsMisses < 2 && mqttClient && mqttClient.connected) {
287
+ try {
288
+ mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
289
+ } catch (_) { }
290
+ return;
291
+ }
277
292
  try {
278
293
  if (mqttClient && mqttClient.connected) {
279
294
  mqttClient.end(true);
@@ -358,6 +373,7 @@ module.exports = function createListenMqtt(deps) {
358
373
  });
359
374
 
360
375
  mqttClient.on("close", function () {
376
+ ctx._mqttConnecting = false;
361
377
  if (ctx._ending || ctx._cycling) {
362
378
  logger("mqtt close expected", "info");
363
379
  return;
@@ -357,7 +357,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
357
357
 
358
358
  try {
359
359
  if (ctx.mqttClient) {
360
- if (isConnected()) {
360
+ if (!soft && isConnected()) {
361
361
  try {
362
362
  ctx.mqttClient.publish("/browser_close", "{}", { qos: 0 });
363
363
  } catch (_) { }
@@ -454,51 +454,16 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
454
454
  if (!ctx.mqttClient) return;
455
455
 
456
456
  ctx.mqttClient.removeAllListeners("packetreceive");
457
- ctx.mqttClient.removeAllListeners("close");
458
- ctx.mqttClient.removeAllListeners("error");
459
-
460
- // [Fixed by xalman] mqtt.js does NOT emit a "pong" event - that was never firing,
461
- // so lastPongTime was never refreshed and the heartbeat below kept
462
- // force-reconnecting the account roughly every minute (this is what
463
- // looked like periodic auto logout). The library's own keepalive
464
- // (keepalive: 30 in connectMqtt.js) sends PINGREQ/PINGRESP
465
- // internally; we detect the PINGRESP via "packetreceive" instead.
466
- // Any other incoming packet (e.g. real messages) also proves the
467
- // connection is alive, so it counts too.
457
+
458
+ // Do not remove "close" / "error". connectMqtt already owns reconnect.
459
+ // Replacing those handlers made every drop run getSeqID (a fresh login)
460
+ // and sometimes opened a second socket — that is what suspends the account.
468
461
  ctx.mqttClient.on("packetreceive", (packet) => {
469
462
  lastPongTime = Date.now();
470
463
  if (packet && packet.cmd === "pingresp") {
471
464
  logger("mqtt pong received", "debug");
472
465
  }
473
466
  });
474
-
475
- ctx.mqttClient.once("close", () => {
476
- logger("mqtt connection closed", "warn");
477
- stopHeartbeat();
478
- if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
479
- if (!isReconnecting) {
480
- isReconnecting = true;
481
- delayedReconnect();
482
- }
483
- }
484
- });
485
-
486
- ctx.mqttClient.once("error", (err) => {
487
- const msg = err && err.message ? err.message : String(err || "");
488
- logger(`mqtt error: ${msg}`, "error");
489
- if (/blocked the login|checkpoint/i.test(msg)) {
490
- emitAuth(ctx, api, globalCallback, "login_blocked", msg);
491
- return;
492
- }
493
- // Do NOT forceCycle here. forceCycle + the close handler together
494
- // open two sessions. One delayed reconnect is enough.
495
- if (!ctx._ending && ctx.globalOptions.autoReconnect !== false && !isConnected()) {
496
- if (!isReconnecting) {
497
- isReconnecting = true;
498
- delayedReconnect();
499
- }
500
- }
501
- });
502
467
  }
503
468
 
504
469
  return function (callback) {
@@ -7,16 +7,12 @@
7
7
 
8
8
  var utils = require("../../utils/utils");
9
9
  var logger = require("../../utils/logger");
10
- var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
11
10
  var { waitTurn } = require("../../utils/sendThrottle");
12
11
 
13
12
  var ALLOWED = {
14
13
  attachment: true, url: true, sticker: true, emoji: true,
15
14
  emojiSize: true, body: true, mentions: true, location: true,
16
- replyToMessage: true, forwardAttachmentIds: true, text_effect_ids: true,
17
- textEffect: true, text_effect: true, text_effect_id: true,
18
- textEffectId: true, textEffectID: true, effect: true, effect_id: true,
19
- effectID: true, text_effect_name: true, effectName: true, effect_name: true
15
+ replyToMessage: true, forwardAttachmentIds: true
20
16
  };
21
17
 
22
18
  var EMOJI_SIZES = { small: 1, medium: 2, large: 3 };
@@ -173,18 +169,6 @@ module.exports = function (defaultFuncs, api, ctx) {
173
169
  var mentionData = buildMentionData(msg, baseBody);
174
170
  if (mentionData) payload0.mention_data = mentionData;
175
171
 
176
- var textEffectId = getTextEffectId(msg);
177
- if (textEffectId) payload0.text_effect_id = textEffectId;
178
- var effectArray = getTextEffectIds(msg);
179
- if (effectArray.length) {
180
- // Messenger applies the animation only when these are numbers.
181
- // String ids ("1") are ignored and the text goes out plain.
182
- payload0.text_effect_ids = effectArray.map(function (id) {
183
- var n = Number(id);
184
- return Number.isFinite(n) && String(n) === String(id) ? n : id;
185
- });
186
- }
187
-
188
172
  if (msg.sticker) {
189
173
  payload0.send_type = 2;
190
174
  payload0.sticker_id = msg.sticker;
@@ -315,6 +299,8 @@ module.exports = function (defaultFuncs, api, ctx) {
315
299
  return async function sendMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
316
300
  if (typeof msg === "string") msg = { body: msg };
317
301
  if (typeof callback !== "function") callback = null;
302
+ var drop = ["text_effect_ids", "textEffect", "text_effect", "text_effect_id", "textEffectId", "textEffectID", "effect", "effect_id", "effectID", "text_effect_name", "effectName", "effect_name"];
303
+ for (var d = 0; d < drop.length; d++) delete msg[drop[d]];
318
304
 
319
305
  var resolve, reject;
320
306
  var promise = new Promise(function (res, rej) {
@@ -393,10 +379,7 @@ module.exports = function (defaultFuncs, api, ctx) {
393
379
  // ---- E2EE text path with cascade fallback ----
394
380
  // Text replies to E2EE DMs should use the bridge; if it fails, try MQTT then OldMessage
395
381
  // instead of hard-failing (Hardened6).
396
- // Effects are not part of the E2EE payload. If one is set, skip the
397
- // bridge and send over MQTT so the effect is not stripped.
398
382
  if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
399
- !getTextEffectId(msg) &&
400
383
  api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
401
384
  try {
402
385
  var e2eeText = await api.e2ee.sendMessage(
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
 
3
3
  var utils = require("../../utils/utils");
4
- var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
5
4
 
6
5
  module.exports = function (defaultFuncs, api, ctx) {
7
6
  return function sendMessageMqtt(msg, threadID, callback, replyToMessage) {
@@ -34,16 +33,6 @@ module.exports = function (defaultFuncs, api, ctx) {
34
33
  multitab_env: 0
35
34
  };
36
35
 
37
- var textEffectId = getTextEffectId(msg);
38
- if (textEffectId) payload0.text_effect_id = textEffectId;
39
- var effectArray = getTextEffectIds(msg);
40
- if (effectArray.length) {
41
- payload0.text_effect_ids = effectArray.map(function (id) {
42
- var n = Number(id);
43
- return Number.isFinite(n) && String(n) === String(id) ? n : id;
44
- });
45
- }
46
-
47
36
  if (msg.sticker) { payload0.send_type = 2; payload0.sticker_id = msg.sticker; }
48
37
  if (replyToMessage || msg.replyToMessage) {
49
38
  payload0.reply_metadata = {
@@ -48,8 +48,7 @@ function createFallbackNamespaces(api) {
48
48
  getEmojiUrl: bindOptionalMethod(api, "getEmojiUrl"),
49
49
  resolvePhotoUrl: bindOptionalMethod(api, "resolvePhotoUrl"),
50
50
  uploadAttachment: bindOptionalMethod(api, "uploadAttachment"),
51
- forwardAttachment: bindOptionalMethod(api, "forwardAttachment"),
52
- bump: bindLiveMethod(api, "bump")
51
+ forwardAttachment: bindOptionalMethod(api, "forwardAttachment")
53
52
  }),
54
53
  threads: compactNamespace({
55
54
  createGroup: bindOptionalMethod(api, "createNewGroup"),
@@ -7,16 +7,16 @@
7
7
  * released no sooner than `delay` ms after the previous one. This avoids sending bursts that
8
8
  * look like a script and that Facebook's rate limiting reacts to.
9
9
  *
10
- * FCA_NX_SEND_DELAY_MS base gap between sends, default 1000 (set 0 to disable)
11
- * FCA_NX_SEND_JITTER_MS extra random 0..N ms added to each gap, default 400
10
+ * FCA_NX_SEND_DELAY_MS base gap between sends, default 1500 (set 0 to disable)
11
+ * FCA_NX_SEND_JITTER_MS extra random 0..N ms added to each gap, default 600
12
12
  * or at runtime: api.setSendDelay(ms, jitterMs)
13
13
  */
14
14
 
15
15
  const state = { last: 0, chain: Promise.resolve(), delay: null, jitter: null, stamps: [] };
16
- // Hard ceiling per rolling minute (FCA_NX_SEND_MAX_PER_MIN, default 20, 0 = off).
16
+ // Hard ceiling per rolling minute (FCA_NX_SEND_MAX_PER_MIN, default 12, 0 = off).
17
17
  function maxPerMin() {
18
18
  const n = Number(process.env.FCA_NX_SEND_MAX_PER_MIN);
19
- return Number.isFinite(n) && n >= 0 ? n : 20;
19
+ return Number.isFinite(n) && n >= 0 ? n : 12;
20
20
  }
21
21
 
22
22
  function readNum(v, d) {
@@ -25,10 +25,10 @@ function readNum(v, d) {
25
25
  }
26
26
 
27
27
  function getDelay() {
28
- return state.delay != null ? state.delay : readNum(process.env.FCA_NX_SEND_DELAY_MS, 1000);
28
+ return state.delay != null ? state.delay : readNum(process.env.FCA_NX_SEND_DELAY_MS, 1500);
29
29
  }
30
30
  function getJitter() {
31
- return state.jitter != null ? state.jitter : readNum(process.env.FCA_NX_SEND_JITTER_MS, 400);
31
+ return state.jitter != null ? state.jitter : readNum(process.env.FCA_NX_SEND_JITTER_MS, 600);
32
32
  }
33
33
 
34
34
  function setSendDelay(ms, jitterMs) {
@@ -1,146 +0,0 @@
1
- "use strict";
2
-
3
- // api.bump(threadID, options?, callback?)
4
- // Bumps a thread by sending a short message (default "👆") then optionally unsending it.
5
- //
6
- // options:
7
- // text: message to send (default "👆")
8
- // effect: text effect name or id (default "confetti"; false/"none" = plain text)
9
- // unsend: unsend after sending (default true)
10
- // delay: ms to wait before unsend (default 1500, clamped 500..10000)
11
- //
12
- // Returns: { threadID, messageID, unsent, unsendError? }
13
- //
14
- // Safety (hardened):
15
- // - per-thread cooldown 45s
16
- // - global cap 8 bumps / 60s
17
- // - rejects invalid threadID early
18
- // - never throws on unsend failure (message already bumped the thread)
19
-
20
- const COOLDOWN_MS = 45 * 1000;
21
- const WINDOW_MS = 60 * 1000;
22
- const MAX_PER_WINDOW = 8;
23
- const MIN_DELAY = 500;
24
- const MAX_DELAY = 10000;
25
-
26
- module.exports = function (defaultFuncs, api, ctx) {
27
- const lastBump = new Map();
28
- let recent = [];
29
-
30
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
31
-
32
- const send = (body, threadID, effect) =>
33
- new Promise((resolve, reject) => {
34
- if (typeof api.sendMessage !== "function") {
35
- return reject(new Error("bump: api.sendMessage is not available"));
36
- }
37
- const msg = { body };
38
- if (effect != null && effect !== false && effect !== "none" && effect !== "") {
39
- msg.effect = effect;
40
- msg.text_effect_ids = [effect];
41
- }
42
- api.sendMessage(msg, threadID, (err, info) => (err ? reject(err) : resolve(info)));
43
- });
44
-
45
- const unsend = (messageID, threadID) =>
46
- new Promise((resolve, reject) => {
47
- if (typeof api.unsendMessage !== "function") {
48
- return reject(new Error("bump: api.unsendMessage is not available"));
49
- }
50
- // support both (messageID, callback) and (messageID, threadID, callback) styles
51
- try {
52
- const ret = api.unsendMessage(messageID, threadID, (err) => (err ? reject(err) : resolve()));
53
- if (ret && typeof ret.then === "function") {
54
- ret.then(resolve, reject);
55
- }
56
- } catch (e) {
57
- // fallback single-arg form
58
- try {
59
- const ret2 = api.unsendMessage(messageID, (err) => (err ? reject(err) : resolve()));
60
- if (ret2 && typeof ret2.then === "function") {
61
- ret2.then(resolve, reject);
62
- }
63
- } catch (e2) {
64
- reject(e2 || e);
65
- }
66
- }
67
- });
68
-
69
- return function bump(threadID, options, callback) {
70
- if (typeof options === "function") {
71
- callback = options;
72
- options = {};
73
- }
74
- options = options || {};
75
-
76
- const promise = (async () => {
77
- if (threadID == null || threadID === "") {
78
- throw new Error("bump: threadID is required");
79
- }
80
- const tid = String(threadID).trim();
81
- if (!tid) throw new Error("bump: threadID is required");
82
-
83
- const now = Date.now();
84
-
85
- const last = lastBump.get(tid) || 0;
86
- if (now - last < COOLDOWN_MS) {
87
- throw new Error(
88
- `bump: cooldown active for this thread, wait ${Math.ceil((COOLDOWN_MS - (now - last)) / 1000)}s`
89
- );
90
- }
91
-
92
- recent = recent.filter((t) => now - t < WINDOW_MS);
93
- if (recent.length >= MAX_PER_WINDOW) {
94
- throw new Error("bump: global rate limit reached (max 8 / minute), try again shortly");
95
- }
96
-
97
- const text = options.text != null ? String(options.text) : "👆";
98
- let effect = "confetti";
99
- if (options.effect === false || options.effect === null || options.effect === "none" || options.effect === "") {
100
- effect = null;
101
- } else if (options.effect != null) {
102
- effect = options.effect;
103
- }
104
- const doUnsend = options.unsend !== false;
105
- let delay = Number.isFinite(options.delay) ? Number(options.delay) : 1500;
106
- if (delay < MIN_DELAY) delay = MIN_DELAY;
107
- if (delay > MAX_DELAY) delay = MAX_DELAY;
108
-
109
- const info = await send(text, tid, effect);
110
- lastBump.set(tid, Date.now());
111
- recent.push(Date.now());
112
-
113
- // prune map if it grows too large (memory safety)
114
- if (lastBump.size > 5000) {
115
- const cutoff = Date.now() - COOLDOWN_MS * 2;
116
- for (const [k, v] of lastBump) {
117
- if (v < cutoff) lastBump.delete(k);
118
- }
119
- }
120
-
121
- const result = {
122
- threadID: tid,
123
- messageID: info && info.messageID ? String(info.messageID) : null,
124
- unsent: false
125
- };
126
-
127
- if (doUnsend && result.messageID) {
128
- await sleep(delay);
129
- try {
130
- await unsend(result.messageID, tid);
131
- result.unsent = true;
132
- } catch (e) {
133
- // Message was still sent (thread is bumped); unsend can fail e.g. in E2EE DMs.
134
- result.unsendError = e && e.message ? e.message : String(e);
135
- }
136
- }
137
-
138
- return result;
139
- })();
140
-
141
- if (typeof callback === "function") {
142
- promise.then((r) => callback(null, r), (e) => callback(e));
143
- }
144
- return promise;
145
- };
146
- };
@@ -1,91 +0,0 @@
1
- "use strict";
2
-
3
- const TEXT_EFFECTS = Object.freeze({
4
- hearts: "1",
5
- heart: "1",
6
- love: "1",
7
- gift: "2",
8
- present: "2",
9
- box: "2",
10
- giftbox: "2",
11
- fire: "3",
12
- flame: "3",
13
- hot: "3",
14
- confetti: "4",
15
- confecti: "4",
16
- party: "4",
17
- celebrate: "4",
18
- celebration: "4",
19
- sparkles: "5",
20
- sparkle: "5",
21
- star: "5",
22
- stars: "5",
23
- magic: "5"
24
- });
25
-
26
- const EFFECT_PROPERTIES = [
27
- "textEffect",
28
- "text_effect",
29
- "text_effect_id",
30
- "textEffectId",
31
- "textEffectID",
32
- "effect",
33
- "effect_id",
34
- "effectID",
35
- "text_effect_name",
36
- "effectName",
37
- "effect_name"
38
- ];
39
-
40
- function toTextEffectId(effect) {
41
- if (effect === null || effect === undefined) return null;
42
- if (typeof effect === "number" && Number.isFinite(effect)) return String(effect);
43
- if (typeof effect !== "string") return null;
44
-
45
- const value = effect.trim();
46
- if (!value) return null;
47
- return TEXT_EFFECTS[value.toLowerCase()] || value;
48
- }
49
-
50
- function getTextEffectId(message) {
51
- if (!message || typeof message !== "object") return null;
52
- for (const property of EFFECT_PROPERTIES) {
53
- if (message[property] !== undefined && message[property] !== null) {
54
- const effectID = toTextEffectId(message[property]);
55
- if (effectID) return effectID;
56
- }
57
- }
58
-
59
- const rawIDs = Array.isArray(message.text_effect_ids)
60
- ? message.text_effect_ids
61
- : [message.text_effect_ids];
62
- for (const rawID of rawIDs) {
63
- const effectID = toTextEffectId(rawID);
64
- if (effectID) return effectID;
65
- }
66
- return null;
67
- }
68
-
69
- function getTextEffectIds(message) {
70
- if (!message || typeof message !== "object") return [];
71
- const raw = message.text_effect_ids;
72
- const rawIDs = raw == null ? [] : (Array.isArray(raw) ? raw : [raw]);
73
- const ids = [];
74
- for (const rawID of rawIDs) {
75
- const effectID = toTextEffectId(rawID);
76
- if (effectID && !ids.includes(effectID)) ids.push(effectID);
77
- }
78
- // Named fields (effect / effectName / textEffect) must also land in the array.
79
- // Messenger renders text_effect_ids; a lone text_effect_id is often ignored.
80
- const primary = getTextEffectId(message);
81
- if (primary && !ids.includes(primary)) ids.unshift(primary);
82
- return ids;
83
- }
84
-
85
- module.exports = {
86
- EFFECT_PROPERTIES,
87
- TEXT_EFFECTS,
88
- getTextEffectId,
89
- getTextEffectIds,
90
- toTextEffectId
91
- };