levix-bot 4.0.4 → 4.2.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 (96) hide show
  1. package/package.json +1 -1
  2. package/public/dashboard/assets/index-4AuqfnH5.js +431 -0
  3. package/public/dashboard/assets/index-LvfJ8ybs.css +2 -0
  4. package/public/dashboard/index.html +2 -2
  5. package/scheduler.cjs +25 -1
  6. package/src/commands/autoschedule.cjs +40 -10
  7. package/src/commands/blacklist.cjs +35 -10
  8. package/src/commands/block.cjs +18 -5
  9. package/src/commands/calc.cjs +90 -24
  10. package/src/commands/debt.cjs +59 -33
  11. package/src/commands/deleteschedule.cjs +21 -5
  12. package/src/commands/digit.cjs +34 -8
  13. package/src/commands/gemini.cjs +235 -108
  14. package/src/commands/group/add.cjs +46 -13
  15. package/src/commands/group/all.cjs +15 -5
  16. package/src/commands/group/antiSpam.cjs +11 -4
  17. package/src/commands/group/antilink.cjs +39 -19
  18. package/src/commands/group/approveall.cjs +22 -7
  19. package/src/commands/group/clearwarns.cjs +18 -5
  20. package/src/commands/group/deletenote.cjs +18 -5
  21. package/src/commands/group/demote.cjs +25 -7
  22. package/src/commands/group/kick.cjs +28 -12
  23. package/src/commands/group/media.cjs +34 -13
  24. package/src/commands/group/members.cjs +21 -6
  25. package/src/commands/group/note.cjs +14 -4
  26. package/src/commands/group/promote.cjs +22 -6
  27. package/src/commands/group/removeall.cjs +13 -3
  28. package/src/commands/group/rules.cjs +20 -5
  29. package/src/commands/group/save.cjs +20 -5
  30. package/src/commands/group/setname.cjs +19 -6
  31. package/src/commands/group/setpp.cjs +21 -6
  32. package/src/commands/group/setrules.cjs +17 -5
  33. package/src/commands/group/setwarn.cjs +23 -7
  34. package/src/commands/group/tagadmins.cjs +16 -6
  35. package/src/commands/group/warn.cjs +35 -15
  36. package/src/commands/group/warns.cjs +33 -13
  37. package/src/commands/group/welcome.cjs +34 -16
  38. package/src/commands/group.cjs +96 -70
  39. package/src/commands/help.cjs +270 -129
  40. package/src/commands/lang.cjs +46 -13
  41. package/src/commands/listschedules.cjs +28 -11
  42. package/src/commands/loop.cjs +43 -9
  43. package/src/commands/memory.cjs +90 -30
  44. package/src/commands/mod.cjs +72 -28
  45. package/src/commands/notes.cjs +15 -5
  46. package/src/commands/perm.cjs +52 -20
  47. package/src/commands/ping.cjs +15 -3
  48. package/src/commands/poll.cjs +71 -24
  49. package/src/commands/prayer.cjs +28 -12
  50. package/src/commands/qr.cjs +20 -5
  51. package/src/commands/rand.cjs +54 -12
  52. package/src/commands/restart.cjs +13 -3
  53. package/src/commands/schedule.cjs +32 -9
  54. package/src/commands/score.cjs +26 -10
  55. package/src/commands/setprefix.cjs +27 -5
  56. package/src/commands/shortlink.cjs +36 -10
  57. package/src/commands/shutdown.cjs +13 -3
  58. package/src/commands/status.cjs +32 -11
  59. package/src/commands/sticker.cjs +34 -7
  60. package/src/commands/stt.cjs +159 -107
  61. package/src/commands/todo.cjs +31 -9
  62. package/src/commands/tts.cjs +61 -36
  63. package/src/commands/unblock.cjs +17 -4
  64. package/src/commands/weather.cjs +55 -17
  65. package/src/config/baileys.config.js +5 -1
  66. package/src/config/settings.cjs +11 -3
  67. package/src/core/connection.js +21 -2
  68. package/src/core/socket.js +31 -7
  69. package/src/db/store.cjs +24 -0
  70. package/src/handlers/command.handler.js +55 -13
  71. package/src/handlers/group.handler.js +5 -1
  72. package/src/handlers/message.handler.js +9 -0
  73. package/src/middleware/antispam.middleware.js +13 -3
  74. package/src/middleware/blacklist.middleware.js +4 -1
  75. package/src/middleware/permissions.middleware.js +38 -51
  76. package/src/routes/dashboard.api.esm.js +91 -10
  77. package/src/services/aiAgent.cjs +51 -41
  78. package/src/services/aiProviders.cjs +46 -19
  79. package/src/services/aiRouter.cjs +11 -3
  80. package/src/services/aiToolAuth.cjs +114 -0
  81. package/src/services/aiTools.cjs +492 -56
  82. package/src/services/modelRegistry.cjs +20 -5
  83. package/src/utils/commandDocs.cjs +58 -0
  84. package/src/utils/geminiMedia.cjs +99 -0
  85. package/src/utils/groupMetadataCache.cjs +83 -0
  86. package/src/utils/i18n.cjs +113 -0
  87. package/src/utils/markdownParser.cjs +4 -2
  88. package/src/utils/memory.cjs +37 -21
  89. package/src/utils/permissionLevel.cjs +83 -0
  90. package/src/utils/providerUrl.cjs +29 -2
  91. package/src/utils/sendBotMessage.cjs +7 -3
  92. package/src/utils/sendBotMessage.esm.js +27 -3
  93. package/src/utils/statusMessage.cjs +11 -4
  94. package/src/utils/storage-hub.cjs +21 -0
  95. package/public/dashboard/assets/index-BnJbz8iW.css +0 -2
  96. package/public/dashboard/assets/index-Dn8ZyzsW.js +0 -426
