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,4 +1,4 @@
1
- const { tr } = require("../utils/i18n.cjs");
1
+ const { t } = require("../utils/i18n.cjs");
2
2
  const { createStatus } = require("../utils/statusMessage.cjs");
3
3
  const {
4
4
  targetOf,
@@ -19,14 +19,6 @@ const toimage = require("./toimage.cjs");
19
19
  module.exports = {
20
20
  name: "sticker",
21
21
  aliases: ["s", "ملصق", "tosticker"],
22
- description: {
23
- en: "Create a sticker from an image, GIF or video.",
24
- ar: "ينشئ ملصقًا من صورة أو صورة متحركة أو فيديو.",
25
- },
26
- usage: {
27
- en: "sticker [crop] [nobg] (attach an image, GIF or video)\nsticker [crop] [nobg] (reply to media)\nsticker (reply to a sticker for PNG)",
28
- ar: "sticker [قص] [بدون-خلفية] (أرفق صورة أو صورة متحركة أو فيديو)\nsticker [قص] [بدون-خلفية] (رد على وسائط)\nsticker (رد على ملصق لصورة PNG)",
29
- },
30
22
  keywords: ["crop", "قص", "nobg", "بدون-خلفية"],
31
23
  chat: "all",
32
24
  async execute(sock, msg, args = []) {
@@ -38,7 +30,7 @@ module.exports = {
38
30
  const who = await ownerModule.forMessage(msg, sock);
39
31
  if (!who.key) {
40
32
  return sock.sendMessage(jid, {
41
- text: tr("I couldn't identify the sender.", "تعذّر تحديد هوية المرسل."),
33
+ text: t("bot.stickers.sticker.senderUnknown"),
42
34
  });
43
35
  }
44
36
  const target = targetOf(msg);
@@ -60,12 +52,9 @@ module.exports = {
60
52
  }
61
53
  const buffer = await downloadTarget(target);
62
54
  if (!media.sniff(buffer)) throw new StickerError("UNSUPPORTED_TYPE");
63
- status = await createStatus(
64
- sock,
65
- jid,
66
- tr("🎨 Creating sticker...", "🎨 جارٍ إنشاء الملصق..."),
67
- { replyTo: msg },
68
- );
55
+ status = await createStatus(sock, jid, t("bot.stickers.sticker.creating"), {
56
+ replyTo: msg,
57
+ });
69
58
  if (library.hasRoom(who)) {
70
59
  const { promise } = studio.createFromBuffer({
71
60
  owner: who,
@@ -1,4 +1,4 @@
1
- const { tr } = require("../utils/i18n.cjs");
1
+ const { t } = require("../utils/i18n.cjs");
2
2
  const { isolate } = require("../utils/bidi.cjs");
3
3
  const { BOT_PAGE_SIZE } = require("../stickers/limits.cjs");
4
4
  const { StickerError } = require("../stickers/errors.cjs");
@@ -41,14 +41,6 @@ function parse(args) {
41
41
  module.exports = {
42
42
  name: "stickers",
43
43
  aliases: ["ملصقاتي"],
44
- description: {
45
- en: "Browse your recent, favorite or packed stickers.",
46
- ar: "يعرض ملصقاتك الحديثة أو المفضلة أو الموجودة في حزمة.",
47
- },
48
- usage: {
49
- en: "stickers [page]\nstickers recent [page]\nstickers favorites [page]\nstickers pack <name> [page]",
50
- ar: "stickers [الصفحة]\nstickers الأحدث [الصفحة]\nstickers المفضلة [الصفحة]\nstickers حزمة <الاسم> [الصفحة]",
51
- },
52
44
  keywords: ["recent", "الأحدث", "favorites", "المفضلة", "pack", "حزمة"],
53
45
  chat: "all",
54
46
  async execute(sock, msg, args = []) {
@@ -56,15 +48,15 @@ module.exports = {
56
48
  const who = await ownerModule.forMessage(msg, sock);
57
49
  if (!who.key)
58
50
  return sock.sendMessage(jid, {
59
- text: tr("I couldn't identify the sender.", "تعذّر تحديد هوية المرسل."),
51
+ text: t("bot.stickers.stickers.senderUnknown"),
60
52
  });
61
53
  try {
62
54
  const selected = parse(args);
63
55
  const query = { limit: BOT_PAGE_SIZE };
64
- let label = tr("Recent stickers", "الملصقات الحديثة");
56
+ let label = t("bot.stickers.stickers.recent");
65
57
  if (selected.mode === "favorites") {
66
58
  query.filter = "favorites";
67
- label = tr("Favorite stickers", "الملصقات المفضلة");
59
+ label = t("bot.stickers.stickers.favorites");
68
60
  } else if (selected.mode === "pack") {
69
61
  // A trailing number is a page unless the whole text names an existing
70
62
  // pack (a pack can itself end in a number: "عيد 2").
@@ -89,10 +81,10 @@ module.exports = {
89
81
  const { items, total } = library.listStickers(who, query);
90
82
  if (!total)
91
83
  return sock.sendMessage(jid, {
92
- text: tr(
93
- `No stickers here yet. Reply to media with ${commandHint("sticker")} or ${commandHint("pack", "<name>")} to save one.`,
94
- `لا توجد ملصقات هنا بعد. رد على وسائط بالأمر ${commandHint("sticker")} أو ${commandHint("pack", "<الاسم>")} لحفظ ملصق.`,
95
- ),
84
+ text: t("bot.stickers.stickers.empty", {
85
+ sticker: commandHint("sticker"),
86
+ pack: commandHint("pack", t("bot.stickers.hint.name")),
87
+ }),
96
88
  });
97
89
  const pages = Math.ceil(total / BOT_PAGE_SIZE);
98
90
  if (selected.page > pages) throw new StickerError("INVALID_OPTIONS");
@@ -104,11 +96,15 @@ module.exports = {
104
96
  ? commandHint("stickers", `favorites ${selected.page + 1}`)
105
97
  : commandHint("stickers", String(selected.page + 1))
106
98
  : null;
99
+ const more = next ? t("bot.stickers.stickers.pageMore", { next }) : "";
107
100
  await sock.sendMessage(jid, {
108
- text: tr(
109
- `${label} — ${countLabel(total)} · page ${selected.page}/${pages}${next ? ` · ${next} for more` : ""}`,
110
- `${label} — ${countLabel(total)} · الصفحة ${selected.page}/${pages}${next ? ` · ${next} للمزيد` : ""}`,
111
- ),
101
+ text: t("bot.stickers.stickers.page", {
102
+ label,
103
+ count: countLabel(total),
104
+ page: selected.page,
105
+ pages,
106
+ more,
107
+ }),
112
108
  });
113
109
  for (const sticker of items) await sendLibrarySticker(sock, jid, who, sticker);
114
110
  } catch (error) {
@@ -8,19 +8,12 @@
8
8
  // is no way to type a start command.
9
9
  const { getSession } = require("../core/session-holder.cjs");
10
10
  const logger = require("../utils/logger.cjs");
11
- const { tr } = require("../utils/i18n.cjs");
11
+ const { t } = require("../utils/i18n.cjs");
12
+ const { createStatus } = require("../utils/statusMessage.cjs");
12
13
 
13
14
  module.exports = {
14
15
  name: "stopbot",
15
16
  aliases: ["stop", "pause"],
16
- description: {
17
- en: "Pauses the WhatsApp connection (the bot process and panel keep running).",
18
- ar: "يوقف اتصال واتساب مؤقتًا (مع استمرار تشغيل البوت ولوحة التحكم).",
19
- },
20
- usage: {
21
- en: "stopbot",
22
- ar: "stopbot",
23
- },
24
17
  chat: "all",
25
18
 
26
19
  async execute(sock, msg) {
@@ -28,27 +21,23 @@ module.exports = {
28
21
  const session = getSession();
29
22
  if (!session) {
30
23
  return await sock.sendMessage(chatId, {
31
- text: tr("The session manager isn't ready yet.", "مدير الجلسة غير جاهز بعد."),
24
+ text: t("bot.core.stopbot.notReady"),
32
25
  });
33
26
  }
34
27
 
35
28
  const state = session.getState();
36
29
  if (!state.connected && !state.canStop) {
37
30
  return await sock.sendMessage(chatId, {
38
- text: tr(
39
- "The WhatsApp connection isn't up — nothing to pause.",
40
- "اتصال واتساب متوقف بالفعل.",
41
- ),
31
+ text: t("bot.core.stopbot.notUp"),
42
32
  });
43
33
  }
44
34
 
45
35
  // The goodbye goes out before the socket comes down: once stop() runs,
46
36
  // nothing can be sent through this chat until the session starts again.
47
- await sock.sendMessage(chatId, {
48
- text: tr(
49
- "⏸️ Pausing the WhatsApp connection. The bot and the control panel stay up — resume from the Connection screen in the panel.",
50
- "⏸️ جارٍ إيقاف اتصال واتساب مؤقتًا. سيستمر تشغيل البوت ولوحة التحكم. يمكنك استئناف الاتصال من صفحة الاتصال في لوحة التحكم.",
51
- ),
37
+ // It is the result, not a progress line, so it is never hidden.
38
+ const status = await createStatus(sock, chatId, t("bot.core.stopbot.pausing"), {
39
+ replyTo: msg,
40
+ category: "system",
52
41
  });
53
42
 
54
43
  try {
@@ -57,12 +46,7 @@ module.exports = {
57
46
  } catch (error) {
58
47
  logger.error({ err: error, command: "stopbot" }, "Failed to pause the WhatsApp connection");
59
48
  // The socket may still be up, so the operator can actually read this.
60
- await sock.sendMessage(chatId, {
61
- text: tr(
62
- "Couldn't pause the connection. Try the panel's Connection screen.",
63
- "تعذّر إيقاف الاتصال. حاول من صفحة الاتصال في لوحة التحكم.",
64
- ),
65
- });
49
+ await status.finish(t("bot.core.stopbot.pauseFailed")).catch(() => {});
66
50
  }
67
51
  },
68
52
  };
@@ -1,15 +1,11 @@
1
1
  // Speech-to-Text Command using FREE Gemini API
2
2
  const { GoogleGenAI } = require("@google/genai");
3
+ const { geminiHttpOptions } = require("../utils/geminiHttpOptions.cjs");
3
4
  const { downloadContentFromMessage } = require("@whiskeysockets/baileys");
4
5
  const logger = require("../utils/logger.cjs");
5
6
  const { createStatus } = require("../utils/statusMessage.cjs");
6
7
  const { unwrapMessage } = require("../utils/messageContent.cjs");
7
- const {
8
- INLINE_MEDIA_LIMIT,
9
- baseMimeType,
10
- downloadMedia,
11
- uploadToGemini,
12
- } = require("../utils/geminiMedia.cjs");
8
+ const { baseMimeType, downloadMedia } = require("../utils/geminiMedia.cjs");
13
9
 
14
10
  const settings = require("../config/settings.cjs");
15
11
  const {
@@ -17,7 +13,8 @@ const {
17
13
  assertProviderRequestUrl,
18
14
  safeProviderFetch,
19
15
  } = require("../utils/providerUrl.cjs");
20
- const { tr } = require("../utils/i18n.cjs");
16
+ const { t } = require("../utils/i18n.cjs");
17
+ const { assertAudio, MAX_MEDIA_BYTES } = require("../services/aiMedia.cjs");
21
18
 
22
19
  // Built on first use from whatever key is in force, and
23
20
  // rebuilt if that key changes — the operator can paste one without a restart.
@@ -36,7 +33,7 @@ function geminiStt() {
36
33
  cache = {
37
34
  key,
38
35
  baseUrl,
39
- genAI: new GoogleGenAI({ apiKey: key, httpOptions: { baseUrl } }),
36
+ genAI: new GoogleGenAI({ apiKey: key, apiVersion: "v1beta", httpOptions: geminiHttpOptions(baseUrl) }),
40
37
  };
41
38
  }
42
39
  return cache;
@@ -67,50 +64,36 @@ function resolveSttProvider() {
67
64
  const TRANSCRIBE_PROMPT =
68
65
  "Please transcribe this audio message accurately. Return ONLY the transcription text without any additional commentary, explanations, or formatting. Just the raw transcribed text.";
69
66
 
70
- // A voice note is a few hundred KB, so it rides inline in the request: one
71
- // round trip, instead of an upload, a finalize and then the request. Past
72
- // INLINE_MEDIA_LIMIT (Gemini caps a whole inline request at 20 MB) it goes
73
- // through the Files API instead.
67
+ // Transcription is capped at 8 MiB and fits inline, without a second upload.
74
68
 
75
- async function transcribeWithGemini(audioBuffer, mimetype) {
69
+ async function transcribeWithGemini(audioBuffer, mimetype, signal) {
76
70
  const gemini = geminiStt();
77
- if (!gemini)
78
- throw new Error(
79
- tr("No Gemini key is set in the settings", "مفتاح Gemini غير مضبوط في الإعدادات"),
80
- );
81
- await assertProviderRequestUrl(settings.get("gemini_base_url"), {
71
+ if (!gemini) throw new Error(t("bot.ai.stt.noGeminiKey"));
72
+ await assertProviderRequestUrl(gemini.baseUrl, {
82
73
  allowLoopback: true,
83
74
  });
84
75
 
85
76
  // WhatsApp labels voice notes `audio/ogg; codecs=opus`; Gemini's type is
86
77
  // `audio/ogg`, and the codec parameter is not part of it.
87
78
  const mimeType = baseMimeType(mimetype, "audio");
88
- let audioPart;
89
- if (audioBuffer.length <= INLINE_MEDIA_LIMIT) {
90
- audioPart = { inlineData: { mimeType, data: audioBuffer.toString("base64") } };
91
- } else {
92
- const file = await uploadToGemini(gemini.genAI, audioBuffer, mimeType, {
93
- displayName: `audio-${Date.now()}`,
94
- });
95
- audioPart = { fileData: { mimeType: file.mimeType || mimeType, fileUri: file.uri } };
96
- }
79
+ const audioPart = { inlineData: { mimeType, data: audioBuffer.toString("base64") } };
97
80
 
98
81
  const response = await gemini.genAI.models.generateContent({
99
82
  model: sttModel(),
100
83
  contents: [{ role: "user", parts: [audioPart, { text: TRANSCRIBE_PROMPT }] }],
84
+ config: {
85
+ abortSignal: signal,
86
+ httpOptions: { timeout: 60_000, baseUrl: gemini.baseUrl },
87
+ maxOutputTokens: 4096,
88
+ },
101
89
  });
102
90
  return (response.text ?? "").trim();
103
91
  }
104
92
 
105
- async function transcribeWithOpenAi(audioBuffer, mimetype) {
93
+ async function transcribeWithOpenAi(audioBuffer, mimetype, signal) {
106
94
  const apiKey = settings.get("openai_api_key");
107
95
  if (!apiKey) {
108
- throw new Error(
109
- tr(
110
- "No OpenAI / Groq key is set in the settings",
111
- "مفتاح OpenAI / Groq غير مضبوط في الإعدادات",
112
- ),
113
- );
96
+ throw new Error(t("bot.ai.stt.noOpenAiKey"));
114
97
  }
115
98
  const baseUrl = assertProviderBaseUrl(
116
99
  settings.get("openai_base_url") || "https://api.openai.com/v1",
@@ -142,61 +125,69 @@ async function transcribeWithOpenAi(audioBuffer, mimetype) {
142
125
  Authorization: `Bearer ${apiKey}`,
143
126
  },
144
127
  body: formData,
145
- signal: controller.signal,
128
+ signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
146
129
  },
147
130
  { allowLoopback: true },
148
131
  );
149
132
  if (!res.ok) {
150
- const err = await res.text().catch(() => "");
151
- throw new Error(`STT API (${res.status}): ${err}`);
133
+ await res.body?.cancel().catch(() => {});
134
+ throw new Error(res.status === 429 ? "STT_QUOTA" : "STT_FAILED");
135
+ }
136
+ const chunks = [];
137
+ let size = 0;
138
+ for await (const chunk of res.body) {
139
+ size += chunk.length;
140
+ if (size > 64 * 1024) {
141
+ controller.abort();
142
+ throw new Error("STT_OUTPUT_INVALID");
143
+ }
144
+ chunks.push(chunk);
152
145
  }
153
- const data = await res.json();
154
- return String(data?.text || "").trim();
146
+ let data;
147
+ try {
148
+ data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
149
+ } catch {
150
+ throw new Error("STT_OUTPUT_INVALID");
151
+ }
152
+ if (typeof data?.text !== "string") throw new Error("STT_OUTPUT_INVALID");
153
+ return data.text.trim();
155
154
  } finally {
156
155
  clearTimeout(timer);
157
156
  }
158
157
  }
159
158
 
160
159
  /** Audio bytes -> text, on whichever engine the settings pick. */
161
- async function transcribe(audioBuffer, mimetype) {
160
+ async function transcribe(audioBuffer, mimetype, { signal } = {}) {
161
+ signal?.throwIfAborted();
162
+ const mime = baseMimeType(mimetype, "audio");
163
+ assertAudio(audioBuffer, mime);
162
164
  const provider = resolveSttProvider();
163
- const hasOpenAi = !!settings.get("openai_api_key");
164
- if (provider === "openai" && hasOpenAi) {
165
- logger.info("[STT] Transcribing via OpenAI/Groq Whisper API");
166
- return transcribeWithOpenAi(audioBuffer, mimetype);
167
- }
168
- if (geminiStt()) {
169
- logger.info("[STT] Transcribing via Gemini");
170
- return transcribeWithGemini(audioBuffer, mimetype);
171
- }
172
- if (hasOpenAi) {
173
- logger.info("[STT] Fallback transcribing via OpenAI/Groq Whisper API");
174
- return transcribeWithOpenAi(audioBuffer, mimetype);
165
+ if (!settings.get(`${provider}_api_key`)) {
166
+ const error = new Error(
167
+ t(provider === "openai" ? "bot.ai.stt.noOpenAiKey" : "bot.ai.stt.noGeminiKey"),
168
+ );
169
+ error.code = "STT_KEY_REQUIRED";
170
+ throw error;
175
171
  }
176
- throw new Error(
177
- tr(
178
- "No AI key (Gemini or OpenAI/Groq) is set",
179
- "مفتاح الذكاء الاصطناعي (Gemini أو OpenAI/Groq) غير مضبوط",
180
- ),
181
- );
172
+ const result =
173
+ provider === "openai"
174
+ ? await transcribeWithOpenAi(audioBuffer, mime, signal)
175
+ : await transcribeWithGemini(audioBuffer, mime, signal);
176
+ signal?.throwIfAborted();
177
+ if (typeof result !== "string" || result.length > 12000) throw new Error("STT_OUTPUT_INVALID");
178
+ return result;
182
179
  }
183
180
 
184
181
  function sttErrorHint(error) {
185
182
  const message = String(error?.message || "");
186
183
  if (/quota|RESOURCE_EXHAUSTED|429/i.test(message)) {
187
- return tr(
188
- "The free quota is used up. Try again later.",
189
- "تم تجاوز الحد المجاني. حاول مرة أخرى لاحقاً.",
190
- );
184
+ return t("bot.ai.stt.quota");
191
185
  }
192
186
  if (/API key|API_KEY|401|403/i.test(message)) {
193
- return tr(
194
- "Check the API key in the control panel (Settings).",
195
- "راجع مفتاح الـ API من لوحة التحكم (Settings).",
196
- );
187
+ return t("bot.ai.stt.apiKeyHint");
197
188
  }
198
189
  if (/upload/i.test(message)) {
199
- return tr("Uploading the audio failed. Try again.", "فشل رفع الملف الصوتي. حاول مرة أخرى.");
190
+ return t("bot.ai.stt.uploadFailed");
200
191
  }
201
192
  return "";
202
193
  }
@@ -204,14 +195,6 @@ function sttErrorHint(error) {
204
195
  module.exports = {
205
196
  name: "stt",
206
197
  aliases: ["totext", "transcribe"],
207
- description: {
208
- en: "Converts speech/audio to text (Gemini or Groq/OpenAI Whisper).",
209
- ar: "يحوّل الكلام/الصوت إلى نص (عبر Gemini أو Groq/OpenAI Whisper).",
210
- },
211
- usage: {
212
- en: "stt (reply to a voice note, or send one with the command)",
213
- ar: "stt (رد على رسالة صوتية أو أرسلها مع الأمر)",
214
- },
215
198
  chat: "all",
216
199
 
217
200
  async execute(sock, msg, args, body, groupMetadata) {
@@ -225,55 +208,39 @@ module.exports = {
225
208
 
226
209
  if (!audioMessage) {
227
210
  return await sock.sendMessage(chatId, {
228
- text: tr(
229
- "📢 Usage:\nSend a voice note, or reply to one, with !stt\n\n✨ Transcribes with Gemini or Groq/OpenAI Whisper\n🌍 Arabic, English and every other language",
230
- "📢 الاستخدام:\nأرسل رسالة صوتية أو قم بالرد على رسالة صوتية بالأمر !stt\n\n✨ يدعم تفريغ الصوت عبر Gemini و Groq/OpenAI Whisper\n🌍 يدعم العربية والإنجليزية وكافة اللغات",
231
- ),
211
+ text: t("bot.ai.stt.usage"),
232
212
  });
233
213
  }
234
214
 
235
- const hasGemini = !!geminiStt();
215
+ const hasGemini = !!settings.get("gemini_api_key");
236
216
  const hasOpenAi = !!settings.get("openai_api_key");
237
217
 
238
218
  if (!hasGemini && !hasOpenAi) {
239
219
  return await sock.sendMessage(chatId, {
240
- text: tr(
241
- "⚠️ No AI key (Gemini or OpenAI/Groq) is set. Add one in the control panel (Settings).",
242
- "⚠️ مفتاح الذكاء الاصطناعي (Gemini أو OpenAI/Groq) غير مضبوط. يرجى إضافته من لوحة التحكم (Settings).",
243
- ),
220
+ text: t("bot.ai.stt.noKeySet"),
244
221
  });
245
222
  }
246
223
 
247
224
  // One message, edited from "transcribing" into the transcript itself.
248
- const status = await createStatus(
249
- sock,
250
- chatId,
251
- tr("🎧 Transcribing...", "🎧 جارٍ تحويل الصوت إلى نص..."),
252
- {
253
- replyTo: msg,
254
- },
255
- );
225
+ const status = await createStatus(sock, chatId, t("bot.ai.stt.transcribing"), {
226
+ replyTo: msg,
227
+ });
256
228
 
257
229
  try {
258
230
  // A real Buffer, not the download stream: the Whisper path wraps it in
259
231
  // a Blob, and a stream in a Blob is the string "[object Object]".
260
- const audioBuffer = await downloadMedia(downloadContentFromMessage, audioMessage, "audio");
232
+ const audioBuffer = await downloadMedia(downloadContentFromMessage, audioMessage, "audio", {
233
+ maxBytes: MAX_MEDIA_BYTES,
234
+ });
261
235
  const transcription = await transcribe(audioBuffer, audioMessage.mimetype);
262
236
 
263
237
  if (!transcription) {
264
- await status.finish(
265
- tr(
266
- "⚠️ I couldn't get any text out of that voice note. Make sure the audio is clear.",
267
- "⚠️ لم أتمكن من استخراج أي نص من الرسالة الصوتية. تأكد من أن الصوت واضح.",
268
- ),
269
- );
238
+ await status.finish(t("bot.ai.stt.emptyTranscript"));
270
239
  return;
271
240
  }
272
241
 
273
242
  // The status line becomes the transcript.
274
- await status.finish(
275
- tr(`📝 Transcript:\n\n${transcription}`, `📝 النص المستخرج:\n\n${transcription}`),
276
- );
243
+ await status.finish(t("bot.ai.stt.transcript", { transcription }));
277
244
 
278
245
  logger.info("[STT] Successfully transcribed audio to text");
279
246
  } catch (error) {
@@ -281,16 +248,17 @@ module.exports = {
281
248
 
282
249
  // The real reason goes in the card — a bare "an error happened" left
283
250
  // nothing to act on.
284
- const details = String(error?.message || error || tr("unknown", "غير معروف")).slice(0, 800);
251
+ const details = String(error?.message || error || t("bot.ai.stt.unknown")).slice(0, 800);
285
252
  const hint = sttErrorHint(error);
286
253
  await status.finish(
287
- tr(
288
- `❌ *Transcription failed*\n\n*Details:* ${details}${hint ? `\n\n${hint}` : ""}`,
289
- `❌ *حدث خطأ أثناء تحويل الصوت إلى نص*\n\n*التفاصيل:* ${details}${hint ? `\n\n${hint}` : ""}`,
290
- ),
254
+ t("bot.ai.stt.failed", {
255
+ details,
256
+ hintBlock: hint ? `\n\n${hint}` : "",
257
+ }),
291
258
  );
292
259
  }
293
260
  },
294
261
  };
295
262
 
296
263
  module.exports.transcribe = transcribe;
264
+ module.exports.resolveSttProvider = resolveSttProvider;
@@ -1,19 +1,11 @@
1
1
  // file: /commands/todo.cjs (Corrected Reply Logic)
2
2
  const { getUserTodos, saveUserTodos } = require("../utils/storage.cjs");
3
3
  const logger = require("../utils/logger.cjs");
4
- const { tr } = require("../utils/i18n.cjs");
4
+ const { t } = require("../utils/i18n.cjs");
5
5
  const normalizeJid = require("../utils/normalizeJid.esm.js").default;
6
6
 
7
7
  module.exports = {
8
8
  name: "todo",
9
- description: {
10
- en: "Manages your personal to-do list.",
11
- ar: "يدير قائمة مهامك الشخصية.",
12
- },
13
- usage: {
14
- en: "todo list\ntodo add <task>\ntodo del <task number>",
15
- ar: "todo list\ntodo add <المهمة>\ntodo del <رقم المهمة>",
16
- },
17
9
  chat: "all",
18
10
 
19
11
  async execute(sock, msg, args) {
@@ -29,16 +21,13 @@ module.exports = {
29
21
  const taskToAdd = args.slice(1).join(" ");
30
22
  if (!taskToAdd) {
31
23
  return await sock.sendMessage(remoteJid, {
32
- text: tr("Write the task you want to add.", "يرجى كتابة المهمة التي تريد إضافتها."),
24
+ text: t("bot.tools.todo.writeTask"),
33
25
  });
34
26
  }
35
27
  userTasks.push(taskToAdd);
36
28
  saveUserTodos(senderId, userTasks);
37
29
  await sock.sendMessage(remoteJid, {
38
- text: tr(
39
- `✅ @${senderId.split("@")[0]}, the task was added to your list.`,
40
- `✅ يا @${senderId.split("@")[0]}، تمت إضافة المهمة لقائمتك.`,
41
- ),
30
+ text: t("bot.tools.todo.added", { user: senderId.split("@")[0] }),
42
31
  mentions: [senderId],
43
32
  });
44
33
  break;
@@ -49,16 +38,16 @@ module.exports = {
49
38
  const taskNumber = parseInt(args[1], 10);
50
39
  if (isNaN(taskNumber) || taskNumber <= 0 || taskNumber > userTasks.length) {
51
40
  return await sock.sendMessage(remoteJid, {
52
- text: tr("That task number isn't valid.", "رقم المهمة غير صالح."),
41
+ text: t("bot.tools.todo.invalidNumber"),
53
42
  });
54
43
  }
55
44
  const removedTask = userTasks.splice(taskNumber - 1, 1);
56
45
  saveUserTodos(senderId, userTasks);
57
46
  await sock.sendMessage(remoteJid, {
58
- text: tr(
59
- `☑️ @${senderId.split("@")[0]}, removed the task: *${removedTask[0]}*`,
60
- `☑️ يا @${senderId.split("@")[0]}، تم حذف المهمة: *${removedTask[0]}*`,
61
- ),
47
+ text: t("bot.tools.todo.removed", {
48
+ user: senderId.split("@")[0],
49
+ task: removedTask[0],
50
+ }),
62
51
  mentions: [senderId],
63
52
  });
64
53
  break;
@@ -68,18 +57,12 @@ module.exports = {
68
57
  default: {
69
58
  if (userTasks.length === 0) {
70
59
  return await sock.sendMessage(remoteJid, {
71
- text: tr(
72
- `Your to-do list is empty, @${senderId.split("@")[0]}.`,
73
- `قائمة مهامك فارغة يا @${senderId.split("@")[0]}.`,
74
- ),
60
+ text: t("bot.tools.todo.empty", { user: senderId.split("@")[0] }),
75
61
  mentions: [senderId],
76
62
  });
77
63
  }
78
64
 
79
- let reply = tr(
80
- `*📋 Your to-do list, @${senderId.split("@")[0]}:*\n\n`,
81
- `*📋 قائمة مهامك يا @${senderId.split("@")[0]}:*\n\n`,
82
- );
65
+ let reply = t("bot.tools.todo.listHeader", { user: senderId.split("@")[0] });
83
66
  userTasks.forEach((task, index) => {
84
67
  reply += `${index + 1}. ${task}\n`;
85
68
  });
@@ -94,10 +77,7 @@ module.exports = {
94
77
  } catch (error) {
95
78
  logger.error({ err: error, command: "todo" }, "An error occurred in the todo command");
96
79
  await sock.sendMessage(msg.key.remoteJid, {
97
- text: tr(
98
- "Something went wrong with the to-do list.",
99
- "حدث خطأ أثناء معالجة قائمة المهام.",
100
- ),
80
+ text: t("bot.tools.todo.error"),
101
81
  });
102
82
  }
103
83
  },
@@ -1,4 +1,4 @@
1
- const { tr } = require("../utils/i18n.cjs");
1
+ const { t } = require("../utils/i18n.cjs");
2
2
  const { createStatus } = require("../utils/statusMessage.cjs");
3
3
  const { targetOf, downloadTarget, commandHint, errorText } = require("../utils/stickerBot.cjs");
4
4
  const media = require("../stickers/media.cjs");
@@ -7,14 +7,6 @@ const jobs = require("../stickers/jobs.cjs");
7
7
  module.exports = {
8
8
  name: "toimage",
9
9
  aliases: ["toimg", "صورة"],
10
- description: {
11
- en: "Turn a replied sticker into a PNG or animated video.",
12
- ar: "يحوّل الملصق المردود عليه إلى صورة PNG أو فيديو متحرك.",
13
- },
14
- usage: {
15
- en: "toimage (reply to a sticker)\ntoimage doc (reply to a sticker)\ntoimage gif (reply to an animated sticker)",
16
- ar: "toimage (رد على ملصق)\ntoimage ملف (رد على ملصق)\ntoimage متحرك (رد على ملصق متحرك)",
17
- },
18
10
  keywords: ["doc", "ملف", "gif", "متحرك"],
19
11
  chat: "all",
20
12
  async execute(sock, msg, args = []) {
@@ -22,10 +14,9 @@ module.exports = {
22
14
  const target = targetOf(msg, { quotedOnly: true });
23
15
  if (target?.type !== "sticker") {
24
16
  return sock.sendMessage(jid, {
25
- text: tr(
26
- `Reply to a sticker with ${commandHint("toimage", "[doc|gif]")}.`,
27
- `رد على ملصق بالأمر ${commandHint("toimage", "[ملف|متحرك]")}.`,
28
- ),
17
+ text: t("bot.stickers.toimage.reply", {
18
+ hint: commandHint("toimage", t("bot.stickers.hint.toimageModes")),
19
+ }),
29
20
  });
30
21
  }
31
22
  let status;
@@ -39,12 +30,9 @@ module.exports = {
39
30
  : args.some((arg) => ["doc", "ملف"].includes(String(arg).toLowerCase()))
40
31
  ? "doc"
41
32
  : "png";
42
- status = await createStatus(
43
- sock,
44
- jid,
45
- tr("🎨 Converting sticker...", "🎨 جارٍ تحويل الملصق..."),
46
- { replyTo: msg },
47
- );
33
+ status = await createStatus(sock, jid, t("bot.stickers.toimage.converting"), {
34
+ replyTo: msg,
35
+ });
48
36
  const job = jobs.submit(
49
37
  ({ signal }) =>
50
38
  mode === "gif" ? media.toMp4(buffer, { signal }) : media.toPng(buffer, { signal }),
@@ -52,15 +40,11 @@ module.exports = {
52
40
  );
53
41
  const result = await job.promise;
54
42
  const caption = staticGif
55
- ? tr(
56
- "This sticker is not animated, so I sent a PNG.",
57
- "هذا الملصق غير متحرك، لذا أرسلت صورة PNG.",
58
- )
43
+ ? t("bot.stickers.toimage.staticGif")
59
44
  : result.animated
60
- ? tr(
61
- `First frame of an animated sticker. Use ${commandHint("toimage", "gif")} for the animation.`,
62
- `الإطار الأول من ملصق متحرك. استخدم ${commandHint("toimage", "متحرك")} للحصول على الحركة.`,
63
- )
45
+ ? t("bot.stickers.toimage.firstFrame", {
46
+ hint: commandHint("toimage", t("bot.stickers.hint.gif")),
47
+ })
64
48
  : undefined;
65
49
  if (mode === "gif") {
66
50
  await sock.sendMessage(jid, { video: result, mimetype: "video/mp4", gifPlayback: true });