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
@@ -3,16 +3,22 @@ import { createRequire } from "module";
3
3
  import { dirname, join } from "path";
4
4
  import { fileURLToPath } from "url";
5
5
  import { checkBotAdmin, checkCommandPermission } from "../middleware/permissions.middleware.js";
6
- import { resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
6
+ import { getCached, getRosterVersion, resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
7
7
  import { sendBotMessage } from "../utils/sendBotMessage.esm.js";
8
+ import { accountEpoch as readAccountEpoch } from "../utils/storage.esm.js";
8
9
 
9
10
  const __filename = fileURLToPath(import.meta.url);
10
11
  const __dirname = dirname(__filename);
11
12
  const require = createRequire(import.meta.url);
12
13
  const logger = require("../utils/logger.cjs");
13
14
  const runtimeConfig = require("../config/runtime-config.cjs");
14
- const { localize, bothLanguages } = require("../utils/commandDocs.cjs");
15
- const { langForCommand, withLang, tr } = require("../utils/i18n.cjs");
15
+ const settings = require("../config/settings.cjs");
16
+ const { localize, allLanguages, attachCommandDocs } = require("../utils/commandDocs.cjs");
17
+ const { langForCommand, withLang, t } = require("../utils/i18n.cjs");
18
+ const { parseCommandText, parseCommandTextV1 } = require("../messaging/parser.cjs");
19
+ const { createMessage, renderMessage, stampWatermark } = require("../messaging/message.cjs");
20
+ const { routeSend, canonicalJid } = require("../messaging/router.cjs");
21
+ const { withCommand } = require("../utils/commandContext.cjs");
16
22
 
17
23
  // Commands collection (keyed by both names and aliases)
18
24
  const commands = new Map();
@@ -66,44 +72,110 @@ const EDIT_IN_PLACE_EXCLUDE = new Set([
66
72
  // * everything else: `sock.sendMessage(jid, content)` automatically adds
67
73
  // `quoted: msg` so the reply threads under the command.
68
74
  // Every other method (groupMetadata, etc.) is forwarded untouched.
69
- function wrapSockWithReply(sock, originalMsg, editInPlace = false) {
75
+ function wrapSockWithReply(sock, originalMsg, editInPlace = false, commandName = "") {
70
76
  const chatJid = originalMsg.key.remoteJid;
77
+ const source = canonicalJid(chatJid) || chatJid;
78
+ const allowed = new Set([source]);
71
79
  let editUsed = false;
80
+ let noticeSent = false;
72
81
 
73
82
  return new Proxy(sock, {
74
83
  get(target, prop, receiver) {
75
84
  if (prop === "sendMessage") {
76
85
  return async (jid, content, options) => {
77
- // Try to edit the trigger message in place for the first eligible
78
- // text reply. We can only edit messages we sent ourselves.
86
+ const opts = options ? { ...options } : {};
87
+ const signal = opts.signal;
88
+ signal?.throwIfAborted();
89
+ const levix = opts.levix || null;
90
+ delete opts.levix;
91
+
92
+ const requested = canonicalJid(jid) || source;
93
+ const protocol = Boolean(content && (content.edit || content.delete || content.react));
94
+ if (protocol) {
95
+ // An edit stays on a chat this command already sent to. It cannot
96
+ // open a new destination.
97
+ if (!allowed.has(requested)) return { key: null, refused: true };
98
+ const outgoing =
99
+ content.edit && levix ? stampText(content, commandName, levix) : content;
100
+ return target.sendMessage.call(target, jid, outgoing, opts);
101
+ }
102
+
103
+ const plan = routeSend({
104
+ sourceJid: chatJid,
105
+ requestedJid: jid,
106
+ senderJid: originalMsg.key.participant || originalMsg.key.remoteJid,
107
+ commandName,
108
+ category: levix?.category || "result",
109
+ sensitivity: levix?.sensitivity || "source",
110
+ terminal: levix?.terminal === true,
111
+ });
112
+
113
+ if (!plan.allow) {
114
+ if (!noticeSent) {
115
+ noticeSent = true;
116
+ const notice = renderMessage(
117
+ createMessage({
118
+ messageKey: plan.noticeKey,
119
+ category: "system",
120
+ context: { sourceChat: chatJid, command: commandName },
121
+ sensitivity: "operational",
122
+ deliveryPolicy: { terminal: true },
123
+ }),
124
+ );
125
+ try {
126
+ await target.sendMessage.call(
127
+ target,
128
+ chatJid,
129
+ { text: notice, linkPreview: null },
130
+ { quoted: originalMsg, ...(signal ? { signal } : {}) },
131
+ );
132
+ } catch (error) {
133
+ logger.warn({ err: error?.message }, "[router] refusal notice failed");
134
+ }
135
+ }
136
+ return { key: null, refused: true };
137
+ }
138
+
139
+ allowed.add(plan.destination);
140
+ const outgoing = stampText(content, commandName, levix);
141
+ const sameChat = plan.destination === source;
142
+
143
+ // Edit the trigger only when the reply stays in this chat. A routed
144
+ // reply must not rewrite the group message it is leaving.
79
145
  const eligibleForEdit =
80
146
  editInPlace &&
147
+ sameChat &&
81
148
  !editUsed &&
82
149
  originalMsg.key.fromMe &&
83
- jid === chatJid &&
84
- content &&
85
- typeof content === "object" &&
86
- typeof content.text === "string" &&
87
- !content.edit;
150
+ requested === source &&
151
+ outgoing &&
152
+ typeof outgoing === "object" &&
153
+ typeof outgoing.text === "string" &&
154
+ !outgoing.edit;
88
155
 
89
156
  if (eligibleForEdit) {
90
157
  editUsed = true;
91
158
  try {
92
- return await target.sendMessage.call(target, jid, {
93
- ...content,
94
- edit: originalMsg.key,
95
- });
159
+ return await target.sendMessage.call(
160
+ target,
161
+ chatJid,
162
+ { ...outgoing, edit: originalMsg.key },
163
+ signal ? { signal } : undefined,
164
+ );
96
165
  } catch {
97
- // Editing failed (too old, not ours after all, …) — fall through
98
- // to a normal quoted send so the user still gets a reply.
166
+ // Editing failed — fall through to a normal send.
99
167
  }
100
168
  }
101
169
 
102
- const opts = options ? { ...options } : {};
103
- if (opts.quoted === undefined) {
104
- opts.quoted = originalMsg;
170
+ if (sameChat) {
171
+ if (opts.quoted === undefined) opts.quoted = originalMsg;
172
+ } else if ("quoted" in opts) {
173
+ delete opts.quoted;
105
174
  }
106
- return target.sendMessage.call(target, jid, content, opts);
175
+ signal?.throwIfAborted();
176
+ const sent = await target.sendMessage.call(target, plan.destination, outgoing, opts);
177
+ if (sent?.key && !sent.key.remoteJid) sent.key.remoteJid = plan.destination;
178
+ return sent;
107
179
  };
108
180
  }
109
181
  const value = Reflect.get(target, prop, receiver);
@@ -112,6 +184,20 @@ function wrapSockWithReply(sock, originalMsg, editInPlace = false) {
112
184
  });
113
185
  }
114
186
 
187
+ function stampText(content, commandName, levix) {
188
+ if (!content || typeof content !== "object" || typeof content.text !== "string") return content;
189
+ if (content.image || content.video || content.audio || content.document || content.sticker) {
190
+ return content;
191
+ }
192
+ const text = stampWatermark(content.text, {
193
+ commandName,
194
+ category: levix?.category || "result",
195
+ exact: levix?.exact === true || levix?.sensitivity === "secret",
196
+ });
197
+ if (text === content.text) return content;
198
+ return { ...content, text };
199
+ }
200
+
115
201
  /**
116
202
  * Point every alias of `command` at it. The effective list is the dashboard
117
203
  * override when there is one, otherwise what the command file declared.
@@ -168,12 +254,11 @@ export function getCommandCatalog() {
168
254
  name: command.name,
169
255
  key,
170
256
  category: command.__category || "general",
171
- // Strings, as the dashboard has always had them (English first), plus
172
- // both languages so it can follow its own UI language.
257
+ // Keep the English strings for existing clients and expose all locales.
173
258
  description: localize(command.description, "en"),
174
- descriptions: bothLanguages(command.description),
259
+ descriptions: allLanguages(command.description),
175
260
  usage: command.usage ? localize(command.usage, "en") : null,
176
- usages: command.usage ? bothLanguages(command.usage) : null,
261
+ usages: command.usage ? allLanguages(command.usage) : null,
177
262
  chat: command.chat || "all",
178
263
  declaredAliases: command.__declaredAliases || [],
179
264
  aliases: runtimeConfig.getAliases(command.name, command.__declaredAliases || []),
@@ -219,6 +304,10 @@ export async function loadCommands() {
219
304
  }
220
305
  }
221
306
 
307
+ // Names are registered in directory order, so an alias of an earlier file
308
+ // can occupy a later command's name. Rebuild once names all exist: a real
309
+ // command keeps its name, and the conflicting alias is dropped.
310
+ rebuildCommandIndex();
222
311
  logger.info(
223
312
  `[Commands] Loaded ${commandList.size} commands (${commands.size} entries with aliases)`,
224
313
  );
@@ -254,6 +343,7 @@ function registerCommand(command, label, category) {
254
343
  try {
255
344
  if (!command?.name) return;
256
345
 
346
+ attachCommandDocs(command, category);
257
347
  command.__category = category || "general";
258
348
  // What the FILE declares, kept aside so a dashboard override can be
259
349
  // cleared back to it later (command.aliases itself is what we index).
@@ -280,43 +370,83 @@ export function getAliasIndex() {
280
370
  }
281
371
 
282
372
  // Handle command execution
283
- export async function handleCommand(sock, msg, body) {
284
- const isGroup = msg.key.remoteJid.endsWith("@g.us");
285
-
373
+ function parseBody(body) {
286
374
  const prefix = runtimeConfig.getPrefix();
287
- if (!body.startsWith(prefix)) return false;
375
+ const useV1 = settings.get("command_parser") === "v1";
376
+ const parse = useV1 ? parseCommandTextV1 : parseCommandText;
377
+ return { prefix, useV1, parsed: parse(body, { prefix }) };
378
+ }
288
379
 
289
- const args = body.slice(prefix.length).trim().split(/\s+/);
290
- const invokedName = args.shift().toLowerCase();
380
+ export async function handleCommand(sock, msg, body, accountEpoch) {
381
+ const epoch = Number.isInteger(accountEpoch) ? accountEpoch : readAccountEpoch();
382
+ const isGroup = msg.key.remoteJid.endsWith("@g.us");
383
+ const { prefix, useV1, parsed } = parseBody(body);
384
+ if (parsed.kind !== "command") return false;
385
+
386
+ const args = parsed.args;
387
+ const invokedName = parsed.name;
291
388
  const command = commands.get(invokedName);
292
- if (!command) return false;
389
+ if (!command) {
390
+ // v1 stayed silent, and a token that is not a command name never reaches
391
+ // here. v2 answers a real typo so the person gets an example.
392
+ if (useV1) return false;
393
+ const text = renderMessage(
394
+ createMessage({
395
+ messageKey: "bot.core.commandHandler.unknown",
396
+ category: "error",
397
+ parameters: { name: invokedName, prefix },
398
+ context: { sourceChat: msg.key.remoteJid },
399
+ sensitivity: "operational",
400
+ deliveryPolicy: { terminal: true },
401
+ }),
402
+ );
403
+ await sendBotMessage(sock, msg.key.remoteJid, { text }, { replyTo: msg });
404
+ return true;
405
+ }
293
406
 
294
407
  // Everything this command sends goes out in one language: the bot's, or in
295
408
  // "auto" the one this message is written in — judged on the arguments, not
296
409
  // on the command's own keywords (see utils/i18n.cjs).
297
410
  const aliases = runtimeConfig.getAliases(command.name, command.__declaredAliases || []);
298
411
  const lang = langForCommand(command, args, aliases);
299
- return withLang(lang, () => runCommand(sock, msg, body, { command, args, invokedName, isGroup }));
412
+ return withLang(lang, () =>
413
+ runCommand(sock, msg, body, {
414
+ command,
415
+ args,
416
+ invokedName,
417
+ isGroup,
418
+ rawRemainder: parsed.rawRemainder,
419
+ accountEpoch: epoch,
420
+ }),
421
+ );
300
422
  }
301
423
 
302
- async function runCommand(sock, msg, body, { command, args, invokedName, isGroup }) {
424
+ async function runCommand(
425
+ sock,
426
+ msg,
427
+ body,
428
+ { command, args, invokedName, isGroup, rawRemainder, accountEpoch },
429
+ ) {
303
430
  // Turned off from the dashboard. Answered rather than ignored so the user
304
431
  // knows the command exists and isn't broken.
305
432
  if (runtimeConfig.isDisabled(command.name)) {
306
433
  await sendBotMessage(
307
434
  sock,
308
435
  msg.key.remoteJid,
309
- { text: tr("⛔ This command is turned off right now.", "⛔ هذا الأمر معطّل حاليًا.") },
436
+ { text: t("bot.core.commandHandler.disabled") },
310
437
  { replyTo: msg },
311
438
  );
312
439
  return true;
313
440
  }
314
441
 
315
442
  try {
316
- // Cache-first: a live query only when no cached metadata exists yet (see
317
- // utils/groupMetadataCache.cjs — this used to be one network round-trip
318
- // per command attempt in every group).
319
- const groupMetadata = isGroup ? await resolveGroupMetadata(sock, msg.key.remoteJid) : null;
443
+ // One read. Authorization uses a fresh or live roster and denies when the
444
+ // only copy is stale. The command body keeps the last known roster so a
445
+ // failed refresh still protects the last-known admins.
446
+ const jid = msg.key.remoteJid;
447
+ const authMetadata = isGroup ? await resolveGroupMetadata(sock, jid, { fresh: true }) : null;
448
+ const groupMetadata = isGroup ? authMetadata || getCached(jid) || null : null;
449
+ const rosterVersion = isGroup ? getRosterVersion(jid) : undefined;
320
450
 
321
451
  if (command.name !== "group") {
322
452
  // Enforce the `chat` constraint declared by the command. Until now this
@@ -327,7 +457,7 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
327
457
  sock,
328
458
  msg.key.remoteJid,
329
459
  {
330
- text: tr("⚠️ This command only works in groups.", "⚠️ هذا الأمر يعمل في المجموعات فقط."),
460
+ text: t("bot.core.commandHandler.groupsOnly"),
331
461
  },
332
462
  { replyTo: msg },
333
463
  );
@@ -338,10 +468,7 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
338
468
  sock,
339
469
  msg.key.remoteJid,
340
470
  {
341
- text: tr(
342
- "⚠️ This command only works in private chats.",
343
- "⚠️ هذا الأمر يعمل في المحادثات الخاصة فقط.",
344
- ),
471
+ text: t("bot.core.commandHandler.privateOnly"),
345
472
  },
346
473
  { replyTo: msg },
347
474
  );
@@ -353,7 +480,7 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
353
480
  // `!kick` directly is gated exactly like running `!group kick`.
354
481
  const permissionKey = command.__category === "group" ? `group:${command.name}` : command.name;
355
482
 
356
- const permissionCheck = checkCommandPermission(permissionKey, msg, groupMetadata, sock);
483
+ const permissionCheck = checkCommandPermission(permissionKey, msg, authMetadata, sock);
357
484
 
358
485
  if (!permissionCheck.hasPermission) {
359
486
  await sendBotMessage(
@@ -370,25 +497,19 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
370
497
  sock,
371
498
  msg.key.remoteJid,
372
499
  {
373
- text: tr(
374
- "⚠️ You need to be a group admin to use this command.",
375
- "⚠️ هذا الأمر يتطلب أن تكون مشرفًا.",
376
- ),
500
+ text: t("bot.core.commandHandler.adminRequired"),
377
501
  },
378
502
  { replyTo: msg },
379
503
  );
380
504
  return true;
381
505
  }
382
506
 
383
- if (command.botAdminRequired && !checkBotAdmin(groupMetadata, sock)) {
507
+ if (command.botAdminRequired && !checkBotAdmin(authMetadata, sock)) {
384
508
  await sendBotMessage(
385
509
  sock,
386
510
  msg.key.remoteJid,
387
511
  {
388
- text: tr(
389
- "⚠️ I need to be a group admin to do that.",
390
- "⚠️ يجب أن أكون مشرفًا لتنفيذ هذا الأمر.",
391
- ),
512
+ text: t("bot.core.commandHandler.botAdminRequired"),
392
513
  },
393
514
  { replyTo: msg },
394
515
  );
@@ -403,6 +524,10 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
403
524
  canonicalName: command.name,
404
525
  isAlias: invokedName !== command.name,
405
526
  groupMetadata,
527
+ authGroupMetadata: authMetadata,
528
+ rawRemainder: rawRemainder || "",
529
+ accountEpoch,
530
+ ...(isGroup ? { rosterVersion } : {}),
406
531
  };
407
532
 
408
533
  // Wrap the socket so legacy commands that still call sock.sendMessage
@@ -412,8 +537,14 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
412
537
  // Action/confirmation commands additionally edit the trigger message in
413
538
  // place instead of posting a second message (see EDIT_IN_PLACE_EXCLUDE).
414
539
  const editInPlace = !EDIT_IN_PLACE_EXCLUDE.has(command.name);
415
- const proxiedSock = wrapSockWithReply(sock, msg, editInPlace);
416
- await command.execute(proxiedSock, msg, args, body, groupMetadata, ctx);
540
+ const proxiedSock = wrapSockWithReply(sock, msg, editInPlace, command.name);
541
+ if (readAccountEpoch() !== accountEpoch) {
542
+ logger.debug("[Command] skipped account work after account change");
543
+ return true;
544
+ }
545
+ await withCommand(command.name, () =>
546
+ command.execute(proxiedSock, msg, args, body, groupMetadata, ctx),
547
+ );
417
548
  return true;
418
549
  } catch (error) {
419
550
  logger.error({ err: error, command: invokedName }, "Error executing command");
@@ -423,14 +554,10 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
423
554
  sock,
424
555
  msg.key.remoteJid,
425
556
  {
426
- text: tr(
427
- `❌ *The command failed*\n\n*Type:* \`${error.name || "Error"}\`\n*Details:* ${
428
- error.message || "unknown"
429
- }`,
430
- `❌ *فشل تنفيذ الأمر*\n\n*النوع:* \`${error.name || "Error"}\`\n*التفاصيل:* ${
431
- error.message || "غير معروف"
432
- }`,
433
- ),
557
+ text: t("bot.core.commandHandler.failed", {
558
+ name: error.name || "Error",
559
+ details: error.message || t("bot.core.commandHandler.unknownDetails"),
560
+ }),
434
561
  },
435
562
  { replyTo: msg },
436
563
  );
@@ -4,7 +4,7 @@ import { getGroupSettings } from "../utils/storage.esm.js";
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
6
  const logger = require("../utils/logger.cjs");
7
- const { tr } = require("../utils/i18n.cjs");
7
+ const { t } = require("../utils/i18n.cjs");
8
8
  const { buildModerationSummary } = require("../utils/moderationSummary.cjs");
9
9
  const { resolveModerationPolicy } = require("../services/moderationPolicy.cjs");
10
10
  const { clearMemberModeration } = require("../utils/moderationAction.cjs");
@@ -20,10 +20,50 @@ function participantIdentities(participant) {
20
20
  return ids;
21
21
  }
22
22
 
23
+ // Baileys rc14 sends group-participants.update participants as objects
24
+ // ({ id, phoneNumber?, lid?, username?, admin }, Socket/messages-recv.js:637);
25
+ // older builds sent the bare JID string. The welcome path only needs the JID,
26
+ // and calling .split() on the object is what used to throw inside the try/catch
27
+ // and swallow every welcome message.
28
+ function participantJid(participant) {
29
+ if (typeof participant === "string") return participant || null;
30
+ if (!participant || typeof participant !== "object") return null;
31
+ const { id } = participant;
32
+ return typeof id === "string" && id ? id : null;
33
+ }
34
+
35
+ // rc14 emits 'group.join-request' with { id, participant, participantPn,
36
+ // action: "created" | "revoked" | "rejected", method }
37
+ // (Utils/process-message.js:496). Older builds passed
38
+ // { type: "request", jid, from }. Both shapes are read here, and the requester
39
+ // is resolved through participantJid() so an object and a string behave alike.
40
+ function joinRequestFields(request) {
41
+ if (!request || typeof request !== "object") return null;
42
+ const legacy = request.type === "request";
43
+ const pending = legacy || request.action === "created";
44
+ if (!pending) return null;
45
+
46
+ const groupId = request.jid || request.id;
47
+ const participantId =
48
+ participantJid(request.from) ||
49
+ participantJid(request.participant) ||
50
+ participantJid(request.participantPn);
51
+ if (!groupId || !participantId) return null;
52
+
53
+ return { groupId, participantId };
54
+ }
55
+
23
56
  // Handle group participant updates (join/leave)
24
57
  export async function handleGroupParticipantsUpdate(sock, update) {
25
58
  const { id, participants, action } = update;
26
- logger.info({ update }, "Received group participants update");
59
+ logger.info(
60
+ { action, count: Array.isArray(participants) ? participants.length : 0 },
61
+ "Received group participants update",
62
+ );
63
+ logger.debugOnly.info(
64
+ { group: id, action, count: Array.isArray(participants) ? participants.length : 0 },
65
+ "Received group participants update",
66
+ );
27
67
 
28
68
  if (action === "remove" || action === "leave") {
29
69
  try {
@@ -36,12 +76,14 @@ export async function handleGroupParticipantsUpdate(sock, update) {
36
76
  }
37
77
  }
38
78
  } catch (error) {
39
- logger.error({ err: error, update }, "Error clearing moderation on leave");
79
+ logger.error({ err: error }, "Error clearing moderation on leave");
80
+ logger.debugOnly.error({ err: error, update }, "Error clearing moderation on leave");
40
81
  }
41
82
  }
42
83
 
43
84
  if (action !== "add") {
44
- logger.info(`[Group] ${action} action for ${id}`);
85
+ logger.info(`[Group] ${action} action handled`);
86
+ logger.debugOnly.info({ group: id }, `[Group] ${action} action handled`);
45
87
  return;
46
88
  }
47
89
 
@@ -50,27 +92,35 @@ export async function handleGroupParticipantsUpdate(sock, update) {
50
92
  const welcomeConfig = settings?.welcome_system;
51
93
 
52
94
  if (!welcomeConfig || !welcomeConfig.enabled || welcomeConfig.messages.length === 0) {
53
- logger.warn(`[Group] Welcome system disabled or no messages for ${id}`);
95
+ logger.warn("[Group] Welcome system disabled or no messages");
96
+ logger.debugOnly.warn({ group: id }, "[Group] Welcome system disabled or no messages");
54
97
  return;
55
98
  }
56
99
 
57
100
  // Send welcome message to each new participant
58
- for (const participant of participants) {
101
+ for (const participant of participants || []) {
102
+ const participantId = participantJid(participant);
103
+ if (!participantId) {
104
+ logger.warn("[Group] Welcome skipped: participant has no JID");
105
+ continue;
106
+ }
107
+
59
108
  const randomIndex = Math.floor(Math.random() * welcomeConfig.messages.length);
60
109
  const welcomeMessage = welcomeConfig.messages[randomIndex];
61
110
 
62
- const welcomeText = welcomeMessage.replace(/\${user}/g, `@${participant.split("@")[0]}`);
111
+ const welcomeText = welcomeMessage.replace(/\${user}/g, `@${participantId.split("@")[0]}`);
63
112
  const summary = buildModerationSummary(settings);
64
113
  const finalMessage = summary ? `${welcomeText}\n\n${summary}` : welcomeText;
65
114
 
66
115
  await delay(1000);
67
116
  await sock.sendMessage(id, {
68
117
  text: finalMessage,
69
- mentions: [participant],
118
+ mentions: [participantId],
70
119
  });
71
120
  }
72
121
  } catch (error) {
73
- logger.error({ err: error, update }, "Error in group-participants.update event");
122
+ logger.error({ err: error }, "Error in group-participants.update event");
123
+ logger.debugOnly.error({ err: error, update }, "Error in group-participants.update event");
74
124
  }
75
125
  }
76
126
 
@@ -78,11 +128,15 @@ export async function handleGroupParticipantsUpdate(sock, update) {
78
128
  export async function handleGroupJoinRequests(sock, events) {
79
129
  logger.info({ events }, "Received group join request update");
80
130
 
81
- for (const request of events) {
82
- if (request.type !== "request") continue;
131
+ // rc14 emits one object per 'group.join-request' event, while the older
132
+ // 'group-requests.update' delivered an array. Accept either.
133
+ const requests = Array.isArray(events) ? events : events ? [events] : [];
83
134
 
84
- const groupId = request.jid;
85
- const participantId = request.from;
135
+ for (const request of requests) {
136
+ const fields = joinRequestFields(request);
137
+ if (!fields) continue;
138
+
139
+ const { groupId, participantId } = fields;
86
140
 
87
141
  try {
88
142
  const settings = getGroupSettings(groupId);
@@ -90,14 +144,20 @@ export async function handleGroupJoinRequests(sock, events) {
90
144
  if (settings?.join_requests?.auto_approve_enabled) {
91
145
  logger.info(`[Auto-Approve] Approving ${participantId} for group ${groupId}`);
92
146
 
93
- await sock.groupRequestUpdate(groupId, participantId, "approve");
147
+ // rc14 names the action groupRequestParticipantsUpdate(jid, users,
148
+ // action); the older single-participant method is kept as a fallback
149
+ // for a socket that still exposes it.
150
+ if (typeof sock.groupRequestParticipantsUpdate === "function") {
151
+ await sock.groupRequestParticipantsUpdate(groupId, [participantId], "approve");
152
+ } else {
153
+ await sock.groupRequestUpdate(groupId, participantId, "approve");
154
+ }
94
155
 
95
156
  await delay(500);
96
157
  await sock.sendMessage(groupId, {
97
- text: tr(
98
- `✅ @${participantId.split("@")[0]}'s join request was approved automatically.`,
99
- `✅ تم قبول طلب انضمام @${participantId.split("@")[0]} تلقائيًا.`,
100
- ),
158
+ text: t("bot.moderation.groupHandler.joinRequestApproved", {
159
+ member: participantId.split("@")[0],
160
+ }),
101
161
  mentions: [participantId],
102
162
  });
103
163
  }