@@ -35,11 +35,8 @@ const {
35
35
  const { sendBotMessage, sendBotError } = require("../utils/sendBotMessage.cjs");
36
36
  const { createStatus } = require("../utils/statusMessage.cjs");
37
37
  const { formatMarkdownForWhatsApp } = require("../utils/markdownParser.cjs");
38
- const {
39
- isOwnerJidSync,
40
- isBotAdminUserSync,
41
- isAdminInGroupSync,
42
- } = require("../utils/permissions.cjs");
38
+ const { isOwnerJidSync } = require("../utils/permissions.cjs");
39
+ const { resolveCaller } = require("../services/aiToolAuth.cjs");
43
40
  const {
44
41
  runAgent,
45
42
  formatSources,
@@ -49,12 +46,12 @@ const {
49
46
  } = require("../services/aiAgent.cjs");
50
47
  const { getProvider } = require("../services/aiRouter.cjs");
51
48
  const { downloadContentFromMessage } = require("@whiskeysockets/baileys");
52
- const fs = require("fs").promises;
53
- const path = require("path");
49
+ const { unwrapMessage, visibleText } = require("../utils/messageContent.cjs");
54
50
  const {
55
51
  assertProviderBaseUrl,
56
52
  assertProviderRequestUrl,
57
53
  } = require("../utils/providerUrl.cjs");
54
+ const { tr } = require("../utils/i18n.cjs");
58
55
 
59
56
  // Per-(chat, sender) explicit context buffer for the multi-message workflow.
60
57
  // Entries accumulate until `!gemini send` flushes them into a single call.
@@ -136,16 +133,29 @@ function geminiClients() {
136
133
  return geminiCache;
137
134
  }
138
135
 
139
- async function processIncomingMedia(parts, mediaMessage, mimeOverride = null) {
136
+ // The media in a message and the type WhatsApp filed it under. That type, not
137
+ // the MIME type, picks the decryption keys: a photo sent as a document has to
138
+ // be downloaded as a "document".
139
+ const MEDIA_TYPES = ["image", "video", "audio", "document"];
140
+ function pickMedia(message) {
141
+ const inner = unwrapMessage(message);
142
+ for (const type of MEDIA_TYPES) {
143
+ const media = inner[`${type}Message`];
144
+ if (media) return { media, type };
145
+ }
146
+ return null;
147
+ }
148
+
149
+ async function processIncomingMedia(parts, mediaMessage, downloadType) {
140
150
  const provider = getProvider();
141
151
  if (provider.id === "gemini") {
142
152
  await assertProviderRequestUrl(settings.get("gemini_base_url"), { allowLoopback: true });
143
153
  }
144
154
  const { genAI } = geminiClients();
145
- return provider.prepareMedia(parts, mediaMessage, mimeOverride, {
155
+ return provider.prepareMedia(parts, mediaMessage, null, {
146
156
  downloadContentFromMessage,
147
157
  genAI,
148
- tempDir: __dirname,
158
+ downloadType,
149
159
  });
150
160
  }
151
161
 
@@ -167,12 +177,12 @@ async function captureContextEntry(msg, args) {
167
177
  const cleanedText = args.slice(1).join(" ").trim();
168
178
  if (cleanedText) entry.text = cleanedText;
169
179
 
170
- const m = msg.message || {};
180
+ const m = unwrapMessage(msg.message);
171
181
 
172
- const directMedia = m.imageMessage || m.videoMessage || m.audioMessage || m.documentMessage;
182
+ const directMedia = pickMedia(m);
173
183
  if (directMedia) {
174
184
  try {
175
- await processIncomingMedia(entry.mediaParts, directMedia);
185
+ await processIncomingMedia(entry.mediaParts, directMedia.media, directMedia.type);
176
186
  } catch (err) {
177
187
  logger.warn(
178
188
  { err: err?.message },
@@ -183,18 +193,11 @@ async function captureContextEntry(msg, args) {
183
193
 
184
194
  const quoted = m.extendedTextMessage?.contextInfo?.quotedMessage;
185
195
  if (quoted) {
186
- entry.quotedText =
187
- quoted.conversation ||
188
- quoted.extendedTextMessage?.text ||
189
- quoted.imageMessage?.caption ||
190
- quoted.videoMessage?.caption ||
191
- quoted.documentMessage?.caption ||
192
- "";
193
- const quotedMedia =
194
- quoted.imageMessage || quoted.videoMessage || quoted.audioMessage || quoted.documentMessage;
196
+ entry.quotedText = visibleText(quoted);
197
+ const quotedMedia = pickMedia(quoted);
195
198
  if (quotedMedia) {
196
199
  try {
197
- await processIncomingMedia(entry.quotedMediaParts, quotedMedia);
200
+ await processIncomingMedia(entry.quotedMediaParts, quotedMedia.media, quotedMedia.type);
198
201
  } catch (err) {
199
202
  logger.warn(
200
203
  { err: err?.message },
@@ -214,7 +217,9 @@ function entryHasContent(e) {
214
217
  function buildPartsFromBuffer(entries) {
215
218
  const parts = [];
216
219
  for (const e of entries) {
217
- if (e.quotedText) parts.push({ text: `(مرجع: "${e.quotedText}")` });
220
+ if (e.quotedText) {
221
+ parts.push({ text: tr(`(Reference: "${e.quotedText}")`, `(مرجع: "${e.quotedText}")`) });
222
+ }
218
223
  if (e.quotedMediaParts?.length) parts.push(...e.quotedMediaParts);
219
224
  if (e.mediaParts?.length) parts.push(...e.mediaParts);
220
225
  if (e.text) parts.push({ text: e.text });
@@ -232,18 +237,30 @@ function summarizeEntry(e, idx) {
232
237
  const preview = e.quotedText.length > 40 ? e.quotedText.slice(0, 40) + "…" : e.quotedText;
233
238
  bits.push(`↩️ "${preview}"`);
234
239
  }
235
- if (e.mediaParts?.length) bits.push(`🖼️ ميديا (${e.mediaParts.length})`);
236
- if (e.quotedMediaParts?.length) bits.push(`🖼️↩️ ميديا مقتبسة (${e.quotedMediaParts.length})`);
237
- return `${idx + 1}. ${bits.join(" · ") || "(فارغة)"}`;
240
+ if (e.mediaParts?.length)
241
+ bits.push(tr(`🖼️ media (${e.mediaParts.length})`, `🖼️ ميديا (${e.mediaParts.length})`));
242
+ if (e.quotedMediaParts?.length) {
243
+ bits.push(
244
+ tr(
245
+ `🖼️↩️ quoted media (${e.quotedMediaParts.length})`,
246
+ `🖼️↩️ ميديا مقتبسة (${e.quotedMediaParts.length})`,
247
+ ),
248
+ );
249
+ }
250
+ return `${idx + 1}. ${bits.join(" · ") || tr("(empty)", "(فارغة)")}`;
238
251
  }
239
252
 
240
253
  module.exports = {
241
254
  name: "gemini",
242
255
  aliases: ["ask", "ai", "resetai", "del", "delall", "generate"],
243
- description:
244
- "مساعد ذكي بأدوات (بحث، فتح روابط، ذاكرة دائمة). sub-commands: add/send/clear/show للسياق، generate للصور، del/delall لمسح المحادثة.",
245
- usage:
246
- "gemini <النص>\ngemini add <النص>\ngemini send\ngemini show\ngemini clear\ngenerate <وصف الصورة>\ndel (مسح ذاكرة المحادثة)\ndelall (مسح كل المحادثات)",
256
+ description: {
257
+ en: "AI assistant with tools (web search, reading links, long-term memory). Sub-commands: add/send/clear/show for context, generate for images, del/delall to clear the conversation.",
258
+ ar: "مساعد ذكي بأدوات (بحث في الويب، قراءة الروابط، ذاكرة دائمة). أوامر فرعية: add/send/clear/show للسياق، وgenerate للصور، وdel/delall لمسح المحادثة.",
259
+ },
260
+ usage: {
261
+ en: "gemini <text>\ngemini add <text>\ngemini send\ngemini show\ngemini clear\ngenerate <image description>\ndel (clear this chat's conversation)\ndelall (clear every conversation)",
262
+ ar: "gemini <النص>\ngemini add <النص>\ngemini send\ngemini show\ngemini clear\ngenerate <وصف الصورة>\ndel (مسح سجل محادثة هذا الشات)\ndelall (مسح كل المحادثات)",
263
+ },
247
264
  chat: "all",
248
265
 
249
266
  async execute(sock, msg, args, body, groupMetadata, ctx = {}) {
@@ -253,8 +270,6 @@ module.exports = {
253
270
 
254
271
  const senderId = msg.key.fromMe ? null : isGroup ? msg.key.participant : msg.key.remoteJid;
255
272
  const isOwner = msg.key.fromMe || isOwnerJidSync(senderId);
256
- const isBotAdmin = isOwner || isBotAdminUserSync(senderId);
257
- const isGroupAdmin = Boolean(isGroup && isAdminInGroupSync(groupMetadata, senderId));
258
273
 
259
274
  // Resolve sub-command. Aliases like !del arrive via ctx.invokedName, while
260
275
  // `!gemini del ...` arrives as args[0].
@@ -283,7 +298,7 @@ module.exports = {
283
298
  return sendBotMessage(
284
299
  sock,
285
300
  chatId,
286
- { text: "🚫 هذا الأمر مخصص للمالك فقط." },
301
+ { text: tr("🚫 Only the bot owner can use this.", "🚫 هذا الأمر مخصص للمالك فقط.") },
287
302
  { replyTo: msg },
288
303
  );
289
304
  await deleteChatHistoryAsync(chatId);
@@ -291,9 +306,12 @@ module.exports = {
291
306
  sock,
292
307
  chatId,
293
308
  {
294
- text:
309
+ text: tr(
310
+ "✅ Conversation history cleared.\n" +
311
+ "_(Long-term memory isn't cleared this way — use `!memory clear` if that's what you meant.)_",
295
312
  "✅ تم مسح سجل المحادثة.\n" +
296
- "_(الذاكرة الدائمة مش بتتمسح كده — استخدم `!memory clear` لو ده اللي تقصده.)_",
313
+ "_(الذاكرة الدائمة مش بتتمسح كده — استخدم `!memory clear` لو ده اللي تقصده.)_",
314
+ ),
297
315
  },
298
316
  { replyTo: msg },
299
317
  );
@@ -303,14 +321,19 @@ module.exports = {
303
321
  return sendBotMessage(
304
322
  sock,
305
323
  chatId,
306
- { text: "🚫 هذا الأمر مخصص للمالك فقط." },
324
+ { text: tr("🚫 Only the bot owner can use this.", "🚫 هذا الأمر مخصص للمالك فقط.") },
307
325
  { replyTo: msg },
308
326
  );
309
327
  await deleteAllChatHistoriesAsync();
310
328
  return sendBotMessage(
311
329
  sock,
312
330
  chatId,
313
- { text: "✅ تم مسح كل سجلات المحادثات بنجاح." },
331
+ {
332
+ text: tr(
333
+ "✅ Every conversation history was cleared.",
334
+ "✅ تم مسح كل سجلات المحادثات بنجاح.",
335
+ ),
336
+ },
314
337
  { replyTo: msg },
315
338
  );
316
339
  }
@@ -325,20 +348,33 @@ module.exports = {
325
348
  sock,
326
349
  chatId,
327
350
  {
328
- text: "اكتب وصف للصورة اللي عايزها بعد الأمر. مثال: !generate قطة ترتدي قبعة",
351
+ text: tr(
352
+ "Describe the image you want after the command. Example: !generate a cat wearing a hat",
353
+ "اكتب وصف للصورة اللي عايزها بعد الأمر. مثال: !generate قطة ترتدي قبعة",
354
+ ),
329
355
  },
330
356
  { replyTo: msg },
331
357
  );
332
358
  }
333
359
 
334
- const status = await createStatus(sock, chatId, "🎨 بجهّز الصورة...", { replyTo: msg });
360
+ const status = await createStatus(
361
+ sock,
362
+ chatId,
363
+ tr("🎨 Making the image...", "🎨 بجهّز الصورة..."),
364
+ { replyTo: msg },
365
+ );
335
366
 
336
367
  try {
337
368
  // Image generation needs a model that returns image bytes, which only
338
369
  // the Gemini image models do — it stays on Gemini whatever the chat
339
370
  // provider is.
340
371
  if (!geminiClients().genAI) {
341
- throw new Error("مفتاح Gemini API غير معرف — توليد الصور يعمل على Gemini فقط");
372
+ throw new Error(
373
+ tr(
374
+ "No Gemini API key is set — image generation only runs on Gemini",
375
+ "مفتاح Gemini API غير معرف — توليد الصور يعمل على Gemini فقط",
376
+ ),
377
+ );
342
378
  }
343
379
  await assertProviderRequestUrl(settings.get("gemini_base_url"), {
344
380
  allowLoopback: true,
@@ -360,7 +396,9 @@ module.exports = {
360
396
  const image = (response.candidates?.[0]?.content?.parts || []).find(
361
397
  (part) => part?.inlineData?.data,
362
398
  );
363
- if (!image) throw new Error("الموديل رجّع رد من غير صورة");
399
+ if (!image) {
400
+ throw new Error(tr("The model answered without an image", "الموديل رجّع رد من غير صورة"));
401
+ }
364
402
  const imageBuffer = Buffer.from(image.inlineData.data, "base64");
365
403
 
366
404
  await status.remove();
@@ -369,13 +407,13 @@ module.exports = {
369
407
  chatId,
370
408
  {
371
409
  image: imageBuffer,
372
- caption: `🖼️ تفضل، صورة لـ: "${imagePrompt}"`,
410
+ caption: tr(`🖼️ Here you go: "${imagePrompt}"`, `🖼️ تفضل، صورة لـ: "${imagePrompt}"`),
373
411
  },
374
412
  { replyTo: msg },
375
413
  );
376
414
  } catch (error) {
377
415
  logger.error({ err: error }, `Error in !generate command`);
378
- await status.fail(error, "للأسف معرفتش أعمل الصورة");
416
+ await status.fail(error, tr("I couldn't make the image", "للأسف معرفتش أعمل الصورة"));
379
417
  }
380
418
  return;
381
419
  }
@@ -388,9 +426,12 @@ module.exports = {
388
426
  sock,
389
427
  chatId,
390
428
  {
391
- text:
429
+ text: tr(
430
+ "📭 Nothing to add to the context.\n\n" +
431
+ "Write text after the command, reply to a message, or send media with the caption `!gemini add`.",
392
432
  "📭 مفيش حاجة أضيفها للـ context.\n\n" +
393
- "اكتب نص بعد الأمر، أو رد على رسالة، أو ابعت ميديا مع كابشن `!gemini add`.",
433
+ "اكتب نص بعد الأمر، أو رد على رسالة، أو ابعت ميديا مع كابشن `!gemini add`.",
434
+ ),
394
435
  },
395
436
  { replyTo: msg },
396
437
  );
@@ -400,7 +441,12 @@ module.exports = {
400
441
  return sendBotMessage(
401
442
  sock,
402
443
  chatId,
403
- { text: `الـ context ممتلئ (حد أقصى ${MAX_BUFFER_ENTRIES} رسائل). ابعت \`!gemini send\` أو \`!gemini clear\`.` },
444
+ {
445
+ text: tr(
446
+ `The context is full (${MAX_BUFFER_ENTRIES} messages at most). Send \`!gemini send\` or \`!gemini clear\`.`,
447
+ `الـ context ممتلئ (حد أقصى ${MAX_BUFFER_ENTRIES} رسائل). ابعت \`!gemini send\` أو \`!gemini clear\`.`,
448
+ ),
449
+ },
404
450
  { replyTo: msg },
405
451
  );
406
452
  }
@@ -410,9 +456,12 @@ module.exports = {
410
456
  sock,
411
457
  chatId,
412
458
  {
413
- text:
459
+ text: tr(
460
+ "The context is too big, or too many contexts are open. " +
461
+ "Send `!gemini send` or `!gemini clear` and try again.",
414
462
  "الـ context كبير جدًا أو عدد الـ contexts المفتوحة وصل للحد. " +
415
- "ابعت `!gemini send` أو `!gemini clear` وحاول تاني.",
463
+ "ابعت `!gemini send` أو `!gemini clear` وحاول تاني.",
464
+ ),
416
465
  },
417
466
  { replyTo: msg },
418
467
  );
@@ -422,9 +471,12 @@ module.exports = {
422
471
  sock,
423
472
  chatId,
424
473
  {
425
- text:
474
+ text: tr(
475
+ `✅ Added to the context. (Total now: *${stored.length}*)\n\n` +
476
+ "Keep going with `!gemini add ...`, or send it all with `!gemini send`.",
426
477
  `✅ اتضافت للـ context. (إجمالي الآن: *${stored.length}*)\n\n` +
427
- "كمل بـ `!gemini add ...` ، أو ابعت كله بـ `!gemini send`.",
478
+ "كمل بـ `!gemini add ...` ، أو ابعت كله بـ `!gemini send`.",
479
+ ),
428
480
  },
429
481
  { replyTo: msg },
430
482
  );
@@ -437,7 +489,12 @@ module.exports = {
437
489
  sock,
438
490
  chatId,
439
491
  {
440
- text: had ? `🗑️ تم مسح *${had}* رسالة من الـ context.` : "📭 الـ context كان فاضي أصلاً.",
492
+ text: had
493
+ ? tr(
494
+ `🗑️ Cleared *${had}* messages from the context.`,
495
+ `🗑️ تم مسح *${had}* رسالة من الـ context.`,
496
+ )
497
+ : tr("📭 The context was already empty.", "📭 الـ context كان فاضي أصلاً."),
441
498
  },
442
499
  { replyTo: msg },
443
500
  );
@@ -449,7 +506,12 @@ module.exports = {
449
506
  return sendBotMessage(
450
507
  sock,
451
508
  chatId,
452
- { text: "📭 الـ context فاضي. ابدأ بـ `!gemini add ...`." },
509
+ {
510
+ text: tr(
511
+ "📭 The context is empty. Start with `!gemini add ...`.",
512
+ "📭 الـ context فاضي. ابدأ بـ `!gemini add ...`.",
513
+ ),
514
+ },
453
515
  { replyTo: msg },
454
516
  );
455
517
  }
@@ -458,9 +520,15 @@ module.exports = {
458
520
  chatId,
459
521
  {
460
522
  text:
461
- `📋 *الـ context الحالي:* (${buf.length} رسالة)\n\n` +
523
+ tr(
524
+ `📋 *Current context:* (${buf.length} messages)\n\n`,
525
+ `📋 *الـ context الحالي:* (${buf.length} رسالة)\n\n`,
526
+ ) +
462
527
  buf.map((e, i) => summarizeEntry(e, i)).join("\n") +
463
- "\n\nابعت كله بـ `!gemini send` أو امسحه بـ `!gemini clear`.",
528
+ tr(
529
+ "\n\nSend it all with `!gemini send` or clear it with `!gemini clear`.",
530
+ "\n\nابعت كله بـ `!gemini send` أو امسحه بـ `!gemini clear`.",
531
+ ),
464
532
  },
465
533
  { replyTo: msg },
466
534
  );
@@ -480,9 +548,12 @@ module.exports = {
480
548
  sock,
481
549
  chatId,
482
550
  {
483
- text:
551
+ text: tr(
552
+ "📭 The context is empty and `!gemini send` has no text.\n\n" +
553
+ "Start with `!gemini add ...`, or write text with `!gemini send ...`.",
484
554
  "📭 الـ context فاضي ومفيش نص في `!gemini send`.\n\n" +
485
- "ابدأ بـ `!gemini add ...` الأول، أو اكتب نص مع `!gemini send ...`.",
555
+ "ابدأ بـ `!gemini add ...` الأول، أو اكتب نص مع `!gemini send ...`.",
556
+ ),
486
557
  },
487
558
  { replyTo: msg },
488
559
  );
@@ -496,39 +567,66 @@ module.exports = {
496
567
  if (!parts.length && (msg.message?.imageMessage || msg.message?.videoMessage)) {
497
568
  const mediaMessage = msg.message.imageMessage || msg.message.videoMessage;
498
569
  try {
499
- await processIncomingMedia(parts, mediaMessage);
570
+ await processIncomingMedia(
571
+ parts,
572
+ mediaMessage,
573
+ msg.message.imageMessage ? "image" : "video",
574
+ );
500
575
  parts.push({
501
- text: prompt || mediaMessage.caption || "ماذا يوجد في هذه الصورة/الفيديو؟",
576
+ text:
577
+ prompt ||
578
+ mediaMessage.caption ||
579
+ tr("What is in this image/video?", "ماذا يوجد في هذه الصورة/الفيديو؟"),
502
580
  });
503
581
  } catch (error) {
504
582
  logger.error({ err: error }, "Failed to upload media to Gemini.");
505
- return sendBotError(sock, chatId, error, "حصلت مشكلة في رفع الصورة/الفيديو", {
506
- replyTo: msg,
507
- });
583
+ return sendBotError(
584
+ sock,
585
+ chatId,
586
+ error,
587
+ tr("Uploading the image/video failed", "حصلت مشكلة في رفع الصورة/الفيديو"),
588
+ {
589
+ replyTo: msg,
590
+ },
591
+ );
508
592
  }
509
593
  } else if (!parts.length && msg.message?.audioMessage) {
510
594
  try {
511
- await processIncomingMedia(parts, msg.message.audioMessage);
512
- parts.push({ text: prompt || "حلل لي هذا التسجيل الصوتي." });
595
+ await processIncomingMedia(parts, msg.message.audioMessage, "audio");
596
+ parts.push({ text: prompt || tr("Analyze this recording.", "حلل لي هذا التسجيل الصوتي.") });
513
597
  } catch (error) {
514
598
  logger.error({ err: error }, "Failed to upload audio to Gemini.");
515
- return sendBotError(sock, chatId, error, "حصلت مشكلة في رفع التسجيل الصوتي", {
516
- replyTo: msg,
517
- });
599
+ return sendBotError(
600
+ sock,
601
+ chatId,
602
+ error,
603
+ tr("Uploading the recording failed", "حصلت مشكلة في رفع التسجيل الصوتي"),
604
+ {
605
+ replyTo: msg,
606
+ },
607
+ );
518
608
  }
519
609
  } else if (!parts.length && msg.message?.documentMessage) {
520
610
  try {
521
- await processIncomingMedia(parts, msg.message.documentMessage);
611
+ await processIncomingMedia(parts, msg.message.documentMessage, "document");
522
612
  const fileName = msg.message.documentMessage.fileName || "document";
523
613
  const text = prompt || msg.message.documentMessage.caption || "";
524
614
  parts.push({
525
- text: text ? `${text}\n(الملف: ${fileName})` : `حلل/لخّص الملف: ${fileName}`,
615
+ text: text
616
+ ? tr(`${text}\n(File: ${fileName})`, `${text}\n(الملف: ${fileName})`)
617
+ : tr(`Analyze/summarize the file: ${fileName}`, `حلل/لخّص الملف: ${fileName}`),
526
618
  });
527
619
  } catch (error) {
528
620
  logger.error({ err: error }, "Failed to upload document to Gemini.");
529
- return sendBotError(sock, chatId, error, "حصلت مشكلة في رفع الملف", {
530
- replyTo: msg,
531
- });
621
+ return sendBotError(
622
+ sock,
623
+ chatId,
624
+ error,
625
+ tr("Uploading the file failed", "حصلت مشكلة في رفع الملف"),
626
+ {
627
+ replyTo: msg,
628
+ },
629
+ );
532
630
  }
533
631
  } else if (!parts.length && prompt) {
534
632
  parts.push({ text: prompt });
@@ -538,7 +636,12 @@ module.exports = {
538
636
  return sendBotMessage(
539
637
  sock,
540
638
  chatId,
541
- { text: "يرجى كتابة سؤال أو إرسال صورة/فيديو/تسجيل صوتي/ملف مع الأمر." },
639
+ {
640
+ text: tr(
641
+ "Write a question, or send an image/video/voice note/file with the command.",
642
+ "يرجى كتابة سؤال أو إرسال صورة/فيديو/تسجيل صوتي/ملف مع الأمر.",
643
+ ),
644
+ },
542
645
  { replyTo: msg },
543
646
  );
544
647
  }
@@ -550,27 +653,29 @@ module.exports = {
550
653
 
551
654
  if (quotedMsg) {
552
655
  let quotedMediaPart = null;
553
- const quotedText =
554
- quotedMsg.conversation ||
555
- quotedMsg.extendedTextMessage?.text ||
556
- quotedMsg.documentMessage?.caption;
557
-
558
- const mediaInQuote =
559
- quotedMsg.imageMessage ||
560
- quotedMsg.videoMessage ||
561
- quotedMsg.audioMessage ||
562
- quotedMsg.documentMessage;
656
+ // Captions count: "describe this" on a captioned photo should see both.
657
+ const quotedText = visibleText(quotedMsg);
658
+ const mediaInQuote = pickMedia(quotedMsg);
563
659
 
564
660
  if (mediaInQuote) {
565
661
  try {
566
662
  const probeParts = [];
567
- await processIncomingMedia(probeParts, mediaInQuote);
663
+ await processIncomingMedia(probeParts, mediaInQuote.media, mediaInQuote.type);
568
664
  quotedMediaPart = probeParts[0];
569
665
  } catch (mediaError) {
666
+ // Stop here. Carrying on without the media used to post this error
667
+ // AND a second reply from a model that had never seen the photo
668
+ // ("I can't see any image") — two messages, the second one wrong.
570
669
  logger.error({ err: mediaError }, "Failed to process quoted media");
571
- await sendBotError(sock, chatId, mediaError, "حصلت مشكلة في الرسالة المقتبسة", {
572
- replyTo: msg,
573
- });
670
+ return sendBotError(
671
+ sock,
672
+ chatId,
673
+ mediaError,
674
+ tr("There was a problem with the quoted message", "حصلت مشكلة في الرسالة المقتبسة"),
675
+ {
676
+ replyTo: msg,
677
+ },
678
+ );
574
679
  }
575
680
  }
576
681
 
@@ -578,12 +683,18 @@ module.exports = {
578
683
  parts.unshift(quotedMediaPart);
579
684
  if (quotedText) {
580
685
  parts.unshift({
581
- text: `بالاعتماد على هذه الرسالة كمرجع:\n"""\n${quotedText}\n"""\n\n`,
686
+ text: tr(
687
+ `Using this message as a reference:\n"""\n${quotedText}\n"""\n\n`,
688
+ `بالاعتماد على هذه الرسالة كمرجع:\n"""\n${quotedText}\n"""\n\n`,
689
+ ),
582
690
  });
583
691
  }
584
692
  } else if (quotedText) {
585
693
  parts.unshift({
586
- text: `بالاعتماد على هذه الرسالة كمرجع:\n"""\n${quotedText}\n"""\n\nأجب على التالي:`,
694
+ text: tr(
695
+ `Using this message as a reference:\n"""\n${quotedText}\n"""\n\nAnswer the following:`,
696
+ `بالاعتماد على هذه الرسالة كمرجع:\n"""\n${quotedText}\n"""\n\nأجب على التالي:`,
697
+ ),
587
698
  });
588
699
  }
589
700
  }
@@ -595,42 +706,50 @@ module.exports = {
595
706
  sock,
596
707
  chatId,
597
708
  {
598
- text: `خطأ في الإعدادات: مفتاح مزود الذكاء الاصطناعي الحالي (${activeProvider.label || activeProvider.id}) غير معرف — عدّله من لوحة التحكم.`,
709
+ text: tr(
710
+ `Settings problem: no API key is set for the current AI provider (${activeProvider.label || activeProvider.id}) — set it in the control panel.`,
711
+ `خطأ في الإعدادات: مفتاح مزود الذكاء الاصطناعي الحالي (${activeProvider.label || activeProvider.id}) غير معرف — عدّله من لوحة التحكم.`,
712
+ ),
599
713
  },
600
714
  { replyTo: msg },
601
715
  );
602
716
  }
603
717
 
604
- // Everyone the agent needs to know about, plus the ids its role tools act
605
- // on (a mention/reply is how "خلي فلان أدمن" gets resolved).
606
- const contextInfo = msg.message?.extendedTextMessage?.contextInfo;
718
+ // Who the agent acts for: the sender of THIS message, resolved exactly the
719
+ // way the command dispatcher resolves them, and frozen. The tools
720
+ // authorize against it and nothing else — not the quoted message's author,
721
+ // not a name in a web page, not anything the model writes into arguments.
722
+ const caller = await resolveCaller({ msg, sock, groupMetadata, text: body || "" });
607
723
  const agentContext = {
724
+ caller,
725
+ // Infrastructure, not identity: tools that post media (speak, poll)
726
+ // send through the socket this run started with. Who they act for is
727
+ // `caller` and only `caller`.
728
+ sock,
729
+ // What the system prompt tells the model about the conversation.
608
730
  chatId,
609
- senderId,
731
+ senderId: caller.senderId,
610
732
  senderName: userName,
611
- isOwner,
612
- isAdmin: isBotAdmin,
613
- isGroupAdmin,
733
+ isOwner: caller.isOwner,
734
+ isAdmin: caller.isOwner || caller.isBotAdmin,
614
735
  isGroup,
615
- chatName: groupMetadata?.subject || null,
616
- mentionedJids: contextInfo?.mentionedJid || [],
617
- quotedParticipant: contextInfo?.participant || null,
618
- userText: body || "",
736
+ chatName: caller.chatName,
619
737
  };
620
738
 
621
739
  // Mentions/replies are ids the model can't invent — hand them over so
622
740
  // "اعمل الراجل ده أدمن" has something concrete to act on.
623
- const targets = [...(agentContext.mentionedJids || []), agentContext.quotedParticipant].filter(
624
- Boolean,
625
- );
741
+ const targets = [...caller.mentionedJids, caller.quotedParticipant].filter(Boolean);
626
742
  if (targets.length) {
627
743
  parts.unshift({
628
- text: `(معرفات مذكورة في الرسالة: ${[...new Set(targets)].join(", ")})`,
744
+ text: tr(
745
+ `(IDs mentioned in the message: ${[...new Set(targets)].join(", ")})`,
746
+ `(معرفات مذكورة في الرسالة: ${[...new Set(targets)].join(", ")})`,
747
+ ),
629
748
  });
630
749
  }
631
750
 
632
751
  // The one message that will carry the whole run.
633
- const status = await createStatus(sock, chatId, "🤖 جاري التفكير...", {
752
+ const status = await createStatus(sock, chatId, tr("🤖 Thinking...", "🤖 جاري التفكير..."), {
634
753
  replyTo: msg,
635
754
  });
636
755
 
@@ -666,7 +785,12 @@ module.exports = {
666
785
  result = await attempt(cleaned);
667
786
  }
668
787
 
669
- const text = result.text?.trim() || "مفيش رد جه من الموديل. جرّب تصيغ السؤال بشكل تاني.";
788
+ const text =
789
+ result.text?.trim() ||
790
+ tr(
791
+ "The model sent no answer. Try asking another way.",
792
+ "مفيش رد جه من الموديل. جرّب تصيغ السؤال بشكل تاني.",
793
+ );
670
794
  // Appended only when Gemini really grounded the answer on a search —
671
795
  // formatSources() returns "" for an answer the model gave from its own
672
796
  // knowledge, so there is never a Sources block with nothing behind it.
@@ -674,7 +798,10 @@ module.exports = {
674
798
  await status.finish(responseText);
675
799
  } catch (error) {
676
800
  logger.error({ err: error }, "Error in !gemini command");
677
- await status.fail(error, "حصلت مشكلة وأنا بكلم الذكاء الاصطناعي");
801
+ await status.fail(
802
+ error,
803
+ tr("Something went wrong while talking to the AI", "حصلت مشكلة وأنا بكلم الذكاء الاصطناعي"),
804
+ );
678
805
  }
679
806
  },
680
807
  };