levix-bot 4.9.1 → 5.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 (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -1,70 +1,274 @@
1
- // In-memory store for messages the bot itself sent.
1
+ // In-memory store for outbound messages the bot itself sent.
2
2
  //
3
- // Sole purpose: back Baileys' getMessage callback so retries succeed. When a
4
- // recipient can't decrypt something we sent, Baileys asks for it again through
5
- // getMessage; rc10's enableAutoSessionRecreation needs this to recover from
6
- // "this message can take a while".
3
+ // Sole purpose: back Baileys' getMessage callback so retry receipts can resend
4
+ // the exact proto.IMessage that was relayed when Baileys' 5-minute internal
5
+ // cache misses.
7
6
  //
8
- // Nothing is written to disk and nothing other people send is kept here.
7
+ // Privacy and persistence:
8
+ // - Memory only; nothing is written to disk or logs, and nothing other people
9
+ // send is kept here.
10
+ // - Cleared on account unlink (clearAccountScopedState -> clearRecentMessages).
11
+ // - After a process restart nothing is recoverable; a retry for a pre-restart
12
+ // message returns undefined so Baileys skips the resend instead of sending an
13
+ // empty message.
9
14
  //
10
- // Eviction: time-based + size-cap, both small — a retry request arrives within
11
- // minutes or not at all.
15
+ // Bounds: at most 500 entries, 1 hour TTL, 8 MiB total encoded protobuf budget,
16
+ // and 1 MiB maximum per single message, evicting oldest entries first.
17
+
18
+ import { proto } from "@whiskeysockets/baileys";
19
+ import { createRequire } from "module";
20
+ import normalizeJid, { isLidJid, isPnJid } from "./normalizeJid.esm.js";
21
+ import { getLidForPn, getLidsForPn, getPnForLid } from "./storage.esm.js";
22
+
23
+ const require = createRequire(import.meta.url);
24
+ const logger = require("./logger.cjs");
12
25
 
13
26
  const DEFAULT_TTL_MS = 1000 * 60 * 60; // 1 hour
14
27
  const DEFAULT_MAX_ITEMS = 500;
28
+ const DEFAULT_MAX_BYTES = 8 * 1024 * 1024; // 8 MiB
29
+ const DEFAULT_MAX_ENTRY_BYTES = 1024 * 1024; // 1 MiB
30
+ const KEY_SEPARATOR = "\u0000";
15
31
 
16
- const recent = new Map(); // id -> { value, expiresAt }
32
+ const recent = new Map(); // "${chatJid}\u0000${id}" -> { chatJid, id, message, bytes, expiresAt }
33
+ let totalBytes = 0;
34
+ let accountEpoch = 0;
17
35
  let ttlMs = DEFAULT_TTL_MS;
18
36
  let maxItems = DEFAULT_MAX_ITEMS;
37
+ let maxBytes = DEFAULT_MAX_BYTES;
38
+ let maxEntryBytes = DEFAULT_MAX_ENTRY_BYTES;
39
+
40
+ function makeCacheKey(chatJid, id) {
41
+ return `${chatJid}${KEY_SEPARATOR}${id}`;
42
+ }
43
+
44
+ function normalizeChatJid(jid) {
45
+ if (typeof jid !== "string") return "";
46
+ const trimmed = jid.trim();
47
+ if (!trimmed) return "";
48
+ if (trimmed.endsWith("@g.us")) {
49
+ return trimmed.includes(":") ? "" : trimmed;
50
+ }
51
+ return normalizeJid(trimmed) || "";
52
+ }
53
+
54
+ function deleteEntry(mapKey) {
55
+ const existing = recent.get(mapKey);
56
+ if (!existing) return;
57
+ totalBytes = Math.max(0, totalBytes - existing.bytes);
58
+ recent.delete(mapKey);
59
+ }
19
60
 
20
61
  function gc(now = Date.now()) {
21
62
  // Drop expired entries first.
22
- for (const [id, entry] of recent) {
23
- if (entry.expiresAt <= now) recent.delete(id);
63
+ for (const [mapKey, entry] of recent) {
64
+ if (entry.expiresAt <= now) {
65
+ deleteEntry(mapKey);
66
+ }
24
67
  }
25
- // If still over the cap, drop oldest insertions (Map preserves order).
26
- while (recent.size > maxItems) {
68
+ // If still over the item or byte cap, drop oldest insertions (Map preserves order).
69
+ while (recent.size > maxItems || totalBytes > maxBytes) {
27
70
  const oldest = recent.keys().next().value;
28
71
  if (oldest === undefined) break;
29
- recent.delete(oldest);
72
+ deleteEntry(oldest);
30
73
  }
31
74
  }
32
75
 
33
- export function configureRecentCache({ ttlMs: nextTtl, maxItems: nextMax } = {}) {
76
+ export function configureRecentCache({
77
+ ttlMs: nextTtl,
78
+ maxItems: nextMax,
79
+ maxBytes: nextMaxBytes,
80
+ maxEntryBytes: nextMaxEntryBytes,
81
+ } = {}) {
34
82
  if (Number.isFinite(nextTtl) && nextTtl > 0) ttlMs = nextTtl;
35
- if (Number.isFinite(nextMax) && nextMax > 0) maxItems = nextMax;
83
+ if (Number.isFinite(nextMax) && nextMax > 0) maxItems = Math.floor(nextMax);
84
+ if (Number.isFinite(nextMaxBytes) && nextMaxBytes > 0) maxBytes = Math.floor(nextMaxBytes);
85
+ if (Number.isFinite(nextMaxEntryBytes) && nextMaxEntryBytes > 0) {
86
+ maxEntryBytes = Math.floor(nextMaxEntryBytes);
87
+ }
88
+ gc();
89
+ }
90
+
91
+ export function getRecentCacheEpoch() {
92
+ return accountEpoch;
93
+ }
94
+
95
+ export function clearRecentMessages() {
96
+ accountEpoch += 1;
97
+ recent.clear();
98
+ totalBytes = 0;
99
+ return accountEpoch;
100
+ }
101
+
102
+ function normalizeEpochArg(candidate) {
103
+ if (typeof candidate === "number" && Number.isInteger(candidate)) return candidate;
104
+ if (
105
+ candidate &&
106
+ typeof candidate === "object" &&
107
+ typeof candidate.epoch === "number" &&
108
+ Number.isInteger(candidate.epoch)
109
+ ) {
110
+ return candidate.epoch;
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ function extractOutboundArgs(arg1, arg2, arg3, arg4) {
116
+ if (typeof arg1 === "string" && typeof arg2 === "string") {
117
+ return {
118
+ remoteJid: arg1,
119
+ id: arg2,
120
+ message: arg3,
121
+ expectedEpoch: normalizeEpochArg(arg4),
122
+ };
123
+ }
124
+ if (arg1 && typeof arg1 === "object") {
125
+ if (
126
+ arg1.key &&
127
+ typeof arg1.key === "object" &&
128
+ (arg2 === undefined || normalizeEpochArg(arg2) !== undefined)
129
+ ) {
130
+ return {
131
+ remoteJid: arg1.key.remoteJid,
132
+ id: arg1.key.id,
133
+ message: arg1.message,
134
+ expectedEpoch: normalizeEpochArg(arg2),
135
+ };
136
+ }
137
+ return {
138
+ remoteJid: arg1.remoteJid,
139
+ id: arg1.id,
140
+ message: arg2,
141
+ expectedEpoch: normalizeEpochArg(arg3),
142
+ };
143
+ }
144
+ if (typeof arg1 === "string" && arg2 && typeof arg2 === "object" && arg2.key?.remoteJid) {
145
+ return {
146
+ remoteJid: arg2.key.remoteJid,
147
+ id: arg1 || arg2.key.id,
148
+ message: arg2.message,
149
+ expectedEpoch: normalizeEpochArg(arg3),
150
+ };
151
+ }
152
+ return { remoteJid: null, id: null, message: null, expectedEpoch: undefined };
36
153
  }
37
154
 
38
- export function rememberMessage(id, value) {
39
- if (!id) return;
40
- const expiresAt = Date.now() + ttlMs;
41
- recent.set(id, { value, expiresAt });
42
- if (recent.size > maxItems) gc();
155
+ export function rememberMessage(arg1, arg2, arg3, arg4) {
156
+ try {
157
+ const { remoteJid, id, message, expectedEpoch } = extractOutboundArgs(arg1, arg2, arg3, arg4);
158
+ if (expectedEpoch !== undefined && expectedEpoch !== accountEpoch) return false;
159
+ if (typeof id !== "string" || !id) return false;
160
+ if (!message || typeof message !== "object") return false;
161
+ const chatJid = normalizeChatJid(remoteJid);
162
+ if (!chatJid) return false;
163
+
164
+ const bytes = proto.Message.encode(message).finish().length;
165
+ if (bytes > maxEntryBytes || bytes > maxBytes) {
166
+ return false;
167
+ }
168
+
169
+ const now = Date.now();
170
+ gc(now);
171
+
172
+ const mapKey = makeCacheKey(chatJid, id);
173
+ if (recent.has(mapKey)) {
174
+ deleteEntry(mapKey);
175
+ }
176
+
177
+ while (recent.size >= maxItems || totalBytes + bytes > maxBytes) {
178
+ const oldest = recent.keys().next().value;
179
+ if (oldest === undefined) break;
180
+ deleteEntry(oldest);
181
+ }
182
+
183
+ recent.set(mapKey, {
184
+ chatJid,
185
+ id,
186
+ message,
187
+ bytes,
188
+ expiresAt: now + ttlMs,
189
+ });
190
+ totalBytes += bytes;
191
+ return true;
192
+ } catch (err) {
193
+ logger.debug({ err: err?.message }, "[RecentCache] failed to cache outbound message");
194
+ return false;
195
+ }
43
196
  }
44
197
 
45
- export function recallMessage(id) {
46
- if (!id) return null;
47
- const entry = recent.get(id);
48
- if (!entry) return null;
49
- if (entry.expiresAt <= Date.now()) {
50
- recent.delete(id);
51
- return null;
198
+ function readEntry(chatJid, id, now) {
199
+ const mapKey = makeCacheKey(chatJid, id);
200
+ const entry = recent.get(mapKey);
201
+ if (!entry) return undefined;
202
+ if (entry.expiresAt <= now) {
203
+ deleteEntry(mapKey);
204
+ return undefined;
52
205
  }
53
- return entry.value;
206
+ return entry.message;
54
207
  }
55
208
 
56
- export function forgetMessage(id) {
57
- if (!id) return;
58
- recent.delete(id);
209
+ function resolveDirectChatAliases(chatJid, rawRemoteJid) {
210
+ const aliases = [];
211
+ const add = (candidate) => {
212
+ const norm = normalizeChatJid(candidate);
213
+ if (
214
+ norm &&
215
+ norm !== chatJid &&
216
+ !norm.endsWith("@g.us") &&
217
+ (isPnJid(norm) || isLidJid(norm)) &&
218
+ !aliases.includes(norm)
219
+ ) {
220
+ aliases.push(norm);
221
+ }
222
+ };
223
+
224
+ try {
225
+ if (isLidJid(chatJid)) {
226
+ const pn =
227
+ getPnForLid(chatJid) ||
228
+ (rawRemoteJid && rawRemoteJid !== chatJid ? getPnForLid(rawRemoteJid) : null);
229
+ if (pn) {
230
+ add(pn);
231
+ const normPn = normalizeChatJid(pn);
232
+ if (normPn) {
233
+ add(getLidForPn(normPn));
234
+ for (const lid of getLidsForPn(normPn)) add(lid);
235
+ }
236
+ }
237
+ } else if (isPnJid(chatJid)) {
238
+ add(getLidForPn(chatJid));
239
+ for (const lid of getLidsForPn(chatJid)) add(lid);
240
+ if (rawRemoteJid && rawRemoteJid !== chatJid) {
241
+ add(getLidForPn(rawRemoteJid));
242
+ }
243
+ }
244
+ } catch {}
245
+
246
+ return aliases;
59
247
  }
60
248
 
61
249
  // Used by Baileys getMessage; expects a `proto.IMessage` (or undefined).
62
250
  export async function getMessageFromRecent(key) {
63
- if (!key?.id) return undefined;
64
- const stored = recallMessage(key.id);
65
- if (!stored) return undefined;
66
- // Stored archive uses { message, ... } shape -- we only need .message
67
- return stored.message || stored.rawMessage || undefined;
251
+ if (!key || typeof key.id !== "string" || !key.id) return undefined;
252
+ if (typeof key.remoteJid !== "string" || !key.remoteJid) return undefined;
253
+
254
+ const chatJid = normalizeChatJid(key.remoteJid);
255
+ if (!chatJid) return undefined;
256
+
257
+ const now = Date.now();
258
+ const exact = readEntry(chatJid, key.id, now);
259
+ if (exact !== undefined) return exact;
260
+
261
+ // Group chats must match the exact group JID.
262
+ if (chatJid.endsWith("@g.us")) return undefined;
263
+ if (!isLidJid(chatJid) && !isPnJid(chatJid)) return undefined;
264
+
265
+ const rawRemoteJid = key.remoteJid.trim();
266
+ for (const aliasJid of resolveDirectChatAliases(chatJid, rawRemoteJid)) {
267
+ const found = readEntry(aliasJid, key.id, now);
268
+ if (found !== undefined) return found;
269
+ }
270
+
271
+ return undefined;
68
272
  }
69
273
 
70
274
  setInterval(() => gc(), 1000 * 60 * 5).unref?.();
@@ -1,3 +1,5 @@
1
+ const { t, withLang, currentLang, intlTag } = require("./i18n.cjs");
2
+
1
3
  const DAY_ALIASES = new Map([
2
4
  ["0", 0],
3
5
  ["7", 0],
@@ -44,8 +46,6 @@ const DAY_ALIASES = new Map([
44
46
  ["سبت", 6],
45
47
  ]);
46
48
 
47
- const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
48
- const WEEKDAYS_AR = ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"];
49
49
  // */N restarts at midnight; only these keep a gap of N across the day boundary.
50
50
  const HOURLY_INTERVALS = [1, 2, 3, 4, 6, 8, 12];
51
51
 
@@ -191,43 +191,71 @@ function recurrenceToCron(recurrence) {
191
191
  return { error: "kind" };
192
192
  }
193
193
 
194
- function recurrenceErrorMessage(error) {
195
- switch (error) {
196
- case "time":
197
- return "Invalid time";
198
- case "weekdays":
199
- return "Select at least one weekday";
200
- case "dayOfMonth":
201
- return "Day of month must be between 1 and 31";
202
- case "everyHours":
203
- return "Hours must be 1, 2, 3, 4, 6, 8 or 12";
204
- default:
205
- return "Invalid recurrence";
206
- }
194
+ const DESCRIBE_LANGS = new Set(["en", "ar", "pt-BR", "es-419"]);
195
+
196
+ function describeLang(lang) {
197
+ // Codes outside en, ar, pt-BR, and es-419 stay English.
198
+ return DESCRIBE_LANGS.has(lang) ? lang : "en";
207
199
  }
208
200
 
209
- function joinWeekdayNames(days, lang) {
210
- const names = days.map((day) => (lang === "ar" ? WEEKDAYS_AR[day] : WEEKDAYS[day]));
211
- if (lang === "ar") return names.join(" و");
201
+ function recurrenceErrorMessage(error, lang = "en") {
202
+ // The panel calls this with no reply language, so the default stays English.
203
+ return withLang(describeLang(lang), () => {
204
+ switch (error) {
205
+ case "time":
206
+ return t("bot.schedules.recurrence.errorTime");
207
+ case "weekdays":
208
+ return t("bot.schedules.recurrence.errorWeekdays");
209
+ case "dayOfMonth":
210
+ return t("bot.schedules.recurrence.errorDayOfMonth");
211
+ case "everyHours":
212
+ return t("bot.schedules.recurrence.errorEveryHours");
213
+ default:
214
+ return t("bot.schedules.recurrence.errorInvalid");
215
+ }
216
+ });
217
+ }
218
+
219
+ function joinWeekdayNames(days) {
220
+ const names = days.map((day) => t(`bot.schedules.recurrence.weekday${day}`));
212
221
  if (names.length === 1) return names[0];
213
- if (names.length === 2) return `${names[0]} and ${names[1]}`;
214
- return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
222
+ const and = t("bot.schedules.recurrence.weekdayAnd");
223
+ if (names.length === 2) return `${names[0]}${and}${names[1]}`;
224
+ const sep = t("bot.schedules.recurrence.weekdaySep");
225
+ return `${names.slice(0, -1).join(sep)}${and}${names[names.length - 1]}`;
215
226
  }
216
227
 
217
228
  function withZone(text, timezone) {
218
229
  return `${text} (${timezone})`;
219
230
  }
220
231
 
221
- function arabicEveryHours(n) {
222
- if (n === 1) return "كل ساعة";
223
- if (n === 2) return "كل ساعتين";
224
- if (n >= 3 && n <= 10) return `كل ${n} ساعات`;
225
- return `كل ${n} ساعة`;
232
+ // The old phrase used the plural noun for 3 to 10 only. CLDR "few" also
233
+ // covers 103 and 110, and those used the same phrase as 11.
234
+ function hourlyPluralCount(n) {
235
+ const category = new Intl.PluralRules(currentLang()).select(n);
236
+ if (category === "few" && (n < 3 || n > 10)) return 11;
237
+ return n;
238
+ }
239
+
240
+ // one and two name the interval and do not print the number.
241
+ function hourlyToken(n) {
242
+ const category = new Intl.PluralRules(currentLang()).select(n);
243
+ if (category === "one" || category === "two") return "";
244
+ return String(n);
245
+ }
246
+
247
+ function everyHoursPhrase(n, minute, lang = "en") {
248
+ return withLang(describeLang(lang), () =>
249
+ t("bot.schedules.recurrence.hourly", {
250
+ count: hourlyPluralCount(n),
251
+ n: hourlyToken(n),
252
+ minute,
253
+ }),
254
+ );
226
255
  }
227
256
 
228
- function describeRecurringCron(cronString, timezone, lang) {
229
- const ar = lang === "ar";
230
- const fallback = withZone(cronString || (ar ? "تكرار غير معروف" : "Unknown recurrence"), timezone);
257
+ function describeRecurringCron(cronString, timezone) {
258
+ const fallback = withZone(cronString || t("bot.schedules.recurrence.unknown"), timezone);
231
259
  const parts = String(cronString ?? "")
232
260
  .trim()
233
261
  .split(/\s+/);
@@ -240,22 +268,10 @@ function describeRecurringCron(cronString, timezone, lang) {
240
268
  const validHour = /^\d+$/.test(hourText) && hour >= 0 && hour <= 23;
241
269
 
242
270
  const everyHours = /^\*\/(\d+)$/.exec(hourText);
243
- if (
244
- validMinute &&
245
- everyHours &&
246
- dayOfMonth === "*" &&
247
- month === "*" &&
248
- dayText === "*"
249
- ) {
271
+ if (validMinute && everyHours && dayOfMonth === "*" && month === "*" && dayText === "*") {
250
272
  const n = Number(everyHours[1]);
251
273
  if (n >= 1 && n <= 12) {
252
- if (ar) {
253
- return withZone(`${arabicEveryHours(n)} عند الدقيقة ${minute}`, timezone);
254
- }
255
- return withZone(
256
- n === 1 ? `Every hour at minute ${minute}` : `Every ${n} hours at minute ${minute}`,
257
- timezone,
258
- );
274
+ return withZone(everyHoursPhrase(n, minute, currentLang()), timezone);
259
275
  }
260
276
  }
261
277
 
@@ -265,10 +281,7 @@ function describeRecurringCron(cronString, timezone, lang) {
265
281
  if (dayOfMonth !== "*" && dayText === "*") {
266
282
  const day = Number(dayOfMonth);
267
283
  if (/^\d+$/.test(dayOfMonth) && day >= 1 && day <= 31) {
268
- return withZone(
269
- ar ? `كل شهر في اليوم ${day} الساعة ${time}` : `Every month on day ${day} at ${time}`,
270
- timezone,
271
- );
284
+ return withZone(t("bot.schedules.recurrence.monthly", { day, time }), timezone);
272
285
  }
273
286
  return fallback;
274
287
  }
@@ -276,34 +289,32 @@ function describeRecurringCron(cronString, timezone, lang) {
276
289
  if (dayOfMonth !== "*") return fallback;
277
290
 
278
291
  if (dayText === "*") {
279
- return withZone(ar ? `يومياً الساعة ${time}` : `Daily at ${time}`, timezone);
292
+ return withZone(t("bot.schedules.recurrence.daily", { time }), timezone);
280
293
  }
281
294
 
282
295
  const days = dayText.split(",").map((token) => parseDayOfWeek(token.trim()));
283
296
  if (!days.length || days.some((day) => day === null)) return fallback;
284
297
  const unique = [...new Set(days)].sort((a, b) => a - b);
285
- const names = joinWeekdayNames(unique, ar ? "ar" : "en");
286
- if (ar) return withZone(`كل يوم ${names} الساعة ${time}`, timezone);
287
- if (unique.length === 1) return withZone(`Every ${names} at ${time}`, timezone);
288
- return withZone(`Every ${names} at ${time}`, timezone);
298
+ const names = joinWeekdayNames(unique);
299
+ return withZone(t("bot.schedules.recurrence.weekly", { days: names, time }), timezone);
289
300
  }
290
301
 
291
302
  function describeScheduledJob(job, timezone, lang = "en") {
292
- const ar = lang === "ar";
293
- if (job.type === "recurring") {
294
- return describeRecurringCron(job.cronString, timezone, ar ? "ar" : "en");
295
- }
296
-
297
- const date = new Date(job.date);
298
- if (!Number.isFinite(date.getTime())) return ar ? "تاريخ غير صالح" : "Invalid date";
299
- return withZone(
300
- new Intl.DateTimeFormat(ar ? "ar-EG" : "en-GB", {
301
- dateStyle: "medium",
302
- timeStyle: "short",
303
- timeZone: timezone,
304
- }).format(date),
305
- timezone,
306
- );
303
+ const code = describeLang(lang);
304
+ return withLang(code, () => {
305
+ if (job.type === "recurring") return describeRecurringCron(job.cronString, timezone);
306
+
307
+ const date = new Date(job.date);
308
+ if (!Number.isFinite(date.getTime())) return t("bot.schedules.recurrence.invalidDate");
309
+ return withZone(
310
+ new Intl.DateTimeFormat(intlTag(code), {
311
+ dateStyle: "medium",
312
+ timeStyle: "short",
313
+ timeZone: timezone,
314
+ }).format(date),
315
+ timezone,
316
+ );
317
+ });
307
318
  }
308
319
 
309
320
  module.exports = {
@@ -312,5 +323,6 @@ module.exports = {
312
323
  parseTime,
313
324
  recurrenceToCron,
314
325
  recurrenceErrorMessage,
326
+ everyHoursPhrase,
315
327
  describeScheduledJob,
316
328
  };
@@ -1,8 +1,7 @@
1
1
  // CommonJS shim around sendBotMessage.esm.js so .cjs commands can use it.
2
2
  // We lazy-import the ESM module on first call and cache the resolved exports.
3
3
 
4
- const logger = require("./logger.cjs");
5
- const { tr } = require("./i18n.cjs");
4
+ const { t } = require("./i18n.cjs");
6
5
 
7
6
  let cached = null;
8
7
 
@@ -13,35 +12,21 @@ async function getModule() {
13
12
  }
14
13
 
15
14
  async function sendBotMessage(sock, jid, content, options = {}) {
16
- try {
17
- const mod = await getModule();
18
- return await mod.sendBotMessage(sock, jid, content, options);
19
- } catch (err) {
20
- logger.error({ err }, "[sendBotMessage.cjs] fell back to raw sendMessage");
21
- const opts = {};
22
- if (options?.quote !== false) {
23
- const quoted = options?.quoted || options?.replyTo;
24
- if (quoted) opts.quoted = quoted;
25
- }
26
- return sock.sendMessage(jid, content, opts);
27
- }
15
+ // Import, cancellation, routing and send errors must propagate. A raw retry
16
+ // could duplicate delivery or bypass the failed helper's safety checks.
17
+ const mod = await getModule();
18
+ return mod.sendBotMessage(sock, jid, content, options);
28
19
  }
29
20
 
30
- async function sendBotError(sock, jid, err, lead = tr("Something went wrong", "حدث خطأ"), options = {}) {
31
- try {
32
- const mod = await getModule();
33
- return await mod.sendBotError(sock, jid, err, lead, options);
34
- } catch (innerErr) {
35
- logger.error({ err: innerErr }, "[sendBotMessage.cjs] error helper failed");
36
- const name = err?.name || "Error";
37
- const message = err?.message || String(err);
38
- return sock.sendMessage(jid, {
39
- text: tr(
40
- `❌ *${lead}*\n\n*Type:* \`${name}\`\n*Details:* ${message}`,
41
- `❌ *${lead}*\n\n*النوع:* \`${name}\`\n*التفاصيل:* ${message}`,
42
- ),
43
- });
44
- }
21
+ async function sendBotError(
22
+ sock,
23
+ jid,
24
+ err,
25
+ lead = t("bot.core.sendBotMessage.defaultLead"),
26
+ options = {},
27
+ ) {
28
+ const mod = await getModule();
29
+ return mod.sendBotError(sock, jid, err, lead, options);
45
30
  }
46
31
 
47
32
  module.exports = { sendBotMessage, sendBotError